LinuxQuestions.org
Register a domain and help support LQ
Go Back   LinuxQuestions.org > Linux Answers > Programming
User Name
Password

Notices

By darin3200 at 2003-07-31 22:53
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
Java has built-in support for multi-threaded programming.
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
[i]
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 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
Java is a trademark of Sun Microsystems, just to let you know for legal stuff.

by Steve Cronje on Mon, 2003-08-04 14:41
I have just skimmed the article, and it looks great. I will go through it in more detail later.

As someone who has been starting with Java only recently, these suggestions may come in handy to other beginners such as I:

1. By all means get a sophisticated IDE such as Netbeans or Eclipse, play around with it, and build a few apps, THEN PUT IT AWAY. It only gets in the way of learning the basics.

2. Download DrJava, which is a very simple, yet very supportive learning environment, and much easier to be productive in than using 'just' a text editor. It is open source, free, and is written in Java.

3. Download the full documentation from Sun. The API is here

4. Download, and work through Thinking in Java which is a free download, and will teach you tons.

Just my 2p

HTH
Steve

by then on Tue, 2003-08-05 03:02
Hi

Well written article , bad formatting though. Had a tough time reading.

A couple of spaces and some para-breaks would be welcome.

regards
theN

by darin3200 on Tue, 2003-08-05 20:01
Yeh, I probably should have put some more formatting in.

by glj on Wed, 2003-09-03 10:37
It might be worthwhile to include a link to Blackdowns' site to download Java Linux stuff from. The site has links to loads of useful sounding programs too

glj

by Neodymium on Wed, 2004-03-10 17:33
A nice introduction, I'll be doing some Java development at college next year, and it's always nice to be ahead of the game.

by AskMe on Sat, 2004-04-24 05:37
I can say, it is good for beginers, but it lacks important fact, like what the command one should issue to compile these codes on Linux, and how one can see the output? It would be better if you include such topics.

by darin3200 on Sat, 2004-04-24 11:53
Yeh, i guess I took it for granted that I knew the commands but 'javac' for compile and 'java' for running

by AskMe on Mon, 2004-04-26 06:08
Yah, most know how to compile java source file with javac filename.java and run the compiled class file with java filename, but I was looking for different thing. I have installed Red Hat Linux 9, and with that there is free GNU, compiler and class file interpretor. After hard try, I found out how to use gcj and gij. So here is the command how to compile java on RedHat9.

To compile source file(filename.java)
gcj -C filename.java

To run calss file (filename.class)
gij filename

I hope this will help people like me, but I am still looking for how to run Applet on RedHat 9, I don't want to use Mozilla, because there is no plug-in installed and to install all these another headache for me as I know very less about linux.

by lmellen on Sat, 2004-06-05 14:40
I've worked all the example programs up to class moon.The class moon program won't compile. I get:

ex6.java:16: cannot resolve symbol
symbol : method readline()
location: class java.io.BufferedReader

Then there is a ^ under the first new in the following line:

String strA = new BufferedReader(new InputStreamReader(System.in)).readLine();

Just wondering why it won't compile. No big deal, but a reply would be interesting.-- Thanks- Larry (I haven't been able to solve this problem)

by darin3200 on Tue, 2004-06-08 16:39
Have you typed this up the code yourself or have you tried copying and pasting into the .java file? Some times there can be typos that have an effect of the compilation of the programs. I'll check that out though.


  



All times are GMT -5. The time now is 09:30 PM.

Main Menu
Advertisement

Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration