What's new

Closed Ultimate java tutorial | huge and detailed | beginner friendly

Status
Not open for further replies.

Strawberrry

Forum Veteran
Elite
Joined
Aug 2, 2016
Posts
1,611
Solutions
4
Reaction
635
Points
528
INTRODUCTION TO JAVA
Hello everyone,

This is a tutorial to teach you some of the basics of Java. I am not making this tutorial to share advanced java code or tutorials with you, this tutorial is designed for those specialists who have no (or very little) previous coding experience/knowledge, who would like to learn.

Introduction


Java is one of the most popular programming languages used today (particularly for client-server web applications). The developers of Java had 5 goals for the language: It should be "simple, object-oriented and familiar", "robust and secure", "architecture-neutral and portable", "high performance" and "interpreted, threaded, and dynamic". It has very similar syntax to C and C++, but it has fewer low-level facilities than either of them, because of the way java programs are run in the JVM. The advantage to the JVM is that it lets application developers "write once, run anywhere", because the code they write can be compiled to class files, inside a JAR (a Java Archive that contains a set of classes a program exists of). The JAR is runnable on any JVM without recompiling. It also has very few dependencies due to its portable design - everything you need comes with the java runtime which is installed on most computers. Disadvantages to the language is that it is not great for coding low level programs, and things such as malware, because it is not natively run and does not have the same abilities as a native language like c/c++ (unless you use the JNI), along with other factors.

Java is an object-oriented programming (OOP) language. OOP languages treat everything as an Object (although Java is not pure OOP - it has primitive types as well), and use abstraction, encapsulation, polymorphism, and inheritance. I will cover these things later.

space

Getting started


There are 3 different java releases: The Java Runtime Environment (JRE, which comes with the parts of the Java SE platform required to run Java programs and is intended for end-users), and the Java Development Kit (JDK, which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger). There is also the server JRE. To start coding in Java, you must install the Java Development Kit.

Download the latest JDK 8 for your operating system here: You do not have permission to view the full content of this post. Log in or register now.
If you want to code using JDK 7, that can be found here: You do not have permission to view the full content of this post. Log in or register now.

After installing the JDK, you need to add an environment variable. Open "Control Panel > System > Advanced system settings > Environment Variables". Click New, call the variable Java, and link your JDK bin folder.

Next, you will need an IDE. An IDE is an Integrated Development Environment, combining the editor, compiler, management and error checking all into one easy environment.
You can code in Java without an IDE by using any text editor (notepad, notepad++, sublime text) and the command line compiler, but I think IDEs are better because they help prevent errors and they keep your project organised.
I use Eclipse (Download: You do not have permission to view the full content of this post. Log in or register now.), but other popular IDEs include NetBeans (Download: You do not have permission to view the full content of this post. Log in or register now.) and IntelliJ (Download: You do not have permission to view the full content of this post. Log in or register now.). Download and install an IDE.

IMPORTANT NOTE: Make sure all your versions match. If you have a 64 bit OS, make sure you download the 64 bit JDK and 64 bit eclipse.

Run eclipse and wait for it to load. Choose a workspace location to store your projects, and wait until the IDE itself loads.
To create a new Java project in eclipse, click "File > New > Java Project". Choose a name for your project and click "Finish". Now we can start coding.

Hello World

As usual, whenever we start a new programming language, the first program we always write is Hello World. In java, this is how you write a hello world program:

Code:
class HelloWorld {
    public static void main(String[] args) {
      System.out.println("Hello World!");
    }
}

This is the breakdown of the project: We have a Class called HelloWorld which holds the main function of our program (main). When you run the program in eclipse (Run > Run), eclipse will find the main function (the main function is always called main) and run it. The function only has one line of code, which calls println("Hello World!"). All the println function does is print a line to the console. When you run this, you will see "Hello World!" written in the console. Your first java program!

If you want to compile and run the java program without using the IDE, then first run the compile command:

Code:
javac HelloWorld.java

Then run the compiled program:
Code:
java HelloWorld

Classes
A class is the blueprint from which individual objects are created. Almost every object in Java is a class. Here is an example of a class:

Code:
public class Car
{
    private double mileage;
    public String manufacturer = "";
    private double petrol;

