Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[Tut] Basic Java (with MapleStory-based examples)

I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
Written by: Deagan Otterspeer
Date: August 2011
Do not re-post this tutorial or pieces of it without providing credits.
If you find anything in this tutorial which you feel needs to be corrected;
Let me know and I will correct it. I'm human.


Chapter 1: Introduction

1.1 Why?
Hi, i've been watching the MapleStory section for a while now and came to the conclusion it's been getting worse and worse; referring to newcomers who have no clue how to work a piece of code and keep on asking questions that could easily be awnsered if some effort for learning was present. So, I decided to write a tutorial for all of them, hoping they all will take the time and effort to read this through diligently.

1.2 The Idea/Goal
My goal is to write such a tutorial, layered with chapters and subchapters, that people who release stuff can now refer to and mention what chapters or subchapters should be familiar to the reader before actually reading the thread. This way I hope to clean up this section from alot of leechers.
I hope the mods will actually adopt their system to it too, when somebody asks something that is already being mentioned in this tutorial, they should be given a warning.

NOTE: This tutorial will not teach you everything you need to know about JAVA but will be just the things that you need (in my opinion) to know your way through the general stuff of coding in Java/OdinMS.
I will not teach you how every single class operates in OdinMS.


Chapter 2: Getting Started

Java is an Object Oriented Programming language (OOP) which basically explains itself; it's a programming language that focusses on objects. I will try to clarify in a bit.

2.1 Abstractions
To be able to code anything in java, you have to be able to think somewhat abstractly; you have to be able to see what kind of properties belong to what kind of object and be able to seperate different objects and their differences.
Example: A character (object in general) in MapleStory has 2 arms, 2 legs, a head and a body (properties). That goes for every character. Not every character is the same level though, or has the same skin color. So character 1 is not identical to character 2 but yet they belong to the object maplecharacter, while they both have their own abstractions.

2.2 Classes, Variables and Methods
To make a source ordened the properties and behaviours of the object with it's different abstractions (the properties of the characters + the things they can do) have to be saved into classes.
To save the properties of the character he uses variables and to save the behaviours he uses methods.
Variables are used to save information in and methos are pieces of code that do something (variables and methods are right now very vaguely described and more will be written about those further into this tutorial but this is purely for understanding the OOP concept).
Example; the developper uses an integer type variable (numerical) to save the level of the character and uses a method called gainMeso() to make the player gain mesos.

2.3 Objects
We can now explain what object oriented means. If you look at maplecharacter as an object, when you use it in your source you can define an object as something that has to be able to show all of the behaviours and properties that are saved in a class.
So java is all about using objects to gather data from different classes and work with them; Object Oriented Programming.


Chapter 3: Java Elements and Structure

3.0.1 Declarations
Before even being able to start working with java elements (classes, variables, methods and objects) you will need to declare them.
Because of that I will show you how to declare java elements before actually describing the elements seperately.

The construction of a declaration is as follows:
Code:
<accessibility modifier(s)> <element type> <name>

You don't always just have access to every class and it's variables and methods, the traffic of java is being taken care of by accessibility modifiers.

- There are 3 accessability modifiers that take care of the visibility out of other classes:
Accessibility Modifiers for Visibility
  • public;
    When the modifier is used for a:
    class: the class is accessible from everywhere. (even outside of packages; the directory you added the class in)
    variable: same thing but for variables.
    method: same thing but for methods.
  • protected;
    When the modifier is used for a:
    class: doesn't happen. (modifier is never used for classes)
    variable: only accessible to classes of the same package.
    method: same thing as variables but for methods.
  • private;
    When the modifier is used for a:
    class: doesn't happen. (modifier is never used for classes)
    variable: only accessible to the class it is declared in.
    method: same thing as variables but for methods.
Many people wonder why in MapleCharacter most variables are declared as private instead of just public.
Quote from (thanks Flav) :
"Deciding when to use private, protected, or public variables is sometimes tricky. You need to think whether or not an external object (or program), actually needs direct access to the information. If you do want other objects to access internal data, but wish to control it, you would make it either private or protected, but provide functions which can manipulate the data in a controlled way."

