Quick Search for:  in language:    
programs,written,JavaTM,language,Java,built,f
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
Java/ Javascript Stats

 Code: 220,465. lines
 Jobs: 89. postings

 How to support the site

 
Sponsored by:

 
You are in:
 

Does your code think in ink?
Login





Latest Code Ticker for Java/ Javascript.
Gobang
By Geniusbob Xu Qiang on 11/27


Click here to see a screenshot of this code!Salary
By Vikram Ivatury on 11/25

(Screen Shot)

Click here to see a screenshot of this code!A (part10) Powerful Swing Code to Maintain CD Database
By James Smith K on 11/25

(Screen Shot)

String Calculator
By MadokaCoder on 11/24


Chobi Dekha
By ShuvoRim on 11/23


Click here to see a screenshot of this code!A basic Client Server application II
By Ronald Holland on 11/23

(Screen Shot)

Bookmark image
By darren kurn on 11/22


myFT
By Owolabi Oyapero on 11/22


Click here to see a screenshot of this code!Simple Socket example
By Steven McElrea on 11/20

(Screen Shot)

Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Building Applications

Print
Email
 

Submitted on: 5/17/2000 6:55:04 PM
By: Monica Pawlan (Copyright Sun Microsystems Inc)  
Level: Beginner
User Rating: By 10 Users
Compatibility:Java (JDK 1.1)

Users have accessed this article 15494 times.
 
(About the author)
 
     All programs written in the JavaTM language (Java programs) are built from classes. Because all classes have the same structure and share common elements, all Java programs are very similar. This lesson describes the structure and elements of a simple application created from one class. The next lesson (Buidling Applets) covers the same material for applets.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
1) You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.

Building Applications

by Monica Pawlan
Reprinted with permission from the Java Developer Connection(SM)
Copyright Sun Microsystems Inc.


All programs written in the JavaTM language (Java programs) are built from classes. Because all classes have the same structure and share common elements, all Java programs are very similar.

This lesson describes the structure and elements of a simple application created from one class. The next lesson covers the same material for applets.


Application Structure and Elements

An application is created from classes. A class is similar to a RECORD in the Pascal language or a struct in the C language in that it stores related data in fields, where the fields can be different types. So you could, for example, store a text string in one field, an integer in another field, and a floating point in a third field. The difference between a class and a RECORD or struct is that a class also defines the methods to work on the data.

For example, a very simple class might store a string of text and define one method to set the string and another method to get the string and print it to the console. Methods that work on the data are called accessor methods.

Every application needs one class with a main method. This class is the entry point for the program, and is the class name passed to the java interpreter command to run the application.

The code in the main method executes first when the program starts, and is the control point from which the controller class accessor methods are called to work on the data.

Here, again, is the example program from Lesson 1. It has no fields or accessor methods, but because it is the only class in the program, it has a main method.

class ExampleProgram {
        public static void main(String[] args){
        System.out.println("I'm a Simple Program");
    }

}

The public static void keywords mean the Java1 virtual machine (JVM) interpreter can call the program's main method to start the program (public) without creating an instance of the class (static), and the program does not return data to the Java VM interpreter (void) when it ends.

An instance of a class is an executable copy of the class While the class describes the data and behavior, you need a class instance to acquire and work on data. The diagram at the left shows three instances of the ExampleProgram class by the names: FirstInstance, SecondInstance and ThirdInstance.

The main method is static to give the Java VM interpreter a way to start the class without creating an instance of the control class first. Instances of the control class are created in the main method after the program starts.

The main method for the simple example does not create an instance of the ExampleProgram class because none is needed. The ExampleProgram class has no other methods or fields, so no class instance is needed to access them from the main method. The Java platform lets you execute a class without creating an instance of that class as long as its static methods do not call any non-static methods or fields.

The ExampleProgram class just calls println, which is a static method in the System class. The java.lang.System class, among other things, provides functionality to send text to the terminal window where the program was started. It has all static fields and methods.

The static fields and methods of a class can be called by another program without creating an instance of the class. So, just as the Java VM interpreter command could call the static main method in the ExampleProgram class without creating an instance of the ExampleProgram class, the ExampleProgram class can call the static println method in the System class, without creating an instance of the System class.

However, a program must create an instance of a class to access its non-static fields and methods. Accessing static and non-static fields and methods is discussed further with several examples in the next section.

Fields and Methods