    public Car(String manufacturer)
    {
        this.manufacturer = manufacturer;
        mileage = 0;
        petrol = 0;
    }

    public void refillPetrol(double amount)
    {
        petrol += amount;
    }

    public double getMileage()
    {
        return mileage;
    }
}

Don't worry if you don't understand all that right now, we will be coming back to the Car class throughout this tutorial. Just notice now that the class contains 2 types of things: variables (mileage, manufacturer, petrol) and methods (refillPetrol, getMileage). There is also a Constructor method (Car) which we will cover shortly.
Classes are essential to OOP. Here are some of the things classes can do:

* Classes can be "instantiated", which means creating a new object based on that class. For example, if we have a Car class, we can create a new Car based on that class.
Instantiating new classes is very easy:

Code:
Car myNewCar = new Car();

We just created a new Car object called myNewCar, and stored a new Car object in it using the "new" keyword.

* Classes can be "extended", also known as inheritance. This allows us to make "subclasses" of a template class, which all share similar attributes/functionality, to save us from repeating ourselves.
Classes are extended using the "extends" keyword - what a suprise. For example, we can create a child class of Car called ToyotaCar, because it shares very similar attributes such as remainingPetrol, and functions such as turnLeft():

Code:
public class ToyotaCar extends Car
{
    public ToyotaCar()
    {
        super("Toyota");
    }
}

Once again, don't worry about the ToyotaCar constructor yet. We will cover that shortly. If we want to make the class ONLY extendable, so it cannot be used (instantiated) on its own, we use the "abstract" keyword in its declaration. Abstract methods are methods which are given no body, but which HAVE to be included in subclasses with a body. This can allow us to create a "template" class and all the information must be filled in later.

Example of an abstract method:

Code:
abstract void turnLeft();

The abstract method has no body, just a name, to make sure that classes which inherit this class include the method. When inheriting that class, we would write:

Code:
public void turnLeft()
{
    //code goes here
}

You can also override a normal method in a subclass too, even if it isnt abstract, in case you want to change something in it. An overriden method can call the superclass method using the super keyword:

Code:
public void turnLeft()
{
    //this is the overriden turnLeft method. to call the original method, we use:
    super.turnLeft();
}

Variables

A variable is a container that holds values. Each variable is declared to be a certain type - depending on whether it holds text, integers, true or false, etc.
There are eight primitive data types:
* byte - Values from -128 to 127 (inclusive).
* short - values from -32,768 to 32,767 (inclusive).
* int - this is the standard variable uses to store whole numbers. it stores a huge range of positive and negative.
* long - double the memory size of an integer - can hold much larger numbers.
* float - Used instead of double to conserve memory, with less accuracy.
* double - standard type to use for decimal numbers.
* char - a single 16-bit Unicode character. ranges from '\u0000' to '\uffff'. An array of chars (a CharSequence) is used to store text - a string is a subclass of CharSequence so a string is very similar to an array of chars.
* boolean - only 2 possible values: true or false.

Types like byte and short are used to save memory, because they are much smaller than the larger int, but they cannot hold as large a range.

In the car class, we can see there are 3 variables declared: mileage, manufacturer and petrol. Mileage and Petrol are both doubles, because they store decimal numbers. manufacturer is a String, which stores text.

Declaration:

Code:
[modifiers] [type] name;

This will declare a variable of type [type]. name can be any name, except for keywords already used by Java (such as string). But this new variable has no value - it is an empty container.

You can also declare multiple variables of the same type at once:

Code:
int a, b, c;
Or, assigning a value at the same time:
Code:
int a = 10, b = 3, c = -4;

Initialization / Assignment:
Code:
name = [value];

This stores [value] in the variable. The value must be the same type as name, otherwise you must "typecast". You can assign the value in the same line as the declaration too. You must assign the variable a value to use it.

Numerical variables can be used in many mathematical operations, like addition, multiplication, etc. Strings can also be manipulated, for example, concatenating strings together to form a longer string. In the code above, I demonstrated a slightly special operator - "petrol += amount;"
This += adds amount to the currently existing value of petrol. It is identical, but shorter, to writing "petrol = petrol + amount;"
You can read about the other operators in the Operators section.

space

Functions and Methods

Methods are blocks of code that can actually be run and do things. An example of a method from our car class is this:

Code:
public void refillPetrol(double amount)
{
    petrol = petrol + amount;
}

Notice that we used the public modifier on this method, so that it can be accessed and run from outside the car class itself - for example, if we wanted to create a new car and refill it with some petrol in our main method.

The main() method is the method that is run when the program starts. It usually looks like this:
Code:
public static void main(String [] args)
{

}

Lets have a look at how a function is coded:
  • we first have modifiers. In the refill class, we just made it public, but in main, we made it public static.
  • next we have a return type. This is the type of variable/object the function will return when it is finished. Both functions i gave above have a return type "void" which means they do not return a value. but the getMileage() method in the car class has return type "double" which means it returns a value of type double to whatever called the method.
  • then we have the function name. main is the name given to the main class, but you can give any other functions any name you like as long as it is not the same as a java keyword (like static or double).
  • we have some parentheses. These can be empty or can have a variable declaration in them. The variables inside the parentheses are "parameters", which are values passed to the function so that it can do something with them. if the brackets are empty, then the function doesn't take any arguments.
  • curly braces are used to surround the function body, where all the code that the function will do is put.
  • finally, we need a return statement if the function has a return type (other than void). For example, if our function is returning a double, we must write return 12.0; at the end.

A method is called like this:
Code:
somewhereToStoreTheReturnedValue = methodname("arguement value");

Easy, right? If you want to run a method which is inside an instantiated class (or a static method), we can do it like this:
Code:
Car myNewCar = new Car();
myNewCar.refillPetrol(18.0);
double mileage = myNewCar.getMileage();

Modifiers

In the code, you will notice these 3 variables declared:
Code:
private float mileage;
public String manufacturer = "";
private float petrol;

Now, you might be wondering what these random private and public words are. they are known as modifiers, and control the behaviour of the variabl/objecte you are declaring. Here are some common modifiers:

- public. This modifier allows the variable to be accessed directly from other classes, the value to be read and modifier, etc. This is often discouraged because the class then has no control over what changes are made, so we often use "getter" and "setter" methods to change the variables with checks on what they are being changed to.

- private. As you might have guessed, this is the opposite of public. This modifier allows only the code in the class to read and change the variable. Things outside the class do not know the variable exists, and cannot access it, so we must create getter and setter methods to read and change the value of private variables. For example, mileage is a private variable, so I created a "getMileage()" method to read the value from outside the class.

- protected. This is somewhere in the middle of private and public. This lets only the class and its children classes access the variable, but not other classes.

Tip: It is good practice to use the use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
Access levels
1a3NWRG.png

- static. This modifier on an object means that only ONE copy of that object is created in the program. If we created a static variable in the car class, then no matter how many cars we instantiated, all the instances of that variable would actually have the same value, and changing one would change the others, because they are all the same. Static methods cannot access non-static methods.

- abstract. This is used in a class of method declaration to force that class to be inherited, before it can be instantiated, for example if the method needed to be changed and could not be used on its own (like if we created an animal class, we cannot create a new animal, we would instead have to extend it to make a cat and then create a new cat)

- final. This is used to make something unchangeable. A final variable is a constant, a final method cannot be overridden and a final class cannot be subclassed.

There are a few other modifiers, but these are probably the most common. I will explain the others if we come across them later. Modifiers are keywords in Java, so they cannot be used as variable names - they are set aside by Java for their specific purpose. Other keywords can be found here: You do not have permission to view the full content of this post. Log in or register now.
 

Attachments

Packages

Packages are designed to organize your classes and to avoid conflicts between things with the same name. They are similar to "namespaces" in languages like C#.
You can have separate packages for different areas of your projects. All classes are contained in packages, and you can use code from other packages by adding an "import" statement at the top of your class.
For example, to use the BufferedReader object in your code (to read from a file, etc.) we can import it to our project. It is part of the java.io package, so we simple add this line at the top of the code:
Code:
import java.io.BufferedReader

If you want to import everything inside a package, you can use the wildcard character (*):
Code:
import java.io.*;

When creating your own packages, use unique and logical names. It is common practice to begin your package names with your domain name in reverse, for example "net.häçkforums.tutorialpackage", because that ensures it will not conflict with packages created by other people.