Just picture it as someone inputting data that is improper into a maplecharacter variable for now to visualise the idea of "security" in this matter. You could add a check into a method to prevent improper input.
Next to being able to control the data that's been changed securely some also state it's better for performance since it only calls the private variable upon invoking the method and doing such would save performance. (just imagine if java would have to save a variable as public to every other class instead of just one, looks like some difference somewhere but shouldn't really be a reason to use one or another)
Oh and some people think it looks cleaner to do it with methods.​

- There are 4 accessability modifiers that take care of the behaviour in reference to objects (I won't be looking at the "native" one but just for you to know it exists):
Accessibility Modifiers in Reference to other Objects
  • static;
    When the modifier is used for a:
    class: doesn't happen.
    variable: the variable is the same for every instance of the class. (i'm aware of the fact that you most of you guys don't know what an instance or reference is yet so just picture this as "if you were to make level in maplecharacter static every player's level would be the same")
    method: same thing as variables but for methods.
  • final;
    When the modifier is used for a:
    class: the class is unexpandable.
    variable: the value of the variable can't be changed; constant.
    method: method can't be overrided by a subclass.
  • abstract (take it easy :D);
    When the modifier is used for a:
    class: class can contain abstract methods and can't be instanced as an object. It can be extended to a subclass though.
    variable: impossible.
    method: the method is an interface (I know, but I don't think I will be telling you guys about interfaces so just let this be for now), if there is 1 abstract method the class automatically needs to be abstract aswell.
If I recall correctly it was once rumored that CelinoSEA was as stable as it was because they declared alot of things final when possible. It would have improved performance, or memory usage, I believe in such way it become really stable. I don't believe anything of this since a stable server basically means no memory leaks and deadlocks. More about those later.

- There is also 1 accessibility modifier (not taking into consideration "strictfp", "transient" and "volatile" that takes care of the behaviour of a method during runtime (running the server):
  • synchronize; the method can be invoked once at a time, aka it behaves singlethreaded instead of multithreaded.
    Be warned though, this does not always prevent deadlocks.
    In fact, I heard that using it too much creates way more of them, thus; using reentrantlock is more efficient to use when trying to prevent deadlocks. I will try my best to explain what memory leaks and deadlocks are near the end of this tutorial.

NOTE: some of these accessibility modifiers can be combined but not every combination is possible. I honestly can't be bothered to type them all out; netbeans or your IDE will let you know ^_^.
Oh, and for the name of the declaration, you will know how to give it a proper name as it is often logic sense. Next to that your IDE will tell you when you can't use a name while declaring aswell. Just make sure to stay ordered as a coder.

3.1 Elements

So now you guys actually know how to declare something we will be talking about the different elements that you can declare (classes, variables, methods and objects).
In this chapter I am assuming you generally understand what each of these elements is used for. (the maplecharacter example; "Getting Started")

NOTE: every example I use, or most of them, are written by me and it is possible there are mistakes in them.. although I hope not. Please let me know if there is false information provided anywhere in my tutorial and I will correct it. I am human.
Next to that, these codes written by me do not have to be used in any piece of code (in OdinMS-based sources) or work the same way as they do in OdinMS (especially not my maplecharacter examples);
@purpose to clarify.

3.1.1 Structure
To be able to understand how the pieces of code came into existence you will need to know something about the general java structure.

In the process of coding anything, it is often usefull to leave notes behind in your code so you know exactly why you added a piece of code or left it out; comments.
To leave a comment that only occupies one line of java code you simply add "//" before the comment you want to make about something and to leave a comment that takes up a couple of lines you simply open the piece of comment with "/*" and close it with "*/".
Some developpers also include information in their code about the author of a piece of code or the purpose of it ect (Javadoc comments).
It will look something like this:
Code:
/**
 *
 * @author Deagan
 * @purpose showing RaGEZONE how to add comments before using examples with them.
 */

The java developper has some rules to keep himself/herself to.
When declaring a variable or method you always add opening and closing brackets, "{" and "}", to indicate where the piece of code starts and ends. When declaring methods you also always need to add brackets, "(" and ")", to be able to give the method an input to work with. (further explained in Elements.Methods ^_^)
Last thing you should mind right now is that, unlike in JavaScript, semicolons (";") are needed after every line to let the java code know where the line ends.
You will see what I mean by this as you look at some examples I will include.

3.1.2 Classes
So now we know how to declare something, we want to create a class to save information about an object in so it can be used by other classes if necessary.

So let's grab the standard model for declaring elements and declare a class which will (later on) include information about a character in MapleStory:

Code:
/**
 * @Author Deagan
 * @Purpose showing RaGEZONE how to declare a class.
 * Creates a class that is accessible from every other class in every package.
 * The package simply shows in which directory the class will be saved,
 * so for this example let's save it into a folder called "examples"
 * we created in another folder called "deagansJavaTut". (case sensitive)
 */

package deagansJavaTut.examples;

// This class will also be accessible from other directories in the deagansJavaTut folder. [B]public[/B]
public class MSCharacter {
}

Normally, when declaring a class, you also declare a constructor which is the method that's invoked first when creating an object out of the class. It is not necessary to declare one but it is proper to; the compiler will create an empty constructor itself anyhow. (more about the constructor in Elements.Methods ^_^)

3.1.3 Variables
To record properties of a character in MapleStory the class uses variables. After the variables has been declared it is still empty, which means it has no value yet (which is not the same as "null" as value, what this means will be explained when I speak about instances).
Giving it a value is called initializing. Working with unitialized datatypes most oftenly will return in java working with the standard value the variable has.
For now I will describe the variables, sometimes also refered to as datatypes, that are most used in OdinMS (and in particular MapleCharacter); numeric/integer type (byte, short, int and long), boolean, floating-point type and the character type.

When initializing variables, you also consume a piece of the memory, wether that is heap or stack isn't really of importance for now but might become interesting later on when I write about deadlocks and memory leaks (the main issues OdinMS has).
The computer's memory consists of bits, which contain a value of "enabled" or "disabled". The computer works with sets of these on and off switches and uses the binary system to work with values. I will not completely explain how that system works apart from it working with powers of 2. If you really want to know find out yourself, it's not really important in this tutorial.

3.1.3.1 Numeric/Integer Type
The integers form the type of variables that save numeric values.
The only difference between these different datatypes is the amount of memory that they consume, which is for proper coding rather important but not so much for basic coding stuff in OdinMS. Yet I still believe taking in consideration what amount of memory a variable will consume is very important.
  • byte
    bits (consumed): 8
    minimum value: -(2^7) / -128
    maximum value: (2^7)-1 / 127​
  • short
    bits (consumed): 16
    minimum value: -(2^15) / -32768
    maximum value: (2^15)-1 / 32767​
  • int
    bits (consumed): 32
    minimum value: -(2^31) / -2147483648
    maximum value: (2^31)-1 / 2147483647​
  • long
    bits (consumed): 64
    minimum value: -(2^63) / -9223372036854775808L
    maximum value: (2^63)-1 / 9223372036854775807L​
    Don't miss out the "L" behind the values for longs, you have to include this after it for java not to throw an out of range error when it goes above 2147483647 or below -2147483648. (it automatically casts it to an int without the L)
The reason why every positive value is -1 is because the value 0 counts as a positive value aswell.

The standard value of an integer type variable is 0.
So when you leave this variable uninitialized it will work with the value of 0.

Something that might be interesting to know about these datatypes is that when you use a byte, short or long to do calculations with in the source, java automatically makes an int out of them because java works faster when using an int.
This "making" of an int is an example of casting other datatypes.
Casting a variable to another datatype takes up relatively much effort from the processor so it will slow down performance(the speed of the processes of in this case OdinMS); which is the reason many people prefer simply using an int to save even small values in if they know it will be used for calculations. (they sacrifice a few bits for performance)
However, this is a personal descision and it's up to you wether you prefer saving up memory or improving performance.

3.1.3.2 Boolean Type
A boolean type variable is a variable which can only contain the value true or false, which brings me back to the way memory in a computer works; a computer works with on and off switches.

The standard value of a boolean is false.
The amount of memory a boolean uses isn't certain, but if you own a computer and JVM that allows writing bits to the memory it will only be one bit; otherwise it will just be 1 byte - 8 bits.
Some people claim that some people actually write seperate bits to a byte untill it's filled fo, just to come to a conclusion,
I would simply say that it ranges from 1-8 bits. :)

3.1.3.3 Floating-point Type
Floating-point type variables are variables that can hold broken numeric values (ex; 0.00 and 0.5).
  • float
    bits (consumed): 32
    minimum value: 1.401298464324817^(-45)f
    maximum value: 3.4028234663852886^(38)f​
  • double
    bits (consumed): 64
    minimum value: 1.7976931348623157^(308)
    maximum value: 4.9^(-324)​

    If you want a variable to stay a float or double even whent he value is non-broken you have to add an "f" or "d" behind the value. Also, if you don't add an "f" behind a broken value java will automatically cast it into a double.
    The standard value of a float is +0.0F and the standard value of a double is +0.0D.

    The minimum and maximum values are the same for positive and negative values.
    The nonzero values for floats and doubles are different apparantly so you can look them all up here if you're interested:
3.1.3.4 Character Type (and Strings)
The char datatype is capable of holding 65536 (2^16) different Unicode characters, however, only one at a time.
So basically, just one letter.
This variables takes up 16 bits and you can initialize them by typing the letter you want to save or the with-the-letter-belonging Unicode code.
You can find the codes here:


In OdinMS, there are often times you need to save more than 1 letter into a variable. For this reason, there are strings.
Strings are not variables though, but Objects.
It is possible to initialize them like the other datatypes though.

Example
So now we know these datatypes we can grab the standard model of the class we created and include some variables to show their use and behaviour.

Code:
/**
 * @Author Deagan
 * @Purpose showing RaGEZONE how to declare a class with some public variables in it.
 */

package deagansJavaTut.examples;

// This class will also be accessible from other directories in the deagansJavaTut folder. public
public class MSCharacter {

// Leaving the constructor out untill we've had the methods subchapter

    // Integers
    public byte GMLevel;
    public short str; // OdinMS has short.max as max value for stats :)
    public short int_; // the name can't be int as it's a keyword
    public int exp;
    public long time = System.currentTimeMillis();

    // Boolean
    public boolean isGM; // we will soon be able to use a method to find out weither someone is a GM or not ^_^

    // Floating-point types
    public float expDecreasementFactor = 0.5f;
    public float expDecreasementFactorTwo = 0f; // not adding the "f" should give error in netbeans
    public double bigFactorForSomethingRandom = 0D; // same thing ^
    public double bigFactorForSomethingRandomTwo = 83427.73;

    // Char and String
    public char H = '\u004f';
    public char O = '\u0073';
    public char T = '\u0069';
    public char G = '\u0072';
    public char U = '\u0069';
    public char Y = '\u0073';
    String nawb = "Deagan";
    String loveRelationship = Character.toString(H) + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y) + " <3 " + nawb;
    String potentialName = "Deag" + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y);
    

}

3.1.4 Methods
Methods are pieces of code that can be referred to inside of the class or outside of it. (in the form of objects)
When declaring methods, the element type describes what kind of an awnser the method should give when being referred to, to return.
Only a void type of method does not need to return a value.

When declaring a method you need to include brackets "()" behind the name. This is done to allow possible input the java code can work with in the process of returning a value or simple executing something when using a void.
When you want the method to work with data which you include manually, you will have to add parameters. Parameters are basically used to provide the method of data with which it can work.
Methods with the same name but with different parameters are NOT the same method. Creating methods with different parameters but the same name is called method overloading.
It's possible to include objects as parameters.

So now we could actually include some simple methods including the constructor which I have been leaving out not to confuse all of you. Like I wrote before, the constructor is usually the first method that is automatically called when using an object of the class.

Example
The model class we created is beginning to get some shape,
yet I can not yet start elaborately declaring methods since I haven't teached you guys how assigning and operators in general work.

Code:
/**
 * @Author Deagan
 * @Purpose showing RaGEZONE how to declare a class with some public variables and methods in it.
 */

package deagansJavaTut.examples;

// This class will also be accessible from other directories in the deagansJavaTut folder. public
public class MSCharacter {

    // Integers
    private byte GMLevel;
    private short str; // OdinMS has short.max as max value for stats :)
    private short int_; // the name can't be int as it's a keyword
    private short level;
    private int exp;
    private long time = System.currentTimeMillis();

    // Boolean
    private boolean isGM; // we will soon be able to use a method to find out weither someone is a GM or not ^_^

    // Floating-point types
    private float expDecreasementFactor = 0.5f;
    private float expDecreasementFactorTwo = 0f; // not adding the "f" -> netbeans makes into double
    private double bigFactorForSomethingRandom = 0d; // same thing ^
    private double bigFactorForSomethingRandomTwo = 83427.73;

    // Char and String
    public char H = '\u004f';
    public char O = '\u0073';
    public char T = '\u0069';
    public char G = '\u0072';
    public char U = '\u0069';
    public char Y = '\u0073';
    String nawb = "Deagan";
    String loveRelationship = Character.toString(H) + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y) + " <3 " + nawb;
    String potentialName = "Deag" + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y);
    
    /*LOL don't mind this <333
     * public static void main(String [] args) {
        char H = '\u004f';
        char O = '\u0073';
        char T = '\u0069';
        char G = '\u0072';
        char U = '\u0069';
        char Y = '\u0073';
        String nawb = "Deagan";
        String loveRelationship = new String();
        String potentialName = loveRelationship;
        loveRelationship = Character.toString(H) + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y) + " <3 " + nawb; // Shut up. DeagSiris for legal java acception!
        potentialName = "DeagSiris";
        System.out.print(loveRelationship + "\r\n");
        System.out.print("Potential name:\r\n" + potentialName + "\r\n\r\n");
    }*/
    
    // Constructor - set some standard values - nvm untill operators chapter ^_^
    public MSCharacter() {
        this.level = 1; // level is never 0 when you start off
        this.str = 4;
        this.int_ = 4; // stats start off with 4
    }

    // Constructor overload - 3 parameters
    public MSCharacter(short strength, short intelligence, short level) {
        this.str = strength;
        this.int_ = intelligence;
        this.level = level;
    }

    public short getLevel() {
        return level;
    }
    
    public boolean isGM() {
        return this.isGM;
    }
    
    public String getPotentialName() {
        return this.potentialName;
    }

}

