Welcome Guest [Log In] [Register]
Welcome to Chibiwolf. We hope you enjoy your visit.


You're currently viewing our forum as a guest. This means you are limited to certain areas of the board and there are some features you can't use. If you join our community, you'll be able to access member-only sections, and use many member-only features such as customizing your profile, sending personal messages, and voting in polls. Registration is simple, fast, and completely free.


Join our community!


If you're already a member please log in to your account to access all of our features:

Username:   Password:
Add Reply
java first application
Topic Started: Apr 15 2008, 05:52 PM (41 Views)
MusicUploader
Member Avatar
The Ownager
[ *  *  *  * ]
Our first application will be extremely simple - the obligatory "Hello World". The following is the Hello World Application as written in Java. Type it into a text file or copy it out of your web browser, and save it as a file named HelloWorld.java. This program demonstrates the text output function of the Java programming language by displaying the message "Hello world!". Java compilers expect the filename to match the class name.

A java program is defined by a public class that takes the form:
Code:
 
public class program-name {
           
               optional variable declarations and methods
               
               public static void main(String[] args) {
                  statements
               }
               
               optional variable declarations and methods
         
           }
Source Code
In your favorite editor, create a file called HelloWorld.java with the following contents:
Code:
 
/** Comment
        * Displays "Hello World!" to the standard output.
        */
                 class HelloWorld {

         public static void main (String args[]) {

           System.out.println("Hello World!");           //Displays the enclosed String on the Screen Console

         }
         
       }
To compile Java code, we need to use the 'javac' tool. From a command line, the command to compile this program is:

javac HelloWorld.java

For this to work, the javac must be in your shell's path or you must explicitly specify the path to the program (such as c:\j2se\bin\javac HelloWork.java). If the compilation is successful, javac will quietly end and return you to a command prompt. If you look in the directory, there will now be a HelloWorld.class file. This file is the compiled version of your program. Once your program is in this form, its ready to run. Check to see that a class file has been created. If not, or you receive an error message, check for typographical errors in your source code. You're ready to run your first Java application. To run the program, you just run it with the java command:

java HelloWorld

Sample Run

Hello world!
The source file above should be saved as myfirstjavaprog.java, using any standard text editor capable of saving as ASCII (eg - Notepad, Vi). As an alternative, you can download the source for this tutorial.

HelloWorld.java
To compile Java code, we need to use the 'javac' tool. From a command line, the command to compile this program is:

javac HelloWorld.java

For this to work, the javac must be in your shell's path or you must explicitly specify the path to the program (such as c:\j2se\bin\javac HelloWork.java). If the compilation is successful, javac will quietly end and return you to a command prompt. If you look in the directory, there will now be a HelloWorld.class file. This file is the compiled version of your program. Once your program is in this form, its ready to run. Check to see that a class file has been created. If not, or you receive an error message, check for typographical errors in your source code. You're ready to run your first Java application. To run the program, you just run it with the java command:

java HelloWorld

Sample Run

Hello world!
The source file above should be saved as myfirstjavaprog.java, using any standard text editor capable of saving as ASCII (eg - Notepad, Vi). As an alternative, you can download the source for this tutorial.

HelloWorld.java

The Java programming language has includes five simple arithmetic operators like are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). The following table summarizes the binary arithmetic operators in the Java programming language.

The relation operators in Java are: ==, !=, <, >, <=, and >=. The meanings of these operators are:
Use Returns true if op1 + op2 op1 added to op2 op1 - op2 op2 subtracted from op1 op1 * op2 op1 multiplied with op2 op1 / op2 op1 divided by op2 op1 % op2 Computes the remainder of dividing op1 by op2
The following java program, ArithmeticProg , defines two
integers and two double-precision floating-point numbers and uses the
five arithmetic operators to perform different arithmetic operations.
This program also uses + to concatenate strings. The arithmetic

Code:
 