The java packages come with the JDK, and provide you with the majority of functionality. To use code created by other members, you can add the code as a library to your project.
You can either add a JAR file or another project as a library for your project, by right clicking on your project in the package explorer > Properties > Java Build Path > Libraries tab > Add JARs / External JARs / Libraries. Once the library is added to your project, you can use the objects and functions in it by importing them wherever they are required, as we just did.

If you don't want to import a package in your code, you can still use it by calling it from its package. We did this in the hello world program:
Code:
System.out.println("Hello World!");

println() is part of the System.out package, so we could have written import System.out; at the top of the program, but we just called it directly.

When naming a package, Java naming conventions state to only use lowercase letters.

Operators

= - Assignment. This is probably the most important operator in Java. It is mainly used when giving a variable a value, and when initializing an object. The assignment operator can be combined with many of the operators below to shorten expressions. Operators like this are +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=. For example:
Code:
int example = 1;
example = example + 3; //add 3 to example and store the result in example
example += 3; //Same as the above line, but shorter and easier to read
//EXAMPLE WILL NOW BE 1 + 3 + 3 = 7

+ - Addition (and string concatenation)
- - Subtraction
* - Multiplication
/ - Division
% - Division Remainder / Modulus operator

++ - Increment operator. Increments a value by 1.
-- - Decrement operator, Decrements a value by 1
The increment and decrement operators can be used both before and after the variable, respectively called Prefix and Postfix. The main difference is when the operation takes place - prefix takes place before the value is used, postfix takes place after.

== - Equal to. Returns true if the 2 values are equal
!= - Not equal to. Returns false if the 2 values are equal.
> - Greater than. Returns true if the left value is greater than the right value.
>= - Greater than or equal to. Returns true if the left value is greater than, or equal to, the right value.
< - Less than. Returns true if the right value is greater than the left value.
<= - Less than or equal. Returns true if the right value is greater than the left value.

&& - AND. Returns true if both sides are true.
AND - Same as above
|| - OR. Returns true if either side is true.
OR - Same as above.
! - NOT. Returns true if given false, returns false if given true (inverts the value of a boolean)

instanceof - Compares an object to a specified type. Returns true if the object is an instance of the given type.

~ - Binary Ones Complement Operator is unary and has the effect of 'flipping' bits - 1s become 0s.
<< - Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>> - Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
>>> - Shift right zero fill operator. Same as >> except shifted values are filled up with zeros.
& - Binary AND Operator copies a bit to the result if it exists in both operands.
^ - Binary OR Operator copies a bit if it exists in either operand.
| - Binary XOR Operator copies the bit if it is set in one operand but not both.

Binary (also known as Bitwise) operators, as their name suggests, operate on a binary level. Here is an example, using the Bitwise exclusive or operator: 5^6
5 in binary is 101 and 6 in binary is 110. If we use the ^ operator, the result is 011 because xor returns 1 (true) if only one of the digits is a 1, otherwise it returns 0 (false):
101
110
-----
011 = 3

space

Comments