3.1.5 Objects/Instances/References
When an object is declared in the shape of a variable it is called an instance. The variabjale itself is then called a reference.
After instantiating this object you use it to call methods and eventually public variables from.
This "calling" of methods and variables is called invoking.

Something I kept doing wrong all the time was trying to assign values to variables and reference variables while in the global part of the code.
This is not possible, you can only work with the variables when you're in a method.
For that same reason, my final example will just include the main method the Java Virtual Machine executes when running the program. I really doubt you will mess up though in public java sources and won't really run against any problems declaring an instance and instantiating it.

Declaring an instance can be done on 2 seperate ways:
Code:
MSCharacter chr; // declare reference but it is still empty
chr = new MSCharacter(); // instantiate it/initialize it :)

or

MSCharacter chr = new MSCharacter(); // both at once
The first thing the instance does is call the constructor method in the class you're trying to assign to a reference variable.
So when you have multiple constructors with different parameters, it is possible to create an instance which sets the values of some variables in your main class to something different than it would normally do.

Code:
MSCharacter chr = new MSCharacter(/* level */ 255, /* str */ 32767, /* int */ 32767); // creates a char which is level 255 and has maxed out strenth and intelligence.

After you instantiated the object you can now invoke the public methods and variables from it. For example:
Code:
MSCharacter chr = new MSCharacter(/* level */ 255, /* str */ 32767, /* int */ 32767); // creates a char which is level 255 and has maxed out strenth and intelligence.
int level = chr.getLevel(); // ofcourse it will return 255... but still


Chapter 4: Working with Data

We've learned how to declare variables, methods and instances untill now but just adding those isn't all that has to be done to create a piece of code that actually works.
In this chapter you will learn how to work with variables, methods and instances so that you can actually create features in your source that are properly coded.

Before we can do any of these you have to actually know how calculations and comparisons are performed in java; with operators. It's basically working with all of the datatypes from the elements chapter without us talking about the way the java code progresses yet (java flow control).

4.1 Operators
So, java uses operators to perform actions on the datatypes mentioned in the elements chapter. There are quite a few operators and I will explain most of them and their use.
Before doing that though, you should notice that operators, just like with maths, have precedences; meaning they don't just work from the left to the right but some calculations are done before the others just like how multiplying someone goes before adding and substituting.

Here's a list of the java operator precedences:
Code:
Operators	Precedence
postfix		expr++ expr--
unary		++expr --expr +expr -expr ~ !
multiplicative	* / %
additive	+ -
shift		<< >> >>>
relational	< > <= >= instanceof
equality	== !=
bitwise AND	&
bitwise exclusive OR	^
bitwise inclusive OR	|
logical AND	&&
logical OR	||
ternary		? :
assignment	= += -= *= /= %= &= ^= |= <<= >>= >>>

Source: http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
These operators are listed by presedence from top to bottom so the top one goes before the ones below it.

There are several types of operators; assignment operators(general, arithmatic and boolean), increment and decrement operators, arithmatic operators, boolean and conditional operators, relational operators (general and equality) and the class and array operators.

4.1.1 Assignment Operators
When you want to assign a value to a variable you will need an assignment operator. The general assignment operator is "=" and is used as the bridge between the variable and the expression; the maths that result in the value that the variable will be given.

Code:
variable = expression;
private int level = expression;

There are also arithmetic operators that immediately allow you to do some maths with the current numeric value of the variable in the expression. The arithmetic assignment variables are "*=","/=", "%=", "+=" and "-=".

Here's an example on how they work:
Code:
int i = 5;
i *= 3; // the value of i now becomes 3 x 5 = 15
i /= 5; // i = 15 / 5 = 3
i %= 2; // i = 3 modulo 2 = the rest that comes out when you can't devide 3 by 2 anymore = 3/2 = 1 plus 1 rest. the 1 rest is the value for i. a second example is 9 mod 4 = 1.
i += 9; // i = 10
i -+ 10; // i = 0
So you can conclude from this that arithmetic assignment operators basically work as i = i + 9; (when using i += 9;)
It won't be hard for you to understand the arithmetic operators in general now but who cares, I really needed to discuss the general assignment operators first.

For boolean variables there are boolean assignment operators.
These are "&=", "^=" and "|=". They work the same as as the other assignment variables; x &= y is the same as x = x & y.
Here are some examples working with boolean assignment operators, you will understand boolean operators in general easily after this too:
Code:
boolean x = true;
boolean y = false;
boolean x2 = false;
boolean y2 = true;

x &= y; // if boolean x and boolean y are both true it assigns a "true" value to x -> assigns a false
x &= y2; // x and y2 are both true so it will return with "true"

x ^= y; // if only ONE of the 2 is two it returns with "true" -> in this case it's true
x ^= y2; // both are true so not just one of them -> return false;
x2 ^= y; // false
x2 ^= y2; // true

