Jump to content
xisto Community
Sign in to follow this  
eyvind

Programming With Coffee Begining Programming with Java

Recommended Posts

Since Java is a complete programming language, one tutorial is not going to cover everything. However, I will try to cover the basics and possibly extend on them later, and will assume you know very little about programming. If something seems unclear, it is because I am not very good at explaining. Read on and if you reach the end of the tutorial and still donât get it, tell me. Tell me even if you figure it out, but something is unclear, I will try to fix it.

 

Any style guides/conventions are not mandatory at all, itâs just how many programmers write their code and makes it easy to read, understand, and maintain code.

 

To begin

 

To begin, you will need to download the Java virtual machine, the program that makes it possible to run your Java programs. You can find the latest version here (http://forums.xisto.com/no_longer_exists/).

 

Second you will want to download a Java editor. Any text editor would be fine however a specialized Java editor is a help when you are learning Java, and you wonât have to deal with the command prompt or anything like that, which I think is a hassle anyway.

 

For a start, I think you should download JCreator, a free, but excellent IDE (Integrated Development Environment). I recommend downloading JCreator and using itwhile going through this tutorial. You can get JCreator here: http://www.jcreator.org/download.htm. I recommend downloading the JRE from Sunâs website, not the JCreator website.

 

Some preliminary basics

 

Here are some basics you should know before reading on.

 

Java uses regular operators such as +, -, /, and *, along with a few others, which are not important. Strings (you will learn what strings are later) are concatenated (added, put together end to end) with a â+.â And any basic arithmetic can be done using these operators, parenthesis, decimal points, values, and variables.

 

Comments (words that comment on the code without Java caring what they say) are begun by â/*â and ended by */â, or, if the comments are only on one line, â//â will suffice.

 

Every time you finish writing a program you compile the program (under the build in JCreator). Then you can run the program and see miracles happen with your new, working program. However, if you made some coding errors (f. ex. you spelled something wrong) it will give you an error message that is displayed at the bottom of the screen in JCreator and you will have to fix the error.

 

Your first program

 

Here is a simple Java version of the traditional âHello, World!â program.

 

public class Hello {    public static void main(String[] args)    {       //Iâm a comment!       System.out.println(âHello, World!â);    } }

 

In the first line, in the signature of the class, âpublicâ means that the class can be used, seen, by all other classes. For now, always write âpublic.â Class denotes that the code enclosed in the following curly braces (â{â and â}â) is a class. Hello is the name of the class; this can be any combination of letters numbers or the underscore character (â_â), good style dictates class names be capitalized. The body of the class is enclosed in curly brackets (â{â and â}â).

 

The main method is a special method that is run by java when you execute (run) the class: its signature has to be what I wrote, exactly.

 

System.out is a standard object with a method println which takes a String parameter, in this case âHello, World!â

 

Strings

 

A string is simply a series of characters. Some characters have special meaning in Java (like the quote character) and require whatâs called an escape character in front of it. In Java this character is the backslash character. So if you would like to print out

 

He said, âHello!â

 

verbatim, you would have to write, within the println statementâs parenthesis

 

âHe said, \âHello!\ââ

 

This might seem a little bit confusing and it can get even worse if you have long strings with lots of escape characters.

 

There are some special escape-character combinations, backslash-and-character pairs that do some helpful things. For example, â\tâ inserts a tab and â\nâ inserts a new line. There are quite a few other such characters, but \n is the most important one these are the important ones.

 

Variables

 

Now, letâs move on to variables.

 

To declare a variable, you type the data type of the variable, the name, and a semicolon. Then to initialize it, to assign a value to it, type the name of the variable, an equals sign and the value you want to set the variable to, and a semicolon as always. You can do initialization and assignment in one statement by typing the data type, the name, an equal sign, the value, and a semi colon.

 

There are numerous data types in Java. These are divided into two separate groups: primitive data types and object reference types. Primitive data types include:

 

byte

Byte-length integer

minimum: -128

maximum: 128

 

short

Short integer

Minimum: -32,768

Maximum: 32,768

 

int

Integer

Minimum: -2,147,483,648

Maximum: 2,147,483,648

 

long

Long integer

Minimum: -9,223,372,036,854,775,808

Maximum: 9,223,372,036,854,775,808

 

float

Single-precision floating point

A 32-bit IEEE 754 number

 

double

Double-precision floating point

A 64-bit IEEE 754 number

 

char

A single character

A 16-bit Unicode character

 

boolean

A boolean value

Either true or false

 

As you can see there are quite a few and you might wonder why you would want all of them, why need all of those that canât go above 128, whatâs the point? Well, there sometimes comes up situation in your programming where such restrictions can come in handy, and of course you donât want to take up more memory than you need.

 

There are also different types of variables. There are instance variables (global variables in an object), there are class variables (denoted by the keyword âstatic,â these are variables global to all objects of that class), there are constants (denoted by the keyword âfinalâ and cannot be changed). Constants should be written with all capital letters and an UNDERSCORE for separating words, for example. Instance variables ae just like regular variables, except they are declared in a class, not it a method, and used in the whole class, by any methods, not just one. a class variable is a type of instance variable.

 

A class variable:

 

public static int variable;

 

A constant:

 

public final int CONSTANT;

 

You can combine the two:

 

public static final int CONSTANT;

 

to get a constant variable that is the same for all objects in a class, this is usually how you are going to use a constant in a class, as a class constant.

 

Never use magic numbers in your code (except for maybe -1, 0, 1, and 2 to account for small errors that come up because of programming technicalities). What I mean by magic numbers is numbers that have no apparent meaning, for example in assigning a value to a variable, you subtract 365, what does this 365 come from? Use constants like DAYS_IN_YEAR.

 

So, instead of

 

somevariable = mybirthday + 365;

 

use

 

somevariable = mybirthday + DAYS_IN_YEAR;

 

There is a whole other set of variables, reference variables. Object reference data types are a little different, and a little harder to explain. I will have to explain OOP (Object Oriented Programming) first.

 

OOP

 

So what is meant by âobject oriented?â Object oriented means that the language supports encapsulated programming. (That doesnât make anything much clearer.) What I mean by that is that the programmer separates his program into cohesive and reusable parts. In Java these parts are: classes, objects, methods, and variables.

 

Classes are like a definition for creating objects. They define the guidelines for creating objects, for example what methods and instance variables the object will contain when the object is created.

 

The object is created by a client program which can create as many objects of a class as it wishes, and then use its methods to do stuff.

 

This is how you create an object, letâs say the class name is called âDataâ:

 

new Data();

 

you can story the returned object in a variable, using an object reference variable which will be discussed later.

 

A method is like a small program that performs a task, such as adding numbers and printing the result to the screen. Methods can be as simple as returning a value to the client program, or as complex as encrypting a letter. Methods can take whatâs called parameters, which the client passes to the method (I will demonstrate momentarily). The method may then do what it wants with these values. The method puts some restriction, however, on what values can be passed. Here is an example of a method in a class Adder that adds two numbers together and returns the sum to the client program:

 

public class Adder {    public static int add(int num1, int num2)    {       int sum = num1 + num2;       return sum;    } }

The âintâ after âpublicâ means that the method will return an int. "Static" means that you do not need to create a new object to call this method, oyu can call it directly from the class, as you will see below. ânum1â is the first variableâs name and ânum2â is the second variableâs name. The âintâs in front of the variable names (num1 and num2) tells java that this method obly accepts an intfor these two variables. The values passed will be stored in the variables num1 and num2, and are discarded when the method returns (stops, comes to the end of itâs code, or returns a value). âint sum = num1 + num2;â stores the sum of num1 and num2 in the int variable âsum.â âreturn sum;â returns the value of sum to the exact location the method was called in the client program.

 

Here is an example of a client program using this method

 

public class AddAndPrint {     public static void main(String args[])    {       System.out.println( Adder.add(1, 4) );    } }

 

Here the client program AddAndPrint asks the method add to do whatever it does with the numbers 1 and 4, and then prints the returned value to the screen. So, on the screen you will see is a lonely â5â in the upper left hand corner followed by a (relatively) brutal message âPress any key to continueâŚâ and a blinking cursor.

 

When you call a method you write the object name (the variable name that points to the object) followed by a period, the method name and the parameters enclosed in parenthesis.

 

object.method(parameter1, parameter2, parameter3)

 

Letâs move on to instance variables. Instance variables are variables that can be accessed or modified by any method in the object. Instance variables are usually private, so clients canât see or use them. Would you want someone strange person mess with your private parts?

 

The convention for naming classes, methods, and variables are as follows (objects are never named except in their variables):

 

Classes â capital first letter with the rest being lowercase and uppercase letters, use uppercase letters to signify the start of new words.

 

Methods and variables â first lowercase letter, occasional capital letters

 

Object reference data types

 

Object reference data types, as I have said, are a bit different. Object reference data types are written exactly as the name of the class of the object the variable will point to. Notice I said âpoint toâ and not âhold,â object references point to a location in memory instead of really âholdingâ the object.

 

There are quite a few standard classes that you can use in your programs without writing defining them, for example, String, Character, Integer, and Double. The last three are all object equivalents of their respective primitive data types. They are called wrapper classes and are used in special situations which I wonât get into now.

 

When you define object instance variables you write the class name, the variable name, an equals sign, the keyword ânew,â and the class name again followed by parentheses. Here is an example of a declaration of a reference variable:

 

Data number;

 

To store objects in a reference variable:

 

Data number;

 

number = new Data();

 

or

 

Data number = new Data() ;

 

Enclosed in the parentheses are the parameters that the class will use in creating the object. The method that handles these parameters is called the âconstructor.â

 

When you define a class you always want a constructor. If you donât, Java will, without you knowing it, add an empty constructor that takes no parameters. The constructor is just like any other method, with some exceptions. The constructorâs name has to be the same as the class, and there is no return type and of course, it has to be public. If it helps you conceptualize how the constructor works, you can say that it automatically returns the newly created object when it is done executing, so it has its own class as itâs return type.

 

Your second program

 

The âSpeakerâ class:

 

public class Speaker {    //instance variable    private String sayWhat;    //Constructor    public Speaker(String saythis)    {       //assigns the value of âsayThisâ toâsayWhatâ       sayWhat = sayThis;    }    /* The return type âvoidâ means that    the method does not return anything    */    public void sayThis(String whatToSay)    {       System.out.println(whatToSay);    }    //returns and prints out the value of âsayWhatâ    public String sayWhatNow()    {       System.out.println(sayWhat);       return sayWhat;    } }

The client program SayStuff:

 

public class SayStuff {    public static void main(String[] args)    {       //create a new Speaer object       Speaker speaker = new Speaker(âHello,World!â);       //tell the speaker to say âWhatâs up?â       speaker.sayThis(What's up?");       /* tell the speaker to tell you           what it has been âtaughtâ to           say, in this case âHello, World!â       */       speaker.sayWhatNow();    } }

 

 

The Speaker class contains the following things:

 

A String instance variable, sayWhat

A constructor taking a value for sayWhat

A method printing a passed String to the console window

A method printing and returning the content of sayWhat

 

The âdriverâ class, SayStuff does this:

 

Creates an instance of the Speaker class with the parameter âHello, World!â

Calls the method saythis with the parameter âWhatâs up?â

Calls the method saywhatnow

 

This program prints out:

 

Whatâs up?

Hello, World!

 

More on decision making, loops, and OOP coming soon.

Share this post


Link to post
Share on other sites

This is very informational i totally agree with every thing i had read with but i would try to shorten it up it is to much for the average guy to read Peace out ymmij

Share this post


Link to post
Share on other sites

Yeah, :P (I haven't even gotten to decision making and loops), I have gotten the same response other places too. People who look for tutorials (as opposed to books, I have always prefered books) usually want something short and simple that will still teach them the essentials. I will try to make a shorter version, and add the if, switch, v-somethingorother statemtns, and for, while, adn do loops (man I can't live without them, how could I net have put them in my tutorial yet!!!)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.