Comments are written in a Java program purely for humans. The compiler ignores them completely. They are just there to explain code to others, to help make it understandable or easier to read. Comments in Java are the same as comments in C++. There are three different styles of comments: a single line style marked with two slashes (//), a multiple line style opened with /* and closed with */, and the Javadoc commenting style opened with /** and closed with */. The Javadoc style of commenting allows the user to run the Javadoc executable to compile documentation for the program. I won't cover Javadocs in more detail, but they are very helpful in providing documentation of methods, etc in your code. Here is some example code to show comment usage:
Code:
// This is an example of a single line comment using two slashes

/* This is an example of a multiple line comment using the slash and asterisk.
This type of comment can be used to hold a lot of information or deactivate
code, but it is very important to remember to close the comment. */

/**
* This is an example of a Javadoc comment; Javadoc can compile documentation
* from this text. Javadoc comments must immediately precede the thing being documented.
* An example of a method written in Java, wrapped in a class.
* Given a non-negative number FIBINDEX, returns
* the Nth Fibonacci number, where N equals FIBINDEX.
* @param start The number to add 3 to
* @return The number with 3 added
*/
public int addThree(int start) {
    return (start + 3);
}

In eclipse, javadocs are shown in a popup when you hover over a method. For example, here is the Javadocs for the println method we used in HelloWorld:
FsudWHE.png

There are some other useful javadoc codes like @author, since, SEE which you can research and use if you like.

Enums

Enum stands for Enumeration, and it is very useful in a Java program. Enums are used to create your own descriptive values. An enum is declared like this:
Code:
public enum Color {
     ORANGE,
     RED,
     YELLOW,
     GREEN
};
It can then be used just like value:
Code:
Color example = Color.ORANGE;

Notice that this is much easier to read and understand than, for example, using integers to represent the colors (1 is orange, 2 is red, etc.). Enums are very similar to a class of constants, but are easier to declare and have some useful functionality you don't need to write yourself. Enums can also be used in Switch statements.


Conditional statements


Conditional statements are extremely important. They allow a program to make decisions and change direction based on input.

The first type of conditional statement is an If-else loop. This checks if a condition is true, and if it is then it does something. If it isnt, it will check to see if the "else if" statement is true. If none of the else if statements are true, it will do the else statement:
Code:
int test = 3;
if(test == 2) {
    //test is not 2, so this will not be run
}
else if (test == 3) {
    //test is 3 so this will be run
    doSomething();
}
else {
    //this is not needed, because it will only be run if test was not 2 or 3.
}

You can use as many "else if" statements as you like. Else and else if statements are optional - you can just have an if statement by itself if you like. That is the same as leaving else{} empty. The condition in an if statement can be very simple or very complex using many conditional operators like AND and OR. You can have functions in the condition too, to check what they return.
It is also possible to nest if() statements inside other if statements, if you want to test for multiple scenarios.

The ternary operator is very similar to an if else statement in one line:
Code:
condition ? trueValue : falseValue
For example, if we want the minimum value of 2 numbers a and b, we can do this:
Code:
minVal = (a < b) ? a : b;
If a is less than b, it will return a otherwise it will return b.

The next conditional statement is a switch case statement. A switch statement is given a variable, and will choose the appropriate action based on the value of that variable. Here is an example of a switch statement:
Code:
Color colorExample = Color.RED;

switch(colorExample){
    case Color.ORANGE :
      //colorExample is orange, so do something
      doSomethingOrange();
      break;
    case Color.RED :
      //colorExample is red, so do something else
      doSomethingRed();
      break;
    default :
    doSomethingElse();
}

In that example, we used the enum Color from the enum section. colorExample is the expression the switch is testing. You can use objects and all datatypes in a switch statement. It will find a case with the same value as colorExample and run the code in that case. You can have as many cases as you want. The default case is similar to an else statement - it will be run if none of the other cases are run. It is optional.
You will notice the break statements in each case. That makes the program leave the switch statement after the case it wants. You can leave the break statement out, which will make the program run the matching case and EVERY other case after it until it finds a break statement. This can be helpful, for example if we wanted to test for the letter "A", we could do this:

Code:
case 'a' :
case 'A' :
    doSomething();
break;

So this will run doSomething() if it is a OR A because if it is 'a', there is no break, so it will keep running the 'A' statement too.


Loops


Loops are very useful in Java for performing repetitive actions over and over, so we do not need to write a lot of code.

The first loop we will see it the while loop. This loop will check the condition, and if it is true it will perform the code in the braces. It will repeat that process over and over until the condition changes to false.

Code:
while (condition) {
    // Do stuff
}

An example of a while loop usage:
Code:
while( x < 20 ) {
      System.out.println("value of x : " + x );
      x++;
}
Notice, we always check if x is less than 20 and will break out of the loop as soon as (x < 20) is false. Every loop, we print out the value of x and then increment it.

If the condition is always true (for example, true or 1==1), then the loop will loop for ever. This is known as an infinite loop, and could crash your program. You should always make sure there is a way to exit the loop.

The second type of loop is a for loop. A for loop is useful for iterating or performing a task a set number of times:

Code:
for (initialization; termination; increment) {
    //do something
}
There are 3 parts inside the parenthesis. initialization is run before the start of the first loop, and is used to declare iteration variables. termination is the condition to check, and when this is false the loop will stop. increment is the commands to run after each loop, usually used to increment the iterator for the next iteration.

An example of a for loop:
Code:
for(int i=0; i<10; i++){
      System.out.println("Count is: " + i);
}
In this loop, we first declared a new variable i to use as the iterator variable, and gave it a value of 0. the condition is (i < 10) so the loop will run until i is greater than or equal to 10. after each loop, i++ increases i by 1. each loop, we print the value of i to the console.

There is another type of for loop which is often used for iterating through elements of an array or list. This is the same as a foreach loop in other languages, and is used like this:

Code:
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
     System.out.print(x);
}