x |= y; // if at least one of the 2, or both, are true it returns true. true.
x |= y2; // true
x2 |= y; // false
x2 |= y2; // true

4.1.2 Increment and Decrement Operators
The increment and decrement operators "++" and "--" come in two shapes; postfix and prefix.
Both of them cause an increase or decrease of the numeric value of the variable by 1.

Postfix:
Code:
int level = 199;
int oldlevel;

oldlevel = level++; // level is now 200 but random is 199.

Prefix:
Code:
int level = 199;
int whatlevel;

whatlevel = ++level; // both whatlever and level are 200 now.
4.1.3 Boolean and Conditional Operators
The boolean operators "!", "&", "^" and "|" are to be applied to boolean variables and they return with another boolean value.
Code:
boolean x = true;
boolean y = false;

boolean new = !x; // returns the opposite value of x - false
new = !y; // true

new = x & y; // if both are true return true, otherwise - false
new = (x) & (!y); // true

new = x ^ y; // if one of them is true but the other isn't - true
new = y ^ (!x); // false
new = x ^ (!y); // false

new = x | y; // if at least one is true, or both are true - true
new = x | (!y); // true
new = (!x) | (!y); // true
new = (!x) | y; // false;

Conditional operators work the same way as boolean operators apart from the fact that the conditional operator "&&" already stops when the first operand is false and that the conditional operator "||" already stops when the left operator is true.

What this is usefull for will be explained in chapter 5.

Code:
boolean x = true;
boolean y = false;

boolean new = x && y; // returns false but didn't stop evaluation untill second operand was checked too because x was true
new = y && x; // returns false but already stopped evaluating when it found out y = false, so it never checked x.
new = x || y; // returns true but already stopped evaluating when it found out x is true.
new = y || x; // returns true but didn't stop evaluating cuz y is false.

Last but not least of the conditional operators there is the conditional if-else operator.
The structure of this operator is and works as follows:
Code:
variable = boolean ? expression1 : expression2;
// if the boolean is true it assigns expression1 to the variable,
if it is false it assigns expression2.
boolean x = true;
boolean y = false;
int i = x ? 0 : 1; // returns 0 because x is true
int i = y ? 0 : 1; // returns 1

4.1.4 Relational Operators
The relational operators "<", "<=", ">" and ">=" can be used on numeric variables and they return with a boolean.

Code:
int x = 0;
int y = 1;
int a = 1;

boolean new = (x < y); // x is smaller than y so it returns true
new = (y < a); // returns false because y is not smaller than a, they are equal

new = (x <= y); // true
new = (y <= a); // true because y is either smaller than a or equal to a. it is equal in this case.

same way around for ">" and ">=" but then bigger and bigger or equal

Next to these general relational operators there are also relational equality operators. The relational equality operators "==" and "!=" are used when you want to compare 2 operands. It doesn't matter what kind of datatypes they are because these can be applied to objects aswell. They return a boolean awnser; "==" return true when both operands are equal and false if not, "!=" returns true when they are unequal, false if they are equal.

Code:
int x = 0;
int y = 1;
int a = 1;

MSCharacter chr = new MSCharacter();
MSCharacter chr2 = new MSCharacter();
MSCharacter chr3 = chr2;

boolean b = (x == y); // returns false because x is not equal to y
b = (x != y); // true because they are not equal
b = (y == a); // true because y and a are equal

b = (chr == chr2); // false because they are 2 different instances
b = (chr2 == chr3); // true, same instance

4.1.5 Array and Class Operators
These two types of operators were left so I thought I would explain them in the end.
The array operator "[]" lets us know that the variable it is used on is an array. An array is a group of seperate values saved into one variable. This is often done because the values have something in common. It is also possible to include objects into arrays but that is not recommended as there are collections and maps which provide many usefull functions. More about collections and maps in the advanced chapter.
There are two ways to declare an array:
Code:
int[] itemids = new int[3];
// you need to provide the array of the size it is going to be when you only declare and initialize the variable integer as an array, but not yet have initialized the array.
itemids[0] = 1000001; // array indexes always start at 0 which is a positive number that counts
itemids[1] = 1000002;
itemids[2] = 1000003; // initialize the array at index 2 with value 1000003

or

int[] itemids = {1000001, 1000002, 1000003}

There are also a few class operators, some of which we have already discussed; "new Class", "instanceof Class", "(SubClass)" and ".".

WWe already talked about "new Class" and (invoking) ".".
With the instanceof class operator we can check if a reference-variable contains an instance of the given class.
With the (SubClass) operator we can cast an upper class to a subclass. More about this in the advanced chapter.

Code:
MSCharacter chr = new MSCharacter();

int x = (chr instanceof MSCharacter) ? 0 : 1;
// if chr is an instance of MSCharacter is returns 0, if not 1

4.2 Java Flow Control
Now you know how to actually perform operations on the datatypes with operators it is time for us to apply some of them in systems which include checking of input and performing calculations with it.
Java gives the developper the possibility to change the flow of the java code by allowing him/her to make the code make choices for itself, request repetitions and provide information to other parts of the statement/method. To do this the developper uses statements.
There are three types of statements; selection statements (to make the java code make descisions by itself), iteration statements (to make the java code request repetitions) and transfer statements (which makes the java code control itself even withing statements and methods).

Being familiar with these statements is essential when working on a source; without them, you have no clue what the java code is doing by itself and makes it extremely hard (if the code is big) for you to find out where the issue is. A good developper controls his code, or actually makes it control itself.

4.2.1 Selection Statements
So up first are the statements that make the java code make it's own descisions upon running the program.
There are 3 selection statements; the if statement, the if-else statement and the switch statement.

If statement:
Code:
if (boolean) {
    // piece of code to be executed if boolean is true
}

If-else statement:
Code:
if (boolean) {
    // piece of code to be executed if boolean is true
} else {
    // piece of code to be executed if boolean is false
}

Switch statement:
Code:
switch (numeric datatype) {
    case number1:
        // piece of code to be executed if the value of the case matches with the numeric datatype - numeric datatype = number1
        break;
    case number2:
        // piece of code to be executed when numeric datatype = number2
        break;
    ect... untill (optional)
    default:
        // piece of code to be executed when the numeric datatypes matches with none of the numbers from the cases
        break; // more about break in the transfer statements
}

4.2.2 Iteration Statements
Second up are the iteration statements, the statements that request the java code for repititions of a piece of code.
There are 3 iteration statements; while, for and do-while.
They all work with the same concept; every single one of these pieces of code shape statement blocks of code (loop body) of which the content is being repeated untill the awnser to the boolean (loop condition) is false.
The while and for statements work by checking the boolean before executing the piece of code inside the loop body, the do-while statement checks after executing it.

While statement:
Code:
while (loop condition) {
    // piece of code to be executed as long as loop condition returns true
}

public void remove3PetsWhile() {
        int amountOfPetsOut = 3; // normale you use a .size() to find out but just for the example...
        while (amountOfPetsOut > 0) {
            System.out.print("Pet #" + amountOfPetsOut + " will be removed;\r\n");
            amountOfPetsOut--; // symbolizes removing pets LOL
            System.out.print(amountOfPetsOut + " pets still out.\r\n");
        }
    }

For statement :
Code:
for (var initialization, loop condition, expression) {
    // piece of code to be executed when loop condition is true, after this the expression is assigned to the var of initialization
}

public void remove3PetsFor() {
        for (int amountOfPetsOut2 = 3; amountOfPetsOut2 > 0; amountOfPetsOut2--) {
            System.out.print("Pet #" + amountOfPetsOut2 + " has been removed;\r\n");
            //System.out.print(++amountOfPetsOut2 + " pets still out.\r\n"); example for infinite loop
            System.out.print(amountOfPetsOut2 - 1 + " pets still out.\r\n");
        }
    }