public class ArithmeticProg {
   public static void main(String[] args) {

   //a few numbers
   int i = 10;
   int j = 20;
   double x = 10.5;
   double y = 20.5;

   //adding numbers
   System.out.println("Adding");
   System.out.println(" i + j = " + (i + j));
   System.out.println(" x + y = " + (x + y));

   //subtracting numbers
   System.out.println("Subtracting");
   System.out.println(" i - j = " + (i - j));
   System.out.println(" x - y = " + (x - y));

   //multiplying numbers
   System.out.println("Multiplying");
   System.out.println(" i * j = " + (i * j));
   System.out.println(" x * y = " + (x * y));

   //dividing numbers
   System.out.println("Dividing");
   System.out.println(" i / j = " + (i / j));
   System.out.println(" x / y = " + (x / y));

   //computing the remainder resulting
   //from dividing numbers
   System.out.println("Modulus");
   System.out.println(" i % j = " + (i % j));
   System.out.println(" x % y = " + (x % y));

   }
Java If-Else Statement
The if-else class of statements should have the following form:

Code:
 
                 if (condition) {
       statements;
       }
       
       if (condition) {
       statements;
       } else {
       statements;
       }
       
       if (condition) {
       statements;
       } else if (condition) {
       statements;
       } else {
       statements;
       }
All programming languages have some form of an if statement that allows you to test conditions. All arrays have lengths and we can access that length by referencing the variable arrayname.length. We test the length of the args array as follows:
Source Code
Code:
 
// This is the Hello program in Java
       class Hello {
       
           public static void main (String args[]) {
           
             /* Now let's say hello */
             System.out.print("Hello ");
             if (args.length > 0) {
               System.out.println(args[0]);
             }
         }

                }


Compile and run this program and toss different inputs at it. You should note that there's no longer an ArrayIndexOutOfBoundsException if you don't give it any command line arguments at all.
What we did was wrap the System.out.println(args[0]) statement in a conditional test, if (args.length > 0) { }. The code inside the braces, System.out.println(args[0]), now gets executed if and only if the length of the args array is greater than zero. In Java numerical greater than and lesser than tests are done with the > and < characters respectively. We can test for a number being less than or equal to and greater than or equal to with <= and >= respectively.
Testing for equality is a little trickier. We would expect to test if two numbers were equal by using the = sign. However we've already used the = sign to set the value of a variable. Therefore we need a new symbol to test for equality. Java borrows C's double equals sign, ==, to test for equality. Lets look at an example when there are more then 1 statement in a branch and how braces are used indefinitely.



Source Code
Code:
 
import java.io.*;
class NumberTest
{
   public static void main (String[] args) throws IOException
   {
       BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );

       String inS;
       int num;

       System.out.println("Enter an integer number");
       inS = stdin.readLine();
       num = Integer.parseInt( inS ); // convert inS to int using wrapper classes

       if ( num < 0 )  // true-branch
       {
         System.out.println("The number " + num + " is negative");
          System.out.println("negative number are less than zero");
       }
       else   // false-branch
       {
          System.out.println("The number " + num + " is positive");
          System.out.print ("positive numbers are greater ");
          System.out.println("or equal to zero ");
       }
       System.out.println("End of program"); // always executed
   }
}
All conditional statements in Java require boolean values, and that's
what the ==, <, >, <=, and >= operators all return. A
boolean is a value that is either true or false. Unlike in C booleans
are not the same as ints, and ints and booleans cannot be cast back and
forth. If you need to set a boolean variable in a Java program, you have
to use the constants true and false. false
is not 0 and true is not non-zero as in C. Boolean values
are no more integers than are strings.
Else
Lets look at some examples of if-else:

Code:
 
                 //Example 1
       if(a == b) {
       c++;
       }
       if(a != b) {
       c--;
       }
       
       //Example 2
       if(a == b) {
       c++;
       }
       else {
       c--;
       }
We could add an else statement like so: Source Code


// This is the Hello program in Java
class Hello {

Code:
 