This will loop through every integer in numbers[], and for each number, it will print it out to the console.

The third type of loop is a do-while loop. This loop is very similar to a while loop, except that the statement is always run AT LEAST ONCE because the condition is checked at the end:
Code:
do {
     //stuff to do goes here
} while (expression);

I won't explain the do...while loop any more because it is so similar to the while loop.

There are 2 important keywords related to loops: break and continue. The break keyword is used to stop the entire loop. As you know, it is also used in switch statements to break out of the switch statement.
The continue keyword skips the rest of the iteration it is used in, but the loop will keep looping. For example:

Code:
for(int i = 0; i < 5; i++) {
      if( i == 3 ) {
          continue;
      }
      System.out.println(i);
}

This will give: 0,1,2,4,5 because when i is 3, the continue statement will skip the println command and move on to the next interation.
 

Attachments

Objects, primitive types, and conversion


In the variables section, we saw the different types of variables in java. The variables we saw are "primitive types", and were written in full lowercase. You will see that there are also some variables with the same name, but with a capital letter, such as "String" instead of "string". These are the object versions of the primitive types.

String can be used in the same was as string, but the big difference is what else it can do. string is a primitive type so all it does is hold a value, but String is an object and it has a lot of functions inside it which are very useful. Here is an example:
Code:
String example = "Example String";
int length = example.length(); //get the length of the string
char firstChar = example.charAt(0); //get the first character
example = example.toUpperCase(); //example will now be "EXAMPLE STRING"

You can see why this is much more useful than just using "string".

What we are using now is technically "String literals". This is different to using String as an object and declaring a new string like this:
Code:
String example = new String("Example string");
While you are allowed to do that, it comes with some issues - for example, comparing 2 strings using the == operator will not work the way you want it to. It is better to just use String example = "abc";

If you want to convert between 2 types of variable, this is done by "casting" or "parsing". There are a few different situations we might have:

1. Casting from a numeric variable to another numeric variable of LESS PRECISION. This is called downcasting, and we must do it "explicitly", to force Java to make the conversion even though we might lose some data, if the new variable cannot hold all the data:
Code:
double a = 10;
int b = (int) a;

Double can hold bigger numbers than int, so we have to use "(int)" to cast the double to an int.

2. Casting from a numeric variable to another numeric variable of GREATER PRECISION. This is called upcasting, and java can do it implicitly, because the new variable will always be able to hold all the data:
Code:
int a = 10;
double b = a;

We do not need to tell java to do this explicitly, it will do it automatically.

3. Casting between completely different types (e.g. String to int or float to double). To do this, we can use some of the methods we just learned about inside the "Capital letter" Integer or String classes, etc.
Code:
int a = 10;
String example = String.valueOf(a); //OR:
example = Integer.toString(a);

example will now be "10". We can also cast the other way:
Code:
String example = "1234";
int a = Integer.parseInt(example);
a will now hold 1234.


Arrays


Arrays are used to hold a lot of related values of the same type.
This is how you declare an array in Java:

Code:
int[] myIntArray = new int[3]; //declare an array with 3 empty spaces
Code:
int[] myIntArray = {100,-4,3}; //declare an array with values 100, -4, 3 (3 spaces)
Code:
int[] myIntArray = new int[]{1,2,3}; //same as second example, with values 1,2,3

In all 3 of the lines above, we created an array with 3 "spaces". An array's size cannot be changed after it is declared in Java. Elements of the array can be accessed like this:
Code:
int firstValue = myIntArray[0]; //firstValue will be 100 if we are using the array from the second example above

