Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 105,404 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 1,788 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Starting with Java

 
Reply to this topicStart new topic

> Starting with Java, useful for beginners, introduces to the basics

alpha02
Group Icon



post 2 Jan, 2007 - 10:24 PM
Post #1


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 - 08:34 PM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

William_Wilson
Group Icon



post 3 Jan, 2007 - 07:20 PM
Post #2
Not a bad tutorial, first large collection of basics for java.
*Your section on files is a little general, using only the file option and not mentioning the need for serializable objects. (all objects implemented by java itself are serializable)
*also not explaining error handling, even though it is used in files.
Go to the top of the page
+Quote Post

alpha02
Group Icon



post 3 Jan, 2007 - 08:35 PM
Post #3
Thanks for your feedback, I added an explanation of the try...catch expressions.
Go to the top of the page
+Quote Post

1lacca
Group Icon



post 4 Jan, 2007 - 07:48 AM
Post #4
Nice start, but I would like to stress the importance of coding conventions. Sun has good guidelines, that make your code easier to read, and later when collaborating with other developers it can save a lot of time and money. And the reason I was talking about so long is the capitalization of class names (prog1 would be Prog1, etc.) This will be even more important if you use static imports (since java 1.5), a lot of confusion can be avoided. I am not going to list everything here, just wanted to mention that these rules should be followed right from the first steps, even before stated explicitly.
Go to the top of the page
+Quote Post

Darshan P V
*



post 20 Jun, 2007 - 02:37 AM
Post #5
QUOTE(1lacca @ 4 Jan, 2007 - 07:48 AM) *

Nice start, but I would like to stress the importance of coding conventions. Sun has good guidelines, that make your code easier to read, and later when collaborating with other developers it can save a lot of time and money. And the reason I was talking about so long is the capitalization of class names (prog1 would be Prog1, etc.) This will be even more important if you use static imports (since java 1.5), a lot of confusion can be avoided. I am not going to list everything here, just wanted to mention that these rules should be followed right from the first steps, even before stated explicitly.

Really it helps me a lot .
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 8/20/08 05:04AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month