                     public static void main (String args[]) {
           
             /* Now let's say hello */
             System.out.print("Hello ");
             if (args.length > 0) {
               System.out.println(args[0]);
             }
             else {
                       System.out.println("whoever you are");
             }
         }

                }


Source Code
Code:
 
public class divisor
       {
       public static void main(String[] args)
                int a = 10;
                int b = 2;
                if ( a % b == 0 )
                {
                              System.out.println(a + " is divisible by "+ b);
                }
                else
                {
                              System.out.println(a + " is not divisible by " + b);
                }
       }
Now that Hello at least doesn't crash with an ArrayIndexOutOfBoundsException we're still not done. java Hello works and Java Hello Rusty works, but if we type java Hello Elliotte Rusty Harold, Java still only prints Hello Elliotte. Let's fix that. We're not just limited to two cases though. We can combine an else and an if to make an else if and use this to test a whole range of mutually exclusive possibilities.




Lets look at some examples of if-else-if:


Code:
 

       //Example 1
       if(color == BLUE)) {
       System.out.println("The color is blue.");
       }
       else if(color == GREEN) {
       System.out.println("The color is green.");
       }
       
       //Example 2
       if(employee.isManager()) {
       System.out.println("Is a Manager");
       }
       else if(employee.isVicePresident()) {
       System.out.println("Is a Vice-President");
       }
       else {
       System.out.println("Is a Worker");
       }


I Loved Her So Much I Saw A Chance And Missed It Now Im Broken

┏┫  | |   ┣┓  ┏┓ 
┗┫━━ ┃ ━━┣┛  ┣┫ 
 ┃ ━━━━━ ┃ ┏┳┫┣┳┓ 
 ┗━━┳━┳━━┛ ┃    ┃ 
━━━━┃ ┃    ┗━┳┳━┛
━━━━┃ ┗━━━━━━┛┃
Posted Image
Offline Profile Quote Post Goto Top
 
DarkCannon
Member Avatar
Willy Wolf
[ *  *  *  *  *  * ]
HAHA! I read this in a book somewere. If you copied it tell me what book cause its driving me crazy.
[size=14]I AM A BUNNY! FEAR ME! I SHALL NIBBLE ON YOUR CARROTS! RAWR![/size]
Offline Profile Quote Post Goto Top
 
Chibi
Member Avatar
Shmell mah finger
Admins
I dont care :P

:Sticky:
Posted Image

"I'd kill the Jews." -glare- "I'd not kill the Jews, no. I'd toss in a penny and watch them fight to the death. -snickering- I did the same with two Catholic priests but I tossed in a small boy!! And the winner, had to fight Michael Jackson!"%mh%-100%mh%
Offline Profile Quote Post Goto Top
 
MusicUploader
Member Avatar
The Ownager
[ *  *  *  * ]
lol i dont remember i used to have the book threw it away i just remembered this from it :)
I Loved Her So Much I Saw A Chance And Missed It Now Im Broken

┏┫  | |   ┣┓  ┏┓ 
┗┫━━ ┃ ━━┣┛  ┣┫ 
 ┃ ━━━━━ ┃ ┏┳┫┣┳┓ 
 ┗━━┳━┳━━┛ ┃    ┃ 
━━━━┃ ┃    ┗━┳┳━┛
━━━━┃ ┗━━━━━━┛┃
Posted Image
Offline Profile Quote Post Goto Top
 
Chibi
Member Avatar
Shmell mah finger
Admins
Still a good job though. This will help out other members like Sal. He is pathetic at this stuff.
Posted Image

"I'd kill the Jews." -glare- "I'd not kill the Jews, no. I'd toss in a penny and watch them fight to the death. -snickering- I did the same with two Catholic priests but I tossed in a small boy!! And the winner, had to fight Michael Jackson!"%mh%-100%mh%
Offline Profile Quote Post Goto Top
 
« Previous Topic · Computer Talk · Next Topic »
Add Reply