Wednesday, May 17, 2006

Beginning with Java on Linux

It seems that you can't go anywhere on the web without running into some form of Java, this is why I am now going to try to explain not only what Java is, but give some examples of programs that you can make, modify and learn from.
What is Java?
Java was originally developed by Sun Microsystems in an attempt to create an architecturally neutral programming language that would not have to be complied for various CPU architectures. Oak (as it was originally called, although the name was changed in 1995) was developed in 1991 for such things as home appliances which would not all run on the same type of processors. Just then the web was taking off and it was obvious that an programming language that could be used for many different operating systems and CPU architectures without compling many times would be of great importance. The final solution was to use bytecode. Unlike C++, Java code is not executable, it is code that is run by a Java Virtual Machine (JVM), so once a JVM is introduced for a platform all the Java programs can be run on it. There are two types of Java programs, the applications and the applets. The applications are what are written on a computer and run on a computer without the Internet connected in anyway. An applet is a program made for use on the internet and is the programs that runs in your browser. Sun also gave Java some buzzwords.
Simple
You might get some arguments from beginners on this, but Java remains a fairly simple language.
Secure
If you ever try to save from a notepad program (or any program) in Java you will get something saying
Quote:
This application has requested read/write access to a file on the local filesystem. Allowing this action will only give the application access to the file(s) selected in the following file dialog box. Do you want to allow this action?
The Java code runs within the JVM and prompts you if the bytecode wants to read or write.
Portable
Since it is architecturally neutral it can run on PCs, Macs, PDAs, Cellphones, and about anything else if there is a JVM for it.
Object-Oriented
While some languages are based around commands, Object-Oriented programming focuses on that data. For a more complete definition I highly recommend going to Google Glossary to learn more.
Robust
Powerful. This is in part due to the fact that the Java complier will check the code and will not complie it if has errors.
Multithreaded[b/]
Java has built-in support for multi-threaded programming.
[b]Architecture-neutral
Java is not made for a specific architecture or operating system.
Interpreted
Thanks to bytecode Java can be used on many different platforms.
High Performace
Java isn't going to be used for 1st person shooters but it does run fast.
Distributed
It can be used on many platforms
Dynamic
Can evolve to changing needs.

