Java basics tutorial
CLASS 101
Every class in Java is a compiled .class file. When you develop, you use a .java file, which will be compiled to a .class file afterwards. The .class or .java file must have the same name as the class in it. As an example, the contents of prog1.java:
CODE
/* Contents of prog1.java */
public class prog1 //declare class (name is prog1)
{
public static void main (String args[]) //when the program starts
{
//some code...
}
}
CLASS 102
Objects are quite easy to declare, as they are a class name with methods, constructors... At first it may seem confusing to you, but you will get familiar. The syntax is object.method(). Objects are declared as a class and the methods are inside it. An example of an account object in prog2.java:
CODE
/* Contents of prog2.java */
public class prog2 //declare class
{
public static void main (String args[])
{
account my_account; //account object handle
my_account = new account(); //instantiate (create) object
my_account.deposit (25.00); //call the deposit method
}
}
/* Contents of account.java */
public class account
{
protected double balance; //variable of balance
public account(double amount) //constructor
{
balance = account; //set balance to account param
}
public account() //overloaded constructor
{
balance = 0.0; //set balance to zero
}
public void deposit(double amount) //method to deposit
{
balance += amount;
}
public double widthraw(double amount) //widthraw money
{
if (balance >= amount) //possible?
{
balance -= amount //retire money
return balance;
}
else //not possible
{
return 0.0;
}
}
public double getbalance() //get balance
{
return balance;
}
}
As you may have noticed, the function with the same name than the class is the constructor, what is called when the object is created. Also, there are two constructors in this one. This is callled function overriding. You can pass a parameter (amount) when creating the object, or you can pass none. These are the two choices, and so the two constructors. It is important to understand this. By the way, System.out.println simply prints text on the screen. Now, all this put togheter in a script:
CODE
/* Contents of prog2.java */
public class prog2 //declare class
{
public static void main (String args[]) //main
{
account my_account = new account(); //create object
my_account.deposit (80.00); //deposit money
System.out.println ("Balance: " + my_account.getbalance());
my_account.widthraw (50.00); //widthraw money
System.out.println ("Balance: " + my_account.getbalance());
}
}
CLASS 103
This section will cover file input/output (IO). We will need to import packages. These are other classes with other objects, methods... In this example, we will write some text in a file. Here is prog3.java:
CODE
/* Contents of prog3.java */
import java.io.*; //import IO package
public class prog3 //main class
{
public static void main (String args[]) //void main
{
FileOutputStream out; //out is an object
PrintStream p; //p is an object
try //try this
{
out = new FileOutputStream ("C:\myfile.txt"); //conn
p = new PrintStream (out); //create print stream obj
p.println ("Write this!"); //write text to file
p.close(); //close connection
}
catch (Exception e) //in case of error
{
System.out.println ("Error writing!"); //show error
}
}
}
We saw something new here: the try...catch. This acts as follow: the code between the try brackets is executed, but in case of an error it will jump to the catch block. If no error occur, the catch block won't be executed.
Input is a little different from output. We will now read a file, in prog3.java:
CODE
/* Contents of prog3.java */
import java.io.*; //import IO package
public class prog3 //class
{
public static void main (String args[]) //main
{
if (args.length == 1) //if there is a file
{
try
{
FileInputStream fs = new FileInputStream(args[0]);
DataInputStream ds = new DataInputStream(fs);
while (ds.available() != 0)
{
System.out.println (ds.readLine());
}
ds.close()
}
catch
{
System.err.println ("File not found!");
}
}
else
{
System.out.println ("Invalid parameters");
}
}
}
CLASS 104
We will take back the account object of the class 102. We will extend a class, called class inheritance. Here is InterestBearingAccount.java:
CODE
/* Contents of InterestBearingAccount.java */
import account; //our previous class
public class InterestBearingAccount extends Account //NEW
{
private static double default_interest = 7.95; //constant
private double interest_rate;
public InterestBearingAccount (double amount, double interest)
{
balance = amount;
interest_rate = interest;
}
public InterestBearingAccount (double amount)
{
balance = amount;
interest_rate = default_interest;
}
public InterestBearingAccount() //overloaded
{
balance = 0.0;
interest_rate = default_interest;
}
public void add_monthly_interest() //add
{
balance += (balance * interest_rate / 100) / 12;
}
}
Now, putting the methods of the 2 classes together:
CODE
/* Contents of prog4.java */
import InterestBearingAccount; //object
public class prog4
{
public static void main (String args[])
{
InterestBearingAccount my_account = new InterestBearingAccount();
my_account.deposit (25.00); //from our extended class
my_account.widthraw (10.00);
my_account.add_monthly_interest(); //from our new class
System.out.println ("Balance: " + my_account.getBalance()); //show
}
}
CLASS 105
There is an introduction to one of the most important packages, java.lang. We will cover some of the most important data types, such as Object, Integer, Long, Float, Double, Character, String, StringBuffer, and so on. The first method we will see is toString(). An example:
CODE
double my_double = 3.14;
String my_str = my_double.toString(); //3.14 is now a string
All numeric data types are from the class Number, so they share the same methods. They can all be converted to any other numeric types, with the calls:
int --> intValue()
long --> longValue()
float --> floatValue()
double --> doubleValue()
An example of conversions would be:
CODE
Float my_float = new Float (3.14);
Double my_double = new Double (my_float.doubleValue());
System.out.println (my_double); //print 3.14
System.out.println (my_double.intValue()); //print 3
The Java languages contains several character comparison routines. The names are self-explanatory:
CODE
//character comparison routines
static boolean isDigit (char c);
static boolean isLetter (char c);
static boolean isLetterOrDigit (char c);
static boolean isLowerCase (char c);
static boolean isUpperCase (char c);
static char toLowerCase (char c);
static char toUpperCase (char c);
Useless to explain what they do. Next point: the String object. It is not like numeric type values which share their methods, the String object has its own set of methods. We will now see them:
CODE
//returns the character at offset index
public char charAt (int index);
//compare, returns 0 if there is a match
public int compareTo (String anotherString);
//append anotherString to string and returns value
public String concat (String anotherString);
//returns the length
public int length();
//returns true if begins with prefix
public boolean startsWith (String prefix);
//returns true if ends with suffix
public boolean endsWith (String suffix);
//returns the remainder, start at offset beginIndex
public String substring (int beginIndex);
//returns the string between offsets beginIndex and endIndex
public String substring (int beginIndex, int endIndex);
//returns the lowercase
public String toLowerCase();
//returns the uppercase
public String toUpperCase();
Well, that's all for now, and do not worry if you have difficulties understanding this, I know Java is hard to learn, I made this tutorial as a referrence sheet while learning, and I decided to publish it. I hope it helped you to better understand the basics of object-oriented programming.
This post has been edited by alpha02: 3 Jan, 2007 - 07:34 PM