ALWAYS REMEMBER: when you declare an array of 3 spaces, the index of each of those spaces starts from 0 not 1, so it will be 0,1,2 not 1,2,3. It is a very common mistake for beginners to declare an array of size 3, and then try to use array[3].

We can also create multidimensional arrays like this:
Code:
String[][] myStringArray = new String [5][5];

myStringArray[0][0] = "a string";
myStringArray[0][1] = "another string";

Multidimensional arrays are very useful in situations such as an array representing a chessboard. We can declare a chessboard array like this:
Code:
String[][] chessBoard = new String[8][8];

Then every square is represented by an element in that array. If there was a king on the 5th square of the 4th row, we could write:
Code:
chessBoard[3][4] = "king";

Remember, elements start from 0 not 1, so the row index is not 4, but 3!

There is another useful type often used instead of arrays, and that is List. A list is popular because there are many useful functions for it, and you can dynamically change its size by adding and removing elements. One implementation of List is ArrayList, so this is how we would declare a new list and store an arraylist in it:
Code:
List<String> myStringList = new ArrayList<String>();
myStringList.add("a string");
myStringList.remove(myStringList.indexOf("a string"));

In that code, we declared a new list of strings. Then we added a new String to the list, with the value "a string". On the third line, we want to remove the string we just added. Remove() takes an index, so we first have to find the index of the string we just added using indexOf("a string"). I think you can see why lists are popular replacements for arrays! Another common type of list is LinkedList. Both can be stored in List and are useful for different things.

Storing an ArrayList and a LinkedList in a List variable is a good example of a key OOP concept in Java: polymorphism. LinkedList and ArrayList both implement the List interface (an interface is like a template, a bit like an abstract class), so both can be stored in a List variable.

This is how you declare an interface:
Code:
interface Car {
    void turnLeft();
}
And this is how you implement an interface (using the "implements" keyword):
Code:
class Toyota implements Car {
    void turnLeft() {
      //do something
    }
}
Implementations of an interface must define all functions inside the interface.


Input/Output and GUIs


Input and output are essential parts of an interactive program. We can code a GUI (Graphical user interface) or interact using the command line. We can also interact with files and network streams. A lot of the useful functions are found in the java.io package. When interaction with the command line, we use System.out and System.in packages. When creating GUIs, we usually use the swing or javaFX libraries. All these things are large topics which I will not cover greatly here.

First, let us look briefly at input and output in the command line.
Code:
import java.util.Scanner;
public class Main
{
    public static void main(String [] args)
    {
      Scanner myScanner = new Scanner(System.in); //make a new Scanner to read from the console, giving it System.in to read from
      System.out.print("Input an integer: "); //show a message to the user
      int userInput = keyboard.nextInt(); //read the input
      System.out.println("You entered " + userInput); //output the nnumber the user entered
    }
}

That is quite simple, we just use scanner to read and println to write to the console.

Here is a basic GUI using swing. You will need to import javax.swing.* to use swing. You will also need to import java.awt.event.* for this code:
Code:
JFrame frame; //this is the java swing version of a window.

  public static void main(String[] args){
    frame = new JFrame("Hello World"); //Create a new frame with Hello World as the title
    JButton button = new JButton("Click Me"); //add a new button
    button.addActionListener(new ButtonClickedAction()); //add an event listener to the button to check when it is clicked. See below
    frame.add(button); //add the button to the Jframe
    frame.setSize(400, 400); //set the size of the jframe to 400 x 400
    frame.setVisible(true); //show the jframe
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set it to exit when the frame is closed.
  }

  public class ButtonClickedAction implements ActionListener{
    public void actionPerformed(ActionEvent e){
      JOptionPane.showMessageDialog(frame,"Hello World"); //when the button is clicked, show this message box
    }
  }

As I said, GUIs are a big topic and you will need to read some more tutorials to learn more.

To read and write data from a file or network, we use Data streams. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Some commonly used stream types are FileInputStream and FileOutputStream.

Lets have a look at a program to sopy one file to another:
Code:
import java.io.*;