How Java is like C/C++
A Java programmer would be able to learn C/C++ quickly and a C/C++ programmer would be able to learn Java quickly because they are similar. When Java was made it was not to be a programming language that was better then C/C++ but was made to meet the goals of the interenet age. Java also has differences with C/C++, for example, someone could not write C/C++ code and complie it as Java for Internet use, nor could someone take Java code and complie it into C/C++.
Getting started writing Java
First you must go and get Java. You can download the JRE, which is the Java Runtime Environment, this is good for using Java but not what we need to compile Java applications. You need to download the SDK, which is the Software Development Kit. Once you have installed this free download you will have two important tools. The first is the javac command which is for compiling the program, and there is the java command for running your program. Once the SDK is installed you try typing javac, if you get an unrecognized error you should put the line
PATH=$PATH:/usr/java/j2sdk1.4.2/bin (or replace /usr/java/j2sdk1.4.2/bin[/i] in whatever is the place to javac (this can be found with locate javac)in your /etc/profile file. This way the commands are accessible from anywhere. For writing the programs, most text editors will work (not word processors though, they format the text) but I prefer Kwrite because after you save it as a java file it colors all the text and makes blocks of code collaspable and expandable. First we are going to do an analysis of a simple program.

/*
This is a simple, simple app.
They will get more fun in time
:)
*/
class First {
public static void main(String args[]) {
System.out.println("Yea! I wrote JAVA");
}
}

Starting at the top you will see the /* and */ markings. This is for a multi-line comment, anything inside of here will be ignored by the Java compiler. You can also add singal line comments with the // markings with everything after the // as a comment.
class is the part of the program that everything is inside of.
First is the title of the program, you have to save it as whatever you have after class, and this case-sensitive.
public is specifying main(String args[]) as being accessable to code outside of its class.
static allows main(String args[]) to be used before any objects have been created.
void Saying that main(String args[]) itself doesn't give output
main(String args[]) { is a method, this is where the code starts executing, you don't need the Sting args for this program but you will need it later so get used to typing it. :)
System.out.println is simply telling the system to print and the ln is telling it to make a new line afterwards. You could also just put print instead of println. Everything in parentheses is where you can type messages.
} The first one is closing the public static void main() { line and the second is closing the class First {.
Once you have this done this, save your file, but make sure to save it as First.java. Next, get a command prompt and go into the folder where you saved your Java file and type
javac First.java
Nothing fancy should happen. If something does, just copy and paste the program off of this document and it should compile fine. Nearly all of my errors with Java are typos that the compiler will let me know about. After this, you should have a file called First.class. Make sure you are in the same directory as First.class and type
java First
and you should see
Yea! I wrote JAVA.
You do not need to include .class when you are running the program.

Next, we get started with variables. Variables can be any sort of things that you assign a value to.

class var {
public static void main(String args[]) {
int v;
v = 5;
System.out.println("v is " + v);
}
}

The output should be v is 5
Since I have already explained most of the things in the previous program I will explain what the new things do.
int v; This is declaring that there will be an integer variable. You must declare a variable before you use it. This variable is call v. The names can be longer then one character and are case sensitive.
v = 5; v is now being assigned the value 5.
System.out.println("v is " + v); Like before, the System.out.println command is being used, everything inside of quotes is what you type. To add the value of v just a the + v outside of the quotes.
Once you have complied the program and ran it you should get.
v is 5
You can also do math with Java programs, like in the next example.

class math {
public static void main(String args[]) {
int a;
int b;
int c;
a = 5;
b = 9;
c = a * b;
System.out.println( a + " times " + b + " is " + c);
}
}

The output will be 5 times 9 is 45
Along with *, you can also use the +, -, and / signs for math. You can also do things like b = b * a where what the variable equals includes itself. The next program demonstrates a loop.

class loop {
public static void main(String args[]) {
double gallons, cups;
for(gallons = 1; gallons <=10; gallons++) {
cups = gallons * 16;
System.out.println(gallons + " gallons is " + cups + " cups.");
}
}
}

The output will be

1.0 gallons is 16.0 cups.
2.0 gallons is 32.0 cups.
3.0 gallons is 48.0 cups.
4.0 gallons is 64.0 cups.
5.0 gallons is 80.0 cups.
6.0 gallons is 96.0 cups.
7.0 gallons is 112.0 cups.
8.0 gallons is 128.0 cups.
9.0 gallons is 144.0 cups.
10.0 gallons is 160.0 cups.

The first thing different about this program is double instead of int. Int declares an integer, these work for a lot of things but loose precision if you were to divide 9 by 2, or dealing with anything that has a decimal. For things with decimals you can use float or double. There are also different types of integers other then int. Int is 32 bits, so it covers from 2,147,483,647 to -2,147,483,648. As its name suggests, long is a very long integer, 64 bit, it can handle numbers slightly over 9,200,000,000,000,000,000 and slightly under the negative. For the smaller numbers you might want to look into short (16 bit, 32,867 through -32,768) and byte(8 bit, 127 through -128). And for characters, you use char.
Getting back on track, the next thing you will notice it the two variables being declared are separated by a comma. This saves time, I can write
double a, b, c, d;
instead of writing out
double a;
double b;
double c;
double d;
The line with for is the loop itself. The basic form of for is for(starting; restrictions; count by) statement;
The gallons = 1; is saying we want the loop starting at 1. You could start it at 57 or -23 if you wanted. gallons <= 10; is saying count everything less then or equal to 10. Here are some important things that will come in handy many times
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
And gallons++ is the same as writing out count = count+1 If you want to count by 2s use count = count+2 or 3s use count = count+3 and so on. The { starts a new block of code, inside we assign cups the value and what to display when the loop is complete.
This next program will use the if statement.

class ifif {
public static void main(String args[]) {
double a, b;
a = 5
b = 4
if(a == b) System.out.println("Since 4 will never equal 5 this won't be displayed, if it does, buy a new CPU");
if(a != b) System.out.println("Since 4 isn't equal to 5 this will be displayed");
if(a < b) System.out.println("5 isn't less then 4, this will not be seen");
if(a > b) System.out.println("I think you get it by now");
}
}

If statements are very useful in all types of situations. The if statement can also be used as a block of code, for example

if(5 == 5) {
double e;
e = 5;
System.out.println("e is " + e);
}
This may not seem like a very useful tool, but in time it will become very important. Say for example, you are writing a temperature conversion program. You want to prompt the user "Press A to convert Fahrenheit to Celsius or B to convert Celsius to Fahrenheit" You would have something like
if(input == A) {
Here is the program to convert Fahrenheit to Celsius
}
if(input == B {
Here is the program to convert Celsius to Fahrenheit
}
This way only the code needed is executed. Of course, you won't actually use [i]input, that is just easy to understand for now.
Here is a program that uses user input to find weight on the moon.

import java.io.*;
class moon {
public static void main(String args[])
throws java.io.IOException {
double e;
double m;
System.out.println("Please enter your weight to get the moon equivalent.");
String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();
e = Double.parseDouble(strA);
m = e * .17;
System.out.println("Your weight on the moon would be " + m + " pounds");
}
}

This one is more complex. import java.io.*; is bringing in things needed for input. The throws java.io.IOException is for error handling. String strA = new BufferedReader(new InputStreamReader(System.in)).readLine(); is going to get the input and the next line is going to assign e the input. From there it is easy. So knowing most of this you can create simple, but useful applications like this.

import java.io.*;
public class triangle {
public static void main(String args[]) throws java.io.IOException {
double a;
double b;
double c;
System.out.println("A is? "); //asking for a
String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();
a = Double.parseDouble(strA);
System.out.println("B is? "); //asking for b
String strB = new BufferedReader(new InputStreamReader(System.in)).readLine();
b = Double.parseDouble(strB);
System.out.println("C is? "); //asking for c
String strC = new BufferedReader(new InputStreamReader(System.in)).readLine();
c = Double.parseDouble(strC);
if(c == 0) { //the block that finds out what c is
b = b * b; //getting b squared
a = a * a; //getting a squared
c = a + b; //a squared + b squared equals c squared
double x=Math.sqrt(c); //finding the square root
System.out.println("C is " + x); //telling what c is
}
if(b == 0) {
c = c * c;
a = a * a;
b = a - c;
if(b <= 0) b = b * -1; //ensuring that the program will not to try to find the square root of a negative number
double y=Math.sqrt(b);
System.out.println("B is " + y);
}
if(a == 0) {
b = b * b;
c = c * c;
a = c - b;
if(a <= 0) a = a * -1;
double z=Math.sqrt(a);
System.out.println("A is " + z);
}
}
}

You get prompted for A,B and C side of a right triangle, if you don't know one side, enter in 0 for that one. The only new stuff is double x=Math.sqrt(c); this is just declaring x and at the same time saying it is the square root of c. Thanks to
moeminhtun on help with the input. This is only scratching the surface of what can be done with Java so here are some more sources that have great information.
Sun has some a lot of documentation on there website.
Java 2: A Beginner's Guide is a great book. This is not a for Dummies book though. It has a steeper, yet easy to follow learning curve. On the right hand side of this page you will also see a link called "Free downloadable code", download this code and look though it, you can learn a lot.
A complete explanation of the Java buzzwords
Some more information from Sun
Beginning Java 2 SDK 1.4 Edition
Learn to program with Java

1 comment:

tiki said...

how can u directly jump to JAva b4 not going for C or C++

and also configuring RHL inPC is also difficult people say, can u focus on that