For statement for arrays :
Code:
for (declaration : initialization with array) {
    // piece of code to be executed for every value that's inside the array you initialized the var for the loop loop with
}

public void remove3PetsForArray() {
        int[] pets = {2, 1, 0};
        for (int petid : pets) {
            System.out.print("Pet #" + (petid + 1) + " will be removed;\r\n");
            pets[petid] = 0; // just imagine it being an instance that gets emptied or pet gets pulled back into it's house
            System.out.print(petid + " pets still out.\r\n");
        }
    }

Do-while statement:
Code:
do {
 // piece of code to be executed before checking the boolean
} while (loop condition);

4.2.3 Transfer Statements
Last up of the statements are the transfer statements. These statements take care of the behaviour of the java code within methods and statements.
There are 3 transfer statements; "break", "continue" and "return";

Break:
You can use the "break" transfer statement to jump out of the "switch" selection statement and all of the iteration statements.
Code:
public void undressPlayerBreak() {
        int amountOfEquips = 14; // let's say player has 20 slots and wears 14 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("Break at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\n");
                break; // change it into return and see what happends later!
            }
            System.out.print("Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }

Continue:
We use continue when we want to skip a loop for once; concluding that it can only be used in iteration statements. When we count the amount of party members in a party and one of them is at another map than the rest the member is skipped. So if there are 6 party members and #5 is at another map, i = 5 is being skipped and not counted; when warping someone in a pq for example.
Code:
public void warpPartyMembers() {
        // gather all members in the map then send them to another map - in the most non literal sense
        for (int member = 0; member < 6; member++) {
            if (member == 3) {
                System.out.print("      Member #" + (member + 1) + " is at another map than the rest of the party.\r\n      The 5 other members can be warped in but #" + (member + 1) + " will have to be skipped.\r\n");
                continue;
            }
            System.out.print("  Warping party member #" + (member + 1) + " into the PQ.\r\n");
        }
    }

Return:
We use the return transfer statement to return a value to the method.
When you return a value in a method the rest of the method isn't being executed anymore so it is closed instantly.
The value you return has to be the same as the element type of the declaration of the method; except for void type methods.
Code:
public void undressPlayerReturn() {
        int amountOfEquips = 6; // let's say player has 20 slots and wears 6 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("Return at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\nPlayer is naked. Jump out of the method undressPlayerReturn.\r\nMessage out of the for loop was never dropped.\r\n");
                return; // change it into return and see what happends!
            }
            System.out.print("Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }

Example
After all of this information we can put together a script that will later be executed when we learn how to run our program and how to deal with errors that java may print out.
This example does not contain an example of everything we've discussed but I would say it's still a pretty elaborate example; display character info, gaining exp and leveling up (multilevel explained), checking if someone is a gm or not, undressing the player, warping all party members except 1 that is at another map and removing pets.
Code:
/**
 * @Author Deagan
 * @Purpose showing RaGEZONE how to create a class with general systems ect to teach RZ how java works; especially in MS-based sources.
 */

package deagansJavaTut.examples;

// This class will also be accessible from other directories in the deagansJavaTut folder. public
public class MSCharacter {

    // Integers
    private byte GMLevel = 2;
    private short str; // OdinMS has short.max as max value for stats :)
    private short int_; // the name can't be int as it's a keyword
    private short level;
    public long time = System.currentTimeMillis();
    private int exp;

    // Boolean
    private boolean isGM; // we will soon be able to use a method to find out weither someone is a GM or not ^_^

    // Floating-point types
    private float expDecreasementFactor = 0.5f;
    private float expDecreasementFactorTwo = 0f; // not adding the "f" -> netbeans makes into double
    private double bigFactorForSomethingRandom = 0d; // same thing ^
    private double bigFactorForSomethingRandomTwo = 83427.73;

    // Char and String
    public char H = '\u004f';
    public char O = '\u0073';
    public char T = '\u0069';
    public char G = '\u0072';
    public char U = '\u0069';
    public char Y = '\u0073';
    String nawb = "Deagan";
    String loveRelationship = Character.toString(H) + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y) + " <3 " + nawb;
    String potentialName = "Deag" + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y);
    
    // Constructor - set some standard values - nvm untill operators chapter ^_^
    public MSCharacter() {
        this.level = 1; // level is never 0 when you start off
        this.str = 4;
        this.int_ = 4; // stats start off with 4
    }

    // Constructor overload - 3 parameters
    public MSCharacter(int strength, int intelligence, int level, int GMLevel) {
        this.str = (short) strength;
        this.int_ = (short) intelligence;
        this.level = (short) level;
        this.GMLevel = (byte) GMLevel;
    }

    public short getLevel() {
        return level;
    }
    
    public int getExp() {
        return exp;
    }
    
    public void gainExp(int gainexp) {
        // decrease amount of gained exp with float factor
        if (expDecreasementFactor != 0) {
            gainexp *= expDecreasementFactor;
            //gainexp = gainexp * expDecreasementFactor;
        }
        while (gainexp >= 200) { // levelup every 200 exp
            levelUp();
            gainexp -= 200;
        }
        exp = gainexp;
    }
    
    public void levelUp() {
        level++;
    }
    
    public short getStr() {
        return str;
    }
    
    public short getInt() {
        return int_;
    }
    
    public boolean isGM() {
        if (GMLevel != 0) {
            return true;
        } else {
            return false;            
        }
    }
    
    public String getPotentialName() {
        return this.potentialName;
    }
    
    public void remove3PetsFor() {
        for (int amountOfPetsOut2 = 3; amountOfPetsOut2 > 0; amountOfPetsOut2--) {
            System.out.print("  Pet #" + amountOfPetsOut2 + " has been removed;\r\n");
            //System.out.print(++amountOfPetsOut2 + " pets still out.\r\n"); example for infinite loop
            System.out.print("  " + (amountOfPetsOut2 - 1) + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsWhile() {
        int amountOfPetsOut = 3; // normale you use a .size() to find out but just for the example...
        while (amountOfPetsOut > 0) {
            System.out.print("  Pet #" + amountOfPetsOut + " will be removed;\r\n");
            amountOfPetsOut--; // symbolizes removing pet
            System.out.print("  " + amountOfPetsOut + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsForArray() {
        int[] pets = {2, 1, 0};
        for (int petid : pets) {
            System.out.print("  Pet #" + (petid + 1) + " will be removed;\r\n");
            pets[petid] = 0; // just imagine it being an instance that gets emptied or pet gets pulled back into it's house
            System.out.print("  " + petid + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsDoWhile() {
        int amountOfPets3 = 3;
        do {
            System.out.print("  Pet #" + amountOfPets3 + " will be removed;\r\n");
            amountOfPets3--; // symbolizes removing pet
            System.out.print("  " + amountOfPets3 + " pets still out.\r\n");
        } while (amountOfPets3 > 0);
    }
    
    public void undressPlayerBreak() {
        int amountOfEquips = 14; // let's say player has 20 slots and wears 14 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("  Break at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\n");
                break; // change it into return and see what happends later!
            }
            System.out.print("  Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("  The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }
    
    public void undressPlayerReturn() {
        int amountOfEquips = 6; // let's say player has 20 slots and wears 6 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("  Return at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\nPlayer is naked. Jump out of the method undressPlayerReturn.\r\nMessage out of the for loop was never dropped.\r\n");
                return;
            }
            System.out.print("  Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("  The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }
    
    public void warpPartyMembers() {
        // gather all members in the map then send them to another map - in the most non literal sense
        for (int member = 0; member < 6; member++) {
            if (member == 3) {
                System.out.print("      Member #" + (member + 1) + " is at another map than the rest of the party.\r\n      The 5 other members can be warped in but #" + (member + 1) + " will have to be skipped.\r\n");
                continue;
            }
            System.out.print("  Warping party member #" + (member + 1) + " into the PQ.\r\n");
        }
    }
}


Chapter 5: Running Your Program & Exception Handling
Now this chapter will be rather important for those who are interested in bat errors and the reasons they exist.
The code we are using as an example is starting to get big and there might occur errors in executign it so we should really look into it and see if we can catch the possible exceptions that may occur and work with them/print them out to the bat.

5.1 Running Your Program
Before looking into the errors though it might be usefull to know how to even be able to run your piece of code.
I assume you already have a Java Development Kit (JDK) and a Java Runtime Environment (JRE) installed.

To even be able to run the JAR file of a source you downloaded here on RaGEZONE you had to fix up your environment variables and get JRE and JDK. The reason for this is because upon running a java class or Java ARchive the pc needs to know in which directory to look for the program to use to run it.
If this fails and "java.exe" doesn't exist you will get an error about "java" not being recognized as internal or external command.

Since the Integrated Development Environments you guys are using already compile .java files to .class files or whole projects to JAR archives it is unnecessary to do this manually. You can only execute .class files.

Let's take a look at the 2 class files we have right now which interact with eachother and return information. To be able to run anything in java you need a main class which contains a main method which is called upon running.

doCharacterStuff (main class):
Code:
package deagansJavaTut;

import deagansJavaTut.examples.MSCharacter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Deagan
 */
public class doCharacterStuff {
    public static void main(String [] args) {
        long currentTime = System.currentTimeMillis();
        MSCharacter chr;
        chr = new MSCharacter();
        short level = chr.getLevel();
        short str = chr.getStr();
        short int_ = chr.getInt();
        String name = chr.getPotentialName();
        boolean isGM = chr.isGM();
        int gainexp = 435;
        System.out.print("Character 1 - info\r\nLevel: " + level + ".\r\nCurrent Exp: " + chr.getExp() + ".\r\nGain "+ gainexp +" exp - new exp: ");
        chr.gainExp(gainexp);
        System.out.print(+ chr.getExp() + ".\r\nLevel Now: " + chr.getLevel() + ".\r\nStrength: " + str + ".\r\nIntelligence: " + int_ + "\r\nRelationship Name:\r\n" + name + "\r\nIs this player a GM?\r\n" + (isGM ? "Yes." : "No.") + "\r\n\r\n");
        
        MSCharacter chr2 = new MSCharacter(538, 4, 212, 0);
        level = chr2.getLevel();
        str = chr2.getStr();
        int_ = chr2.getInt();
        isGM = chr2.isGM();
        System.out.print("Character 2 - info\r\nLevel: " + level + ".\r\nCurrent Exp: " + chr2.getExp() + ".\r\nGain "+ (gainexp * 10) +" exp - new exp: ");
        chr2.gainExp(gainexp * 10);
        System.out.print(+ chr2.getExp() + ".\r\nLevel Now: " + chr2.getLevel() + ".\r\nStrength: " + str + ".\r\nIntelligence: " + int_ + "\r\nRelationship Name:\r\n" + name + "\r\nIs this player a GM?\r\n" + (isGM ? "Yes." : "No.") + "\r\n");
        
        System.out.print("\r\nGoing on with statements:\r\nIteration Statements - While:\r\n");
        chr.remove3PetsWhile();
        
        System.out.print("\r\nIteration Statements - For:\r\n");
        chr.remove3PetsFor();
        
        System.out.print("\r\nIteration Statements - For Array:\r\n");
        chr.remove3PetsForArray();
        
        System.out.print("\r\nIteration Statements - Do-while:\r\n");
        chr.remove3PetsDoWhile();
        
        System.out.print("\r\nTransfer Statements - Break:\r\n");
        chr.undressPlayerBreak();
        
        System.out.print("\r\nTransfer Statements - Return:\r\n");
        chr.undressPlayerReturn();
        
        System.out.print("\r\nTransfer Statements - Continue:\r\n");
        try {
            chr.warpPartyMembers();
        } catch (Exception ex) {
            Logger.getLogger(doCharacterStuff.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.print("It took the program " + (System.currentTimeMillis() - currentTime) + " milliseconds to execute.");
    }   
}

MSCharacter:
Code:
/**
 * @Author Deagan
 * @Purpose showing RaGEZONE how to create a class with general systems ect to teach RZ how java works; especially in MS-based sources.
 */

package deagansJavaTut.examples;

// This class will also be accessible from other directories in the deagansJavaTut folder. public
public class MSCharacter {

    // Integers
    private byte GMLevel = 2;
    private short str; // OdinMS has short.max as max value for stats :)
    private short int_; // the name can't be int as it's a keyword
    private short level;
    public long time = System.currentTimeMillis();
    private int exp;

    // Boolean
    private boolean isGM; // we will soon be able to use a method to find out weither someone is a GM or not ^_^

    // Floating-point types
    private float expDecreasementFactor = 0.5f;
    private float expDecreasementFactorTwo = 0f; // not adding the "f" -> netbeans makes into double
    private double bigFactorForSomethingRandom = 0d; // same thing ^
    private double bigFactorForSomethingRandomTwo = 83427.73;

    // Char and String
    public char H = '\u004f';
    public char O = '\u0073';
    public char T = '\u0069';
    public char G = '\u0072';
    public char U = '\u0069';
    public char Y = '\u0073';
    String nawb = "Deagan";
    String loveRelationship = Character.toString(H) + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y) + " <3 " + nawb;
    String potentialName = "Deag" + Character.toString(O) + Character.toString(T) + Character.toString(G) + Character.toString(U) + Character.toString(Y);
    
    // Constructor - set some standard values - nvm untill operators chapter ^_^
    public MSCharacter() {
        this.level = 1; // level is never 0 when you start off
        this.str = 4;
        this.int_ = 4; // stats start off with 4
    }

    // Constructor overload - 3 parameters
    public MSCharacter(int strength, int intelligence, int level, int GMLevel) {
        this.str = (short) strength;
        this.int_ = (short) intelligence;
        this.level = (short) level;
        this.GMLevel = (byte) GMLevel;
    }

    public short getLevel() {
        return level;
    }
    
    public int getExp() {
        return exp;
    }
    
    public void gainExp(int gainexp) {
        // decrease amount of gained exp with float factor
        if (expDecreasementFactor != 0) {
            gainexp *= expDecreasementFactor;
            //gainexp = gainexp * expDecreasementFactor;
        }
        while (gainexp >= 200) { // levelup every 200 exp
            levelUp();
            gainexp -= 200;
        }
        exp = gainexp;
    }
    
    public void levelUp() {
        level++;
    }
    
    public short getStr() {
        return str;
    }
    
    public short getInt() {
        return int_;
    }
    
    public boolean isGM() {
        if (GMLevel != 0) {
            return true;
        } else {
            return false;            
        }
    }
    
    public String getPotentialName() {
        return this.potentialName;
    }
    
    public void remove3PetsFor() {
        for (int amountOfPetsOut2 = 3; amountOfPetsOut2 > 0; amountOfPetsOut2--) {
            System.out.print("  Pet #" + amountOfPetsOut2 + " has been removed;\r\n");
            //System.out.print(++amountOfPetsOut2 + " pets still out.\r\n"); example for infinite loop
            System.out.print("  " + (amountOfPetsOut2 - 1) + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsWhile() {
        int amountOfPetsOut = 3; // normale you use a .size() to find out but just for the example...
        while (amountOfPetsOut > 0) {
            System.out.print("  Pet #" + amountOfPetsOut + " will be removed;\r\n");
            amountOfPetsOut--; // symbolizes removing pet
            System.out.print("  " + amountOfPetsOut + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsForArray() {
        int[] pets = {2, 1, 0};
        for (int petid : pets) {
            System.out.print("  Pet #" + (petid + 1) + " will be removed;\r\n");
            pets[petid] = 0; // just imagine it being an instance that gets emptied or pet gets pulled back into it's house
            System.out.print("  " + petid + " pets still out.\r\n");
        }
    }
    
    public void remove3PetsDoWhile() {
        int amountOfPets3 = 3;
        do {
            System.out.print("  Pet #" + amountOfPets3 + " will be removed;\r\n");
            amountOfPets3--; // symbolizes removing pet
            System.out.print("  " + amountOfPets3 + " pets still out.\r\n");
        } while (amountOfPets3 > 0);
    }
    
    public void undressPlayerBreak() {
        int amountOfEquips = 14; // let's say player has 20 slots and wears 14 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("  Break at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\n");
                break; // change it into return and see what happends later!
            }
            System.out.print("  Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("  The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }
    
    public void undressPlayerReturn() {
        int amountOfEquips = 6; // let's say player has 20 slots and wears 6 pieces of clothing... just for the idea
        for (int i = 20; i > 0; i--) {
            if (amountOfEquips == 0) {
                System.out.print("  Return at i = " + i + ", so the for loop made " + (20-i) + " loops.\r\nPlayer is naked. Jump out of the method undressPlayerReturn.\r\nMessage out of the for loop was never dropped.\r\n");
                return;
            }
            System.out.print("  Player wears " + amountOfEquips + " pieces of clothing; removing one piece of clothing.\r\n");
            amountOfEquips--;
        }
        System.out.print("  The player is now naked.\r\nThis message would not have been printed if we used the return transfer statement instead of break.\r\n");
    }
    
    public void warpPartyMembers() throws Exception {
        // gather all members in the map then send them to another map - in the most non literal sense
        for (int member = 0; member < 6; member++) {
            if (member == 3) {
                System.out.print("      Member #" + (member + 1) + " is at another map than the rest of the party.\r\n      The 5 other members can be warped in but #" + (member + 1) + " will have to be skipped.\r\n");
                continue;
            }
            System.out.print("  Warping party member #" + (member + 1) + " into the PQ.\r\n");
        }
    }
}

If you create these directories and classes and click on "Run" -> "Run Main Project" or press F6 the project will run and display as follows:
Code:
run:
Character 1 - info
Level: 1.
Current Exp: 0.
Gain 435 exp - new exp: 17.
Level Now: 2.
Strength: 4.
Intelligence: 4
Relationship Name:
Deagsiris
Is this player a GM?
Yes.

Character 2 - info
Level: 212.
Current Exp: 0.
Gain 4350 exp - new exp: 175.
Level Now: 222.
Strength: 538.
Intelligence: 4
Relationship Name:
Deagsiris
Is this player a GM?
No.

Going on with statements:
Iteration Statements - While:
  Pet #3 will be removed;
  2 pets still out.
  Pet #2 will be removed;
  1 pets still out.
  Pet #1 will be removed;
  0 pets still out.

Iteration Statements - For:
  Pet #3 has been removed;
  2 pets still out.
  Pet #2 has been removed;
  1 pets still out.
  Pet #1 has been removed;
  0 pets still out.

Iteration Statements - For Array:
  Pet #3 will be removed;
  2 pets still out.
  Pet #2 will be removed;
  1 pets still out.
  Pet #1 will be removed;
  0 pets still out.

Iteration Statements - Do-while:
  Pet #3 will be removed;
  2 pets still out.
  Pet #2 will be removed;
  1 pets still out.
  Pet #1 will be removed;
  0 pets still out.

Transfer Statements - Break:
  Player wears 14 pieces of clothing; removing one piece of clothing.
  Player wears 13 pieces of clothing; removing one piece of clothing.
  Player wears 12 pieces of clothing; removing one piece of clothing.
  Player wears 11 pieces of clothing; removing one piece of clothing.
  Player wears 10 pieces of clothing; removing one piece of clothing.
  Player wears 9 pieces of clothing; removing one piece of clothing.
  Player wears 8 pieces of clothing; removing one piece of clothing.
  Player wears 7 pieces of clothing; removing one piece of clothing.
  Player wears 6 pieces of clothing; removing one piece of clothing.
  Player wears 5 pieces of clothing; removing one piece of clothing.
  Player wears 4 pieces of clothing; removing one piece of clothing.
  Player wears 3 pieces of clothing; removing one piece of clothing.
  Player wears 2 pieces of clothing; removing one piece of clothing.
  Player wears 1 pieces of clothing; removing one piece of clothing.
  Break at i = 6, so the for loop made 14 loops.
  The player is now naked.
This message would not have been printed if we used the return transfer statement instead of break.

Transfer Statements - Return:
  Player wears 6 pieces of clothing; removing one piece of clothing.
  Player wears 5 pieces of clothing; removing one piece of clothing.
  Player wears 4 pieces of clothing; removing one piece of clothing.
  Player wears 3 pieces of clothing; removing one piece of clothing.
  Player wears 2 pieces of clothing; removing one piece of clothing.
  Player wears 1 pieces of clothing; removing one piece of clothing.
  Return at i = 14, so the for loop made 6 loops.
Player is naked. Jump out of the method undressPlayerReturn.
Message out of the for loop was never dropped.

Transfer Statements - Continue:
  Warping party member #1 into the PQ.
  Warping party member #2 into the PQ.
  Warping party member #3 into the PQ.
      Member #4 is at another map than the rest of the party.
      The 5 other members can be warped in but #4 will have to be skipped.
  Warping party member #5 into the PQ.
  Warping party member #6 into the PQ.
It took the program 18 milliseconds to execute.
BUILD SUCCESSFUL (total time: 0 seconds)

If you want to manually run;
- Open up cmd.exe.
- Make your way to the directory where the .jar file was created.
To do this type "cd <directory>".
- Type "java -jar projectname.jar".
- Or do what NetBeans says when it is done creating the jar;
"To run this application from the command line without Ant, try:
java -jar <.jar directory here>".
- Enter.

5.2 Exception Handling

In java, an exception is a signal for an unexpected problem that occured while running the program.
An exception makes it impossible for the rest of the code to still be executed unless being taken care of properly.
This taking care of exceptions is called exception catching.
Exceptions are java objects aswell; they contain the subclasses "Error" and "Exception".
Errors are unchecked exceptions and are exceptions within the runtime environment itself so there is no need to take care of them in the source-code.
Exceptions from the Exceptions subclass (checked exceptions) in contrary are ought to always be catched properly.

There are 2 other transfer statements that are used to take care of checked exceptions; the "throw-catch-finally" statement and the "throw" statement.
Some often occuring exceptions:
  • NullPointerException - an object appears to be empty (null).
  • ArrayIndexOutOfBoundsException - an array index doesn't exist.
  • OutOfMemoryError - no more memory could be made free to allocate to an object.
  • SQLException - problem occured when working with SQL.
  • ArithmeticException - deviding by 0.

5.2.1 Try-catch-finally Statement
Code:
try {
    // piece of code to be executed.
} catch (exceptiontype1 parameter1) {
    // piece of code to be executed when exception occurs in main piece of code of specific exception type1.
} catch (exceptiontype2 parameter2) {
    // piece of code to be executed when exception occurs in main piece of code of specific exception type2.
}
  (optional)
  finally {
    // piece of code to always be executed; doesn't matter if exception occured or not
}

try {
        MSCharacter chr3 = null; // oops I made a mistake :(
        System.out.print("Player's level is " + chr3.getLevel() + ". wait...");
        } catch (NullPointerException e) {
            e.printStackTrace();
        } finally {
            System.out.print("Nullpointer erection??\r\n");
        }

5.2.2 Throw Statement
When you want to throw an exception to the console we can use the "throw" statement. It isn't necessary to do this within an try-catch-finally statement but it is proper.
Code:
System.out.print("\r\nLet's make a third character for fun!\r\n");
        try {
        MSCharacter chr3 = null; // oops I made a mistake :(
        System.out.print("Player's level is " + chr3.getLevel() + ". wait...");
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw e;
            throw new RuntimeException("Object is uninitialized.");
        } finally {
            System.out.print("Nullpointer erection??\r\n");
        }
        
        System.out.print("It took the program " + (System.currentTimeMillis() - currentTime) + " milliseconds to execute.\r\n");
// last system print will never be done so the programs tops executing after exception has been thrown.
Whenever you decide to use "throw" in a method the method itself will need to be declared with a throws clause.
When invoking the method you will also need to surround it in a try-catch-finally statement aswell.
Basically, this statement isn't very much recommended by me.

NOTE: Preventing is better than curing!
You should use conditional operators and if else checks to see if objects are not empty; eventually even initialize them.
When fixing errors, simply follow the java classes mentioned and you will find the cause of the exception soon enough.

Chapter 6: Advanced - Objects and Caching
This chapter is still being written; it takes a little bit of time for myself to look into it myself.
I hope to be able to provide information about often occuring issues in OdinMS like memory leaks and deadlocks in this chapter very soon. Give me like 1 day. :thumbup1:
Please don't complete this tutorial before I write my part; just be patient.

Chapter 7: Summary & List of Definitions
soon to be added.
 
Last edited:
Junior Spellweaver
Joined
May 9, 2011
Messages
141
Reaction score
21
Deagan, nice job! This would help newbie alot! :)
 
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
Deagan, nice job! This would help newbie alot! :)

Depends on who you consider to be "noob" or not. I know many people that don't know 90% of what I just typed out in this tutorial and they are still known as pro on here.

This is good stoofs =) Nice Tut even though i have no idea what it is

Maybe you have no clue what it is because you haven't read it yet?
It obviously is just a tutorial to teach everyone here java; so for once people can start doing stuff for themselves.
 
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
All your releases are gewd stoofs :8:

Actually most of my previous releases aren't too much special... except my anti-packet database; I consider that to be my best java release untill now, and this my best tutorial.

Even though i'm honoured that you like every single one of them, I don't think it's a valid reason to like this tutorial before even reading it just because you think all my previous releases rock.

I really hope people will read this and pay attention to it; eventually even a special system on the section where people can redirect to chapters/subchapters in this tutorial before reading a thead.
 
Initiate Mage
Joined
Aug 5, 2011
Messages
3
Reaction score
1
I'm going to take a brief recess from my trolling due to the sheer respect I have for you spending so much time on your tutorial; I know it's a witch to make. XD It's fairly well done, and god knows this section needed something like this. I'm looking forward to seeing your section on caching, primarily the memory leaks and deadlocks in OdinMS. Just to help you out a bit, there's a few Factories you'll want to look at in Odin.
Anyways, good job.

Depends on who you consider to be "noob" or not. I know many people that don't know 90% of what I just typed out in this tutorial and they are still known as pro on here.
Like who? o_o
 
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
I'm going to take a brief recess from my trolling due to the sheer respect I have for you spending so much time on your tutorial; I know it's a witch to make. XD It's fairly well done, and god knows this section needed something like this. I'm looking forward to seeing your section on caching, primarily the memory leaks and deadlocks in OdinMS. Just to help you out a bit, there's a few Factories you'll want to look at in Odin.
Anyways, good job.


Like who? o_o

Thanks for the respect and looking forward to that advanced chapter.
I already know about memory leaks and the problems with caching that lead to it but I really need to look into the literal java features like hashmaps, pairs, lists ect. to be able to add it into a tutorial this literal.
Do you maybe have something for me to look into for "threads" aswell? No clue what they are and how they work yet it seems so easy to talk about them.

Oh and maybe I exaggerated about 90% but I am still convinced I know some "pros" that actually aren't as amazing as they claim to be. But I will not provide names; despite my intense lust to be a nazi and rat out every single idiot with an enormous ego I choose not to simply because I don't really want the flame wars in my thread.
 
Last edited:
Initiate Mage
Joined
Aug 5, 2011
Messages
3
Reaction score
1
Thanks for the respect and looking forward to that advanced chapter.
I already know about memory leaks and the problems with caching that lead to it but I really need to look into the literal java features like hashmaps, pairs, lists ect . to be able to add it into a tutorial this literal.
Do you maybe have something for me to look into for "threads" aswell? No clue what they are and how they work yet it seems so easy to talk about them.

Oh and maybe I exaggerated about 90% but I am still convinced I know some "pros" that actually aren't as amazing as they claim to be. But I will not provide names; despite my intense lust to be a nazi and rat out every single idiot with an enormous ego I choose not to.
Pair is a generic class in most MS sources, so it shouldn't be classified with the other things you listed.
Threading in Odin is generally fine... I mean, there are definitely TimerManager problems, but that's because of how TimerManager is used, not because of strictly threading.
PM me for my msn if you want it. xD
 
Junior Spellweaver
Joined
Jul 26, 2008
Messages
161
Reaction score
51
Thank you very much Deagan. I just happen to be learning the ropes of Java right now too! :thumbup1:

A crystal-clear guide describing a lot of vital/important aspects of Java (although it's probably not complete).

Many thanks (once again),
Jacky

Edit* Bookmarked. :D:
 
Last edited:
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
Thank you very much Deagan. I just happen to be learning the ropes of Java right now too! :thumbup1:

A crystal-clear guide describing a lot of vital/important aspects of Java (although it's probably not complete).

Many thanks (once again),
Jacky

Once the advanced chapter is done, it will be even more than complete as I claim this tutorial only teached the basics of java.
I take it a little bit further to have more people up-to-date with what's going on.

A java tutorial can never be complete though... there's so many classes and things to look into. It is very much possible to complete a tutorial which teached basic java though as basic is still... very basic. :)
 
Newbie Spellweaver
Joined
Jun 17, 2011
Messages
99
Reaction score
19
Sexy guide Degan :)

Even though I don't really need it, it's well written and awesome for beginners!

Thumbs up.

(Cyrus)
 
Last edited:
return null;
Loyal Member
Joined
Dec 21, 2008
Messages
805
Reaction score
130
Nice tutorial, this is covering the basics and you'll be able to create really simple applications. It's good to see that there are still people who take their time to help others.


edit:

You might want to correct
Code:
Java Visual Machine
with
Code:
Java Virtual Machine
in chapter 3.1.5
 
Last edited:
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
Nice tutorial, this is covering the basics and you'll be able to create really simple applications. It's good to see that there are still people who take their time to help others.


edit:

You might want to correct
Code:
Java Visual Machine
with
Code:
Java Virtual Machine
in chapter 3.1.5

Thanks, fixed that; VisualMS must have been in my head a little too much. ^_^

Advanced & caching chapter will contain an introduction to a handfull of new datatypes and the way classes interact with eachother. (interfaces, subclasses *extending*, enums and threading)
 
Newbie Spellweaver
Joined
Sep 28, 2008
Messages
62
Reaction score
0
I'm so confused. Lol I guess I'll have to read it again.
If that doesn't help, I think I'll just stop trying to learn from the internets and wait for college to start so I can take a class about java. =/
 
I'm sexy and I know it :)
Joined
Oct 21, 2008
Messages
811
Reaction score
350
I'm so confused. Lol I guess I'll have to read it again.
If that doesn't help, I think I'll just stop trying to learn from the internets and wait for college to start so I can take a class about java. =/

Well, my advice is to take your time and experiment a bit with what you've learned already. practically ececuting what you're learning improves the amount of information that you save.

Read it again ofcourse, take your time, and it will be alright.
BTW, sorry for not yet adding the last 2 chapters... I think I won't succeed when i'm drunk. Too much of a party person... I should stop it.
 
Back
Top