public class CopyFile {
   public static void main(String args[]) throws IOException
   {
      FileInputStream in = null;
      FileOutputStream out = null;

      try {
      in = new FileInputStream("input.txt");
      out = new FileOutputStream("output.txt");

      int c;
      while ((c = in.read()) != -1) { //keep reading from the input file until we reach the end of the file. We get -1 at the end, which will make the loop stop.
      out.write(c);
      }
      }finally {
      if (in != null) {
      in.close(); //make sure the inputstream is closed
      }
      if (out != null) {
      out.close(); //make sure the outputstream is closed
      }
      }
   }
}

Firstly, notice that we imported the io package at the top. This is the main function of the program so it will be run when the program starts. We surround our input and output using try statements too, in case there is an error when reading or writing to the file. Both the streams are ByteStreams, so they deal with bytes not strings of other types. That is why we read the data and store it in an int.

Instead of using ByteStreams, we can also use readers and writers. These deal with types rather than bytes. A good example is using the BuffedReader to read from a text file line by line:
Code:
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}
This example is slightly more complicated. You will notice that we used both FileReader and BufferedReader. FileReader is the input stream to read from the file, and BufferedReader uses a FileReader to "buffer" the input and read line by line as we need. This program will print each line of the file input.txt to the console. Also notice the slightly more complicated condition in the while loop? "(line = reader.readLine()) != null". It does 3 things at once, it reads the line, stores the line in "line" and then checks if line is null.

Check out ๖ۣۜLooka's stream tutorial here for more information.


Errors and Try/Catch


If we want to perform a risky action in Java, such as opening a file, we might get an error at runtime. This error could be caused by a lot of things, for example the file being open in another program. This is what we use Try catch statements for.

Everything risky can be put in a try statement. Java will try to run the code, but if it encounters an error, then it will go to the catch statement to deal with the error. We can also include a finally statement, to run no matter if there was an error called or not afterwards. The finally block is usually used to close input streams, etc, to ensure they are not left open if an error occurred.

This is an example of a try catch finally statement, in which we try to parse a string to an integer. Parsing a string to an integer might throw a NumberFormatException, and if it does, we write the message from the error to the console :
Code:
try {
    Integer.parseInt(numString);
}
catch(NumberFormatException numExc) {
    System.out.println(numExc.getMessage());
}

It is possible to declare resources inside parenthesis in the try block like this:
Code:
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
      return br.readLine();
}

This is called try-with-resources. The resources declared in the try block are ensured they are closed at the end automatically - in this example it is important because BufferedReader should always be closed after use.

We can also write functions which throw errors themselves, to force code in another place to deal with the error rather than the function itself. We write "throws exceptionNameHere" in the function declaration, and use the "throw" statement to throw the exception should we need to. For example:
Code:
public void throwSecurityException(bool throwAnException) throws SecurityException{
      if(throwAnException){
      throw new SecurityException();
      }
}

Java native interface (JNI)

The Java Native Interface (JNI) allows you to call native code (ie. a C function). You might want to do this if you want to use a library written in C in your program code, or if you want to use some low level native code to accomplish something that would be hard or impossible to do in Java.

JNI is quite an advanced Java topic so I will not cover it here. It also requires knowledge of C code. You can do some research online to learn more about how to do this.

Here are a few tutorials:
- You do not have permission to view the full content of this post. Log in or register now.
- [Tut] Java Native Interface basics by s0ap_scum


From here...


Now you know the basics of Java, what do you do? From here, the best thing to do is keep reading, researching and practicing.

I suggest that you find a project idea, start coding, and whenever you find something you don't know how to do, LOOK IT UP. That is the best way to learn. If you can't find something on google, try posting a question thread here on HF.

I suggest that you read whatever you can to learn more about Java - whether that be tutorials, source code, ebooks, books or other peoples questions. Have a look at this collection of Java resources here.
 
ng kakagamit ko ng drag and drop na programming language (vb addict) prang tinatamad na ako mag manual code lols,, kakamis to nung 1st year,, btw tnx,, try naman ng bago
 
ng kakagamit ko ng drag and drop na programming language (vb addict) prang tinatamad na ako mag manual code lols,, kakamis to nung 1st year,, btw thanks,, try naman ng bago
Marami pa akong pinost na thread sir hanapin mo nalang haaahahaa
 
Status
Not open for further replies.

Similar threads

Back
Top