The LessonTwoA.java program alters the simple example to store the text string in a static field called text. The text field is static so its data can be accessed directly without creating an instance of the LessonTwoA class.
class LessonTwoA {
    static String text = "I'm a Simple Program";
        public static void main(String[] args){
        System.out.println(text);
    }

}
The LessonTwoB.java and LessonTwoC.java programs add a getText method to the program to retrieve and print the text.

The LessonTwoB.java program accesses the non-static text field with the non-static getText method. Non-static methods and fields are called instance methods and fields. This approach requires that an instance of the LessonTwoB class be created in the main method. To keep things interesting, this example includes a static text field and a non-static instance method (getStaticText) to retrieve it.


Note: The field and method return values are all type String.
class LessonTwoB {
    String text = "I'm a Simple Program";
    static String text2 = "I'm static text";
        String getText(){
        return text;
    }

String getStaticText(){ return text2; }
public static void main(String[] args){ LessonTwoB progInstance = new LessonTwoB(); String retrievedText = progInstance.getText(); String retrievedStaticText = progInstance.getStaticText(); System.out.println(retrievedText); System.out.println(retrievedStaticText); }
}
The LessonTwoC.java program accesses the static text field with the static getText method. Static methods and fields are called class methods and fields. This approach allows the program to call the static getText method directly without creating an instance of the LessonTwoC class.
class LessonTwoC {
    static String text = "I'm a Simple Program";
    //Accessor method

        static String getText(){
        return text;
    }

public static void main(String[] args){ String retrievedText = getText(); System.out.println(retrievedText); }
}
So, class methods can operate only on class fields, and instance methods can operate on class and instance fields.

You might wonder what the difference means. In short, there is only one copy of the data stored or set in a class field but each instance has its own copy of the data stored or set in an instance field.

The figure above shows three class instances with one static field and one instance field. At runtime, there is one copy of the value for static Field A and each instance points to the one copy. When setFieldA(50) is called on the first instance, the value of the one copy changes from 36 to 50 and all three instances point to the new value. But, when setFieldB(25) is called on the first instance, the value for Field B changes from 0 to 25 for the first instance only because each instance has its own copy of Field B.

See Understanding Instance and Class Members lesson in The Java tutorial for a thorough discussion of this topic.

Constructors

Classes have a special method called a constructor that is called when a class instance is created. The class constructor always has the same name as the class and no return type. The LessonTwoD program converts the LessonTwoB program to use a constructor to initialize the text string.

Note: If you do not write your own constructor, the compiler adds an empty constructor, which calls the no-arguments constructor of its parent class. The empty constructor is called the default constructor. The default constructor initializes all non-initialized fields and variables to zero.
class LessonTwoD {
    String text;
    //Constructor

        LessonTwoD(){
        text = "I'm a Simple Program";
    }

//Accessor method String getText(){ return text; }
public static void main(String[] args){ LessonTwoD progInst = new LessonTwoD(); String retrievedText = progInst.getText(); System.out.println(retrievedText); }
}

To Summarize

A simple program that prints a short text string to the console would probably do everything in the main method and do away with the constructor, text field, and getText method. But, this lesson used a very simple program to show you the structure and elements in a basic Java program.

More Information

See Understanding Instance and Class Members lesson in The Java tutorial for a thorough discussion of this topic.

_______
1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.


<--BEGIN READER SURVEY-->

Reprinted with permission from the Java Developer Connection(SM)
Copyright Sun Microsystems Inc.

[TOP]

<-- ================ --> <-- End Main Content --> <-- ================ -->
<-- Copyright Insert -->

 
 

 

<-- Copyright Insert -->


Other 7 submission(s) by this author

 

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this article(in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments
12/8/2000 1:59:32 PM:RAKESH BANZAL
PLEASE TELL ME A SINGLE BEST BOOK FOR JCD.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
2/27/2001 3:43:21 PM:Trenton Miller
Any Suggestions on any books for Java Applications ? BTW nicely written text. Email me: Magi-nation@thefragile.com if you know any good books
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
3/11/2003 9:10:04 PM:
Excellent tutorial! I was wrestling with a textbook on Java and just not "getting it"; this let me look at things from a new point of view and now I understand what I missing before.
Keep the Planet clean! If this comment was disrespectful, please report it:
Reason:

 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this article has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular article, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | Java/ Javascript Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.