~~~~~~~~~~~~~~~Index~~~~~~~~~~~~~~
Part 1.) Introduction
Part 2.) Basic Structure
Part 3.) Variables and Types
Part 4.) Simple Commands and Syntax
Part 5.) Logical Operators
Part 6.) Decision Structures
~~~~~~~~~~~~~~~Part 1~~~~~~~~~~~~~~~
Introduction:
Hi, thanks for reading my newest tutuorial. A lot of n00bs are asking about the most simplest of things, including syntax and such. The purpose of this tutorial is to give the very basics on Java, whether you're trying to get a head start on your class or as a little extra help in your class, so you can jump into Java with ease. Since Java is basically an intro course to other programming languages, such as C and C++, it is important to master the basic concepts of this simple language in order to move on. Note: this is not a replacement for a good old fashioned book or class, which I suggest doing. ....
Let's get started, shall we?
~~~~~~~~~~~~~~~Part 2~~~~~~~~~~~~~~~
Basic Structure:
If you look at a piece of Java code, you will notice that it has a very distinct structure. This is because its object oriented. Every thing takes place in classes, making it easier to reuse code. ((we programmers like to recycle.... because we're lazy >_>)) A class is an outer most shell of code, holding all the code associated inside. Every program has to has at least one class, a main class, or your program will not compile.
public class main {
}
That's the outtermost shell of your program. Anywho, inside a class, you should have these components called methods. These babies is where all the magic happen. Every main class should have a main method. This main method is where your main code is run. You could run a program without using more than the main class with only the main method, but then it would take the charm outta object oriented.
So, basic structure:
Main class{
Main method {
//code
}
Method 1 {
//code
}
Method 2 {
//code
}
}
Now, these {} (curly brackets) are important because they hold the code that fits inside. If you're missing one, your code my compile, but the program will not run the way you want. I would go into detail about how to set up classes, but that's a little complex for a n00b at the moment, so you can read a tutorial about that some other time. For now, we will look at a method.
public class main {
public static void main(String[] args) {
//code
}
}
The first word public means that any other class can see or use it (will cover in another tutorial). It could either be public, private, or protected. The static word means that it can be called within the same class. If the static is skipped, the compiler assumes it to be an instance method, meaning you have to created an instance of the class to use the method (will cover in another tutorial). Void, however, can't be skipped. This is the return type. For the main class, you usually are not returning anything, so leave it void. Next is the methods name. It should have the same rules as a variable when it comes to naming. The parenthesis are the parameters. Parameters are typed values that the method takes and manipulates, but we will cover that in another tutorial. The String[] args thing in complicated, but I think there's a tutorial on that if you're really interested. It has to do with calling your program in the command promt or something.
So, putting it simpler:
access (static) return name(type parameter) {}
For now, all you should know is the code I gave above. This is the basic structure of a program.
~~~~~~~~~~~~~~~~~Part 3~~~~~~~~~~~~~~~~~~~~
Variables and Types:
In Java, or any programming language for that matter, you need variables. Variables hold values for your program. It makes code a lot more clean if everything is clearly labeled, as opposed to a big jumble of numbers. You also use variables to catch input. Say you're making a program to determine how much money you will have in a savings account after the interest rate, and you want to say that the rate of interest is... 0.02% or something like that (I'd switch banks >=[ ). You could make a variable called interestRate, and set it equal to 0.02, so everytime you want to use that number as an interest rate, you'd use interestRate instead.
Why? you ask? Well, when you start a project, quit, then come back to it 3 months later, chances are you are not going to remember what those numbers are and what their significance to the program is. Programs can have as many variables as you want. Now, variables also have different types, which determine what kind of value goes in them.
Here are a list of common types:
int - integer (most common. no decimal)
long - holds a really big integer
float - accurate up to 7 decimal places
double - accurate up to 15 decimal places I do believe (at work and don't have a book)
boolean - false or true (also 1 = true, 0 = false)
String - anything from numbers to letters to whole sentences. It will take the input literately.
char - character, such as f or 6 or \. You can also use the decimal numbers to determine a character (130 = é)
These are the most common types you will deal with. Float isn't used that often, as double is way more accurate. Actually, if you use a float the compiler will probably tell you that you should use double due to loss of precision. Now to declare a new variable, all you have to do is state it's type and what it is to be called.
type name;
This is where the semi-colon starts to come into play. At the end of every statement, you use a ;. This tells the compiler that the command is over, and to start with the next command. You can also initialize the variable, meaning you can assign a value to it, in the same line or in 2 separate commands.
Next I guess I should explain the rules to naming things. Just like children, you are not allowed to name variables retarded names. Your variable should be descriptive and should leave no doubt what the meaning of the variable's contents. Also, you cannot start a variable name with numbers or any special characters other than _ and $, which are rare,and the variable cannot have spaces. It's also standard convention to make the first letter for normal variables lowercase, with the first letter of other word is uppercase. Lastly, the names cannot be reserved words, such as: int, true, in, out, class, ...etc.
Legal names:
-name
-file2
-_letter
-lastNameValue
Illigal names:
-2variable
-&name
-last name value
public class main {
public static void main(String[] args) {
int x = 5;
int y;
y = 10;
}
}
Now we have declared 2 variables, x and y. x's value is 5, and y is 10. Those variables will contain those values until changed by declaring it as something else, or until it goes out of scope (will explain in later tutorial). Easy enough? Let's try another.
public class main {
public static void main(String[] args) {
double d = 5.25;
String greeting = "hello";
}
}
Simple enough, right? Now lets figure out how to make programs that do stuff with those variables.
~~~~~~~~~~~~~~~~Part 4~~~~~~~~~~~~~~~~~~~~
Simple Commands and Syntax:
Okay, everybody's first program in ANY language is hello, world. That's classic. So I will show you how to do it.
public class main {
public static void main(String[] args) {
System.out.print("Hello, world");
}
}
That's it. Wow. Kinda lame, huh? Yea, your first programs will be. Okay, to break this down, the System part means you're dealing with the console. I prefer to do stuff in the console because I'm too lazy to fool with GUI (graphic user interface - the pretty pop up windows), so most of the stuff in my tutorials will be console. Now, after the System you have to put a period here. This is an important part that will be explained in a later tutorial when we talk about classes and methods and instantiation and junk. Anywho, the out means that you're outputting something through the console (System). print is just the method used to return a String object to the screen.
Remember how I told you that methods have to have parenthesis, which may or may not hold parameters? Well here is an example. What you put inside those quotes are a type String object, which the print method takes and manipulates, which in this case just prints it to the console. Pretty simple stuff.
The thing with print is that is keeps going and going on the same line until you type a return character in the string. \n tells the compiler to make a new line. You could use this at the end of every line, or use:
System.out.println("");
"Hey, the print and println methods take Strings, right? Hey! I know how to make Strings!" That's right. Lets combine what we know.
public class main{
public static void main(String[] args) {
String gretting = "Hello";
String comma = ',';
String subject = " world!!!";
System.out.print(greeting);
System.out.print(comma);
System.out.print(subject);
}
}
Did I also mention that you can combine strings using a +? Example:
System.out.println(greeting + comma + subject);
Okay, now lets manipulate those variables. + and - signs work just as you expect them to when in an expression. 1 + 2 = 3. * and / are the same as well. 2 * 1 = 2. % (modulus) returns the remainder. This is expecially useful for searching for even/odd numbers or prime numbers. 4 % 2 = 0, 15 % 10 = 5. = is considered an assignment operater, meaning it assigns values to something, in this case, an answer to a variable. The variable comes first when doing math. Say z is the variable catching the answer, you put the z before the = sign. z = x + y; means that z is equal to the value of x plus the value of y. Lets do an example, shall we?
public class main {
public static void main(String[] args) {
int x = 3;
int y = 2;
int z;
z = x + y;
System.out.println(z);
}
}
Way easy, non? By the way, the z was magically transformed into a String by the compiler.
If you're trying to, say, add up a list of numbers into a variable int sum, you are probably going to say
sum = sum + num;
That is a legal statement, but you could also condense it to just
sum += num;
This takes sum, adds num, then assigns it to sum. These are great ways to add values in an array, like say adding scores or something. You can do this for all 5 of those operations I showed.
+=
-=
*=
/=
%=
Also, you will want to increment or decrement a number as well. ++ or -- will either add 1 or minus 1 from the current variable. You've probably already looked at some code and saw a for loop. For loops are perfect examples when showing incrementation.
for(int i = 0; i < 5, i++) {//do stuff}
After each iteration the i increments itself. This is an example of a postfix function, as it does the operation after it reads the value of i. You could also have ++i and --i, but the number will be increamented/decremented before showing, so the loop shown above would be shorter.
((You've probably also seen me do a // in some code blocks. These are comments. Everything after these is ignored by the compiler. I wrote a whole tutorial about this called Documentation for N00blets. You should check it out for a more in depth explanation))
~~~~~~~~~~~~~~~Part 5~~~~~~~~~~~~~~~~~~
Logical Operators:
Without these.... we really couldn't do anything. They are probably the most import thing when it comes to doing ANYTHING in programming. Collision detection in a game, printing things out in an array, checking for certain info, organizing data, etc. all depend on logical operators. You've already seen most of these before in math class. Remember those greater than and less than symbols? If you paid attention in class you already know how these work.
These determine conditions (relational operators):
< less than > greater than <= less than or equal to >= greater than or equal to == is equal to != not equal to
There are also the logic operators for determining truthfulness:
&& and || or (shift + backslash key) ! not
Now, there is a chart to help you get a feel for these little operations. Their called truth tables. You probably already learned about those in math. In order for an "and" statement to be true, all the conditions have to be true, or else it will return false. On the other hand, for an "or" statement to be true, at least one of the conditions has to be true
X Y && ---------------------------------- T T T T F F F T F F F F X Y Z && -------------------------------------------- T T T T T T F F T F T F T F F F F T T F F T F F F F T F F F F F X Y || ----------------------------- T T T T F T F T T F F F X Y Z || ---------------------------------------- T T T T T T F T T F T T T F F T F T T T F T F T F F T T F F F F
That should clear things up a bit. Not basically negates anything. If x = true, then !x = false, and vice versa. Simple enough. Now lets put those things into context.
~~~~~~~~~~~~~~~Part 6~~~~~~~~~~~~~~~~
Decision Structures:
if statements are very helpful when making conditions, and they are easy to use. NOTICE!!!! Because I am lazy, I'm shortening System.out.println to sout. If you type sout in Netbeans and hit tab, it will automatically expand into System.out.println("");. Pretty nifty.
if(x > y) sout(x);
This just basically says that if the value of x is greater than the value of y, then print x to the screen. The basic format for an if statement is:
if(variable condition variable) {
do stuff
}
Because I only had one line in the above example, I had no need for curly brackets. If you have more than one command to go in that if statement, you need to enlose them in the curly brackets. I use curly brackets all the time for clarity's sake (and I like to be better safe than sorry).
else statements are what happens when an if statement fails. These aren't exactly necessary unless you have to have something happen depending on the variables. They don't need parenthsis as they are like the worst case scenarios.
if(x > y) {
sout(x);
}
else {
sout(y);
}
else if are kinda like what I call "plan b" conditions. If situation a doesn't work out, and situation 2 does, then do this, else do this. That's those 3 put in a nutshell.
if(x > y) {
sout("x is greater than y");
}
else if(x < y) {
sout("x is less than y");
}
else if(x == y) {
sout("x is equal to y");
}
else {
sout("I have no clue what in the hell happend :(/> ");
}
for loops we sorta glanced at above. They state a loop control variable, usually an i or x, put a conditional in place, then increment i, and it does all the stuff in the brackets while that condition is true. These are very powerful tools and are used very very very often. Be careful though, as your computer starts to count at zero.
for(int controlVariable; condition including controlVariable; controlVariable++) {do stuff}
((Make sure those are semi-colons in between, as they are basically mini-statements))
Say we want to ... find a factoral of number x. We could say:
int factoral = 5;
int x = 1;
for(int i = 0; i < 5; i++) {
x *= factoral;
factoral--;
System.out.println(x);
}
This code basically finds the 5! by using a for loop. We set a max (factoral decreases, so we can't put that as i < factoral) at 5, then for each of the five steps it multiplies x by factoral then factoral decreases by 1. If we look at the values, just like a step through debugger we would see:
i = 0
x = 1
factoral = 5
i = 1
x = 5
factoral = 4
i = 2
x = 20
factoral = 3
i = 2
x = 60
factoral = 2
i = 4
x = 120
factoral = 1
i = 5
x = 120
factoral = 0
Very useful arent they. Instead of going through step by step and doing those steps, you could just use for loops to handle it. I mean, if you want to write it all out, fine, but if you're trying to calculate 573!, you'll be wanting to use that loop.
((Actually, I'm curious as to what that would be... *reruns program* Oh yea, I should mention that there are limits to how many numbers an int can hold. >_> For to find 573!, you'd probably need to make x a long. Actually, that number is so big, it just goes to zero's after a while due to the number restraints on the variables. :\ Even my calculator gives an overflow error, but 17! = 355687428096000
Okay, while loops are very useful for doing a certain task while a certain condition is true.
while(variable condition variable) {do stuff}
while(x < y) {
sout(x);
}
Very easy. This checks to make sure the condition is true before doing what's inside the brackets. You could also to a post check operation, meaning
doing the action and then checking to make sure the conditional is true, by using do while loops.
do {
sout(x);
} while (x < y);
do {statements} while(condition);
Okay, with this little knowledge, you should be able to do quite a bit in Java. Believe it or not, this simple basic stuff you just learned is about 90% of the meat in a Java program. You're half way to becoming a decent programmer.
tuned for more.
Next tutorial:
Java For N00blets Part 2
This post has been edited by macosxnerd101: 25 May 2012 - 02:51 PM
Reason for edit:: Added link to next tutorial










MultiQuote












|