Sams Teach Yourself C in 21 Days

(singke) #1
applicationsare programs that run on their own, just like the C programs you have seen
throughout this book. Java can be used in a number of ways. Java applets use to receive a
lot of attention because of all the hype surrounding the Web. Java can also be used to cre-
ate components, server-side Web applications, and enterprise-level objects. Most impor-
tantly, Java is useful for creating stand-alone applications. In this brief introduction to
Java, you will concentrate on using Java for stand-alone applications, as that is more
directly comparable to the uses of C and C++ you have seen elsewhere in this book.

Java Program Essentials ......................................................................................


At the most simple level, a Java program consists of two parts, one contained within the
other. As with just about everything else in Java, a program is a class and is defined as
follows:
public class ProgramName
{
}
All the code that makes up the program is placed within the braces, and the entire source
code file is saved on disk with an extension of java. A program called ProgramName
would be stored as ProgramName.java. The second essential part of a Java program is
themainfunction. When you execute a Java program, execution starts in mainjust as it
does in C and C++. Here’s what mainlooks like:
public class ProgramName {
public static void main (String args[])
{
}
}
You’ll note that maintakes an argument called args[]. This is the way that command
line arguments are passed to a Java program. Unlike C, you don’t have an integer argc
variable stating how many values were provided. Instead, you use args.length.

Working with Imports ..................................................................................

Almost every Java program, except the simplest, must use the importstatement to have
access to classes that the program uses. You must use importwith classes that are part of
Java, as well as with classes you have written. importstatements are placed at the start
of a Java source code file, before the class definition. You can import classes individual-
ly, as in this example that imports the class someClassfrom the package my.package:
import my.package.someClass;

704 Bonus Day 4

39 448201x-Bonus4 8/13/02 11:19 AM Page 704

Free download pdf