Nov 23, 2009

Programming With Coffee - Begining Programming with Java

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > MISC (not applicable to above Programming Categories)

Programming With Coffee - Begining Programming with Java

eyvind
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://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=22&PartDetailId=jdk-1.5.0_02-oth-JPR&SiteId=JSC&TransactionId=noreg).

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.com/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.

CODE
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:

CODE
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

CODE
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:

CODE
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:

CODE
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.

 

 

 


Comment/Reply (w/o sign-up)

7JJohnson
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

Comment/Reply (w/o sign-up)

eyvind
Yeah, smile.gif (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!!!)

Comment/Reply (w/o sign-up)


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : programming, coffee, begining, programming, java

  1. Drawing Basic Rectangles
    Using Java! (0)
  2. Sorting
    How to sort data in arrays- examples given in Java (0)
    Sorting- Using Java Language First of all, why the heck should I care about sorting? Easier
    to present data- it is very frustrating to be looking for some information and it is not in order
    Faster searching algorithms- most searching algorithms require looking at every element in a list
    until the requested one is found, but if it is sorted, you can use binary search (I'll explain
    in another tutorial) to drastically cut search time Less memory for searching- there ARE ways to
    increase search time in unsorted lists (with indexing and such), but these take mu....
  3. Programming In Glut (lesson 6)
    Texture filters and lighting (1)
    This tutorial demonstrates how to use texture filters and will let you see the differences of each
    filter. I will also be introducing lighting into this tutorial. We first have to create our
    "bitmap.h" header file with the functions we use to load our bitmaps, this is changed from the last
    tutorial to fit the needs of this one. The first thing to do is to link all of our OpenGL libraries
    and include our needed headers for the functions we will call. CODE #pragma comment(lib,
    "opengl32.lib")//Link to the OpenGL libraries #pragma comment(lib, "glu32.lib") #pragma....
  4. Programming In Glut (lesson 5)
    How to texture map and use keyboard controls. (1)
    In this tutorial I am going to teach you how to texture map your polygons and implement basic
    keyboard control. There is alot of new material in this tutorial and I hope I have explained it
    enough. Before you get started you will want to name a bmp file "image.bmp" or "image" depending on
    your computer settings (if one doesn't work then use the other) and place it in the same folder
    as your project. Now to start we will be making a seperate header file where we will write our
    function to load a bitmap file. You should name it "bmpload.h". The code to write in it ....
  5. Programming In Glut (lesson 4)
    Making 3D objects (7)
    Hello, in this tutorial we will be creating a 3D pyramid. We are building this tutorial from Lesson
    3, but I took out the 2D objects and placed a 3D pyramid in there instead. The 3rd axis for drawing
    can be a litle confusing, but after you get the hand of it you'll do fine. Now when you are
    setting a 3D vertex just remember that the camera is on the positive end of the z axis. So things
    that have a more positive z axis value are closer than verteces with a more negative value. Well
    let's get started We always start by including the glut library CODE #i....
  6. Programming In Glut (lesson 3)
    How to animate objects in GLUT (1)
    In this tutorial I am going to talk about how to get animation in your program. I will be working
    directly off of Lesson 2 and will now take out the notes left behind from Lesson 1, but I will leave
    the notes from Lesson 2. CODE #include //include our glut library First we are going to
    initialize a variable called "time" which will record how much time has passed so we can use it to
    determine how to animate the objects. Then we have our init function that initializes some stuff in
    GLUT CODE float time = 0;//(NEW) variable to record the how much time has....
  7. Programming In Glut (lesson 2)
    Learn how to draw 2D polygons in this tutorial (10)
    This is the second lesson in my series of tutorials on how to use GLUT to create graphics. In this
    tutorial I am going to be teaching you how to create different types of polygons. I am going to be
    adding on to last tutorial's code and will leave the notes in to help you remember what all the
    function are. I will also be noting the new functions that we will be using and how to use them.
    CODE #include //Include the GLUT functions This time we are going to not only set the
    background color, but set the area that we are viewing as well. gluOrtho2D(); sets....
  8. Programming In Glut (lesson 1)
    The first of a series of tutorials on how to use the OpenGL Utility To (4)
    Hello, I'm starting a series on how to program in OpenGL using the OpenGL Utility Toolkit,
    a.k.a. GLUT. I chose GLUT because it is quick and easy to write, and very easy to learn. In this
    tutorial I am going to teach you how to create a basic window which we will build off of in later
    tutorials. Throughout the tutorial I will leave notes to let you know what each command does, and
    how you can modify it to fit your needs. Everything in the code section can be copied and pasted
    into your compiler and it should compile proporly, if it does not, please let me know, a....
  9. Java Applets
    how to make an applet in Java (6)
    The purpose of this tutorial is to explain how to create a Java applet. A Java applet is simply a
    Java program that runs on a webpage. This tutorial assumes that you have a basic understanding of
    Java. If you don't, I would suggest reading a tutorial on Java first. In this tutorial I
    will be using Java 1.5 (or 5.0). If you don't have it you can download it from Sun . The
    classes and methods used in this tutorial may work for other versions of Java, but I don't know
    for sure. During this tutorial I would suggest opening up Java's online documen....

    1. Looking for programming, coffee, begining, programming, java

See Also,

*SIMILAR VIDEOS*
Searching Video's for programming, coffee, begining, programming, java
advertisement



Programming With Coffee - Begining Programming with Java

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com