You are on page 1of 15

Advanced Java Programming I

COMP-228

Introduction to Java
Java is a modern programming language from Sun Microsystems, with elements from C, C++, and other languages, and with libraries highly tuned for the Internet environment. Java is also a complete execution environment that allows programs to be run from a web browser. The designer of Java was James Gosling, and the programmer who implemented the first public version of the compiler was Arthur van Hoff. Kim Polese was the marketing person who dreamed up the name "Java" for its exotic, exciting, adrenaline-pumping connotations. Java is an object-oriented programming language. Compared with C (procedural language used for structured programming), Java does not have: Memory address (pointer) arithmetic Preprocessor The goto statement Automatic type conversion Global functions and variables Type definition aliases (typedefs) Compared with C++, Java does not have: Operator overloading Multiple inheritance Java is really a computing platform, just as the Mac and Windows are platforms. The Java platform consists of the Java application programming interfaces (APIs) and the Java virtual machine (Java VM). Java APIs are libraries of compiled code that you can use in your programs. They let you add ready - made and customizable functionality to save you programming time. Java has become the language of choice for implementing Internet-based applications and software for devices that communicate over a network. There are now billions of Java-enabled mobile phones and handheld devices. Java is the preferred language for meeting many organizations enterprise-wide programming needs. Java Virtual Machine Java source code is compiled to produce object code, known as bytecode. So far, this is just like any other language. The critical difference is that bytecode is not the binary code of any existing computer. It is an architecture-neutral machine code that can quickly be

Java Notes #1

Page 1 of 15

Advanced Java Programming I

COMP-228

interpreted to run on any specific computer. You execute a Java program by running another program called the Java Virtual Machine, or JVM. The JVM is in most cases invoked by running the program called java. The JVM reads the bytecode program and interprets or translates it into the native instruction set. This feature is highly significant! Running bytecode on a JVM is the reason that Java software is "Write Once Run Everywhere". Java produces code that runs on every processor.

Figure 1.1 Java Virtual Machine The following are some of Java programming language features: Simple Architecture neutral Object oriented Portable Distributed High performance Multithreaded Robust Dynamic Secure

Software Portability Software portability is the single most important advantage of Java. The non-Microsoft part of the computer industry is strongly supporting the "100% Pure Java" test suites and certification aimed at keeping code portable. Java brings the industry closer to true software portability than any previous system does. The Java Virtual Machine (a fancy name for the interpreter) needs to be implemented once for each computer system; then all bytecode will run on that system. There are several alternative JVMs available for the PC and the Mac, and they differ in speed, cost, and quality. Bytecode is not just for Java. If you modify a compiler for some other language (such as Ada or Visual Basic) so that it outputs bytecode, you can run it equally happily on the JVM on any computer. Microsofts .NET is another technology that followed Javas path.

Java Notes #1

Page 2 of 15

Advanced Java Programming I

COMP-228

Performance Portability initially comes at the cost of some performance. It's a reasonable bargain. If a binary is not compiled down to a specific machine code, extra work is needed at runtime to finish the job. People are very interested in making Java as fast as possible and several clever approaches are being tried. Some JVMs can even compile the bytecode as they run it, a technique known as Just In Time compilation, or JIT. The first time through, the code is run at interpreted speed; subsequent passes through a loop are executed at native binary speed. A JIT compiler knows the exact details of the execution environment (cache sizes, whether floating point is emulated, amount of main memory, etc.) so it can conceivably generate higher performance code than a C compiler, targeting a more general environment. The current generation of Java tools runs quickly enough that performance is not an issue for all but the most critical programs. Java takes several other steps to ensure portability. It offers the same Application Programmer Interface (API) on all platforms. Java has the same Application Binary Interface (ABI) on all platforms, namely, the Java Virtual Machine. Java uses the Unicode character set, which is a 16-bit superset of ASCII. Unicode can represent the symbols in most of the alphabets in the world, including Russian Cyrillic characters, and Asian ideograms.

Java Libraries The Java language is nice, but much of the real value of Java is in the set of crossplatform APIs that come with the system. Java has possibly the easiest-to-use networking and windowing (GUI) of any language, which has helped its widespread adoption. A GUI application written in Java has the same total portability of other Java programs. It just runs on all computer systems. A network program written in Java is much the same as any other kind of I/O. You create an object of the appropriate type and read or write it. The runtime system does all the painful low-level work of making the connections and sending the bytes over the wire for you. Java programs consist of pieces called classes. Classes include methods that perform tasks and return information when the tasks complete. Java class libraries are rich collections of existing classes. Java libraries are also known as the Java APIs (Application Programming Interfaces). The Java libraries can be divided into two categories:

Java Notes #1

Page 3 of 15

Advanced Java Programming I

COMP-228

Core libraries bundled with the JDK. These are the class libraries that every JDK must support. Optional additions to the JDK. These are the class libraries that are optional. But if the feature is supported, it must be supported with this API. The following is a list of the current Java APIs. J2SE (Core/Desktop) J2EE (Enterprise/Server) JME (Mobile/Wireless) Java Card Java Web Services XML Applets There are two kinds of Java programs: stand-alone programs, known as applications, and programs that run in web browsers, known as applets. An applet is simply an application program that runs inside a browser. There are very few differences between programming an applet versus programming an application, in fact, a single binary can even be both. Everything you learn about Java application programming carries over to applet programming, and vice versa. You can put a web page with hypertext on a server, and clients such as browsers can download the page on demand to see the formatted text. Applets work in the same way. You write and compile a Java applet program, then place a URL or HTML reference to it in the web page. When a client browses that page, the Java applet binary is downloaded to the client along with the text and graphics files. The browser contains a JVM, and it executes the applet on the client computer. Originally, an applet was considered a little application, but in fact there is no size restriction on applets. Because the model is useful, applets of all sizes exist. Java applets fit very neatly into the client/server model of computing. By writing your Java program as an applet, you can put it on a web page and allow anyone, with any kind of computer, anywhere on your intranet or in the world to access and execute it automatically, without installing anything. When you update or change your applet, you simply put the new version on your web page, and on the next access, clients get the updated copy automatically. Software distribution problems, which were a major headache for installations with more than a dozen PCs, become a thing of the past. A less-visible but more valuable benefit is in system administration. Having one applet that is kept on a server and downloaded on demand by dozens or hundred of clients is a great way of doing zero-install client machines. These clients can just browse your page and go. When you update the software, you just put one new version on the server instead of sending disks to all the clients. The next time they browse the server, they automatically get the new version.

Java Notes #1

Page 4 of 15

Advanced Java Programming I

COMP-228

Java applets run on the client CPU, not the server-a true realization of distributed processing. A third benefit of applets is the automatic multimedia framework that the web browser provides (yes, the animations, sound effects, video, and so on). Finally, the platform-independence of Java is a boon to software developers and users alike. Applets make it much, much easier to program the "client" side of the client/server architecture. The applet concept provides the framework for free without the developer expending any effort on programming the underlying network transport protocols. These benefits can be realized by industrial-strength applets that do real work, as well as by toy animations. Applet Security Applets are the second major benefit of Java, enabled by Java's binary software portability (the first major benefit). But there must be restrictions on applets too. When any user can cause any program, anywhere in the world, to appear on his system and start executing just by virtue of his browsing a web page, there are security implications. No one wants to see a repeat of the virus problems endemic in the PC world. Without serious attention paid to the security aspect, Java applets would be too risky to run except in controlled circumstances on private nets. Any method for automatically downloading code into a browser and executing it should have some answers to the questions of computer security, not pose further problems. Fortunately, the designers of the Java system realized this from the outset and carefully put strong protective measures in place to allow applets to run without compromising a system. Java is the only system in use today, which allows for safe, secure downloading of executable content.

Introduction to Java Applications


Anatomy of a Java Application
An application is a standalone Java program that can run on any computer with a Java Virtual Machine. Applications are the ideal type for developing software. Lets consider a very simple Java application that displays a greeting on the console:
//First Java application public class Welcome { public static void main(String[] args) { System.out.println("Java is really cool!"); } }

Java Notes #1

Page 5 of 15

Advanced Java Programming I

COMP-228

Before we explain every line of the program above, lets consider a very important definition: A block is a sequence of statements and local variable declaration statements within braces. { statements } A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason. A local variable declaration statement declares one or more local variable names. For example: int x, String s, int a[]; which is equivalent with: int x; String s; int a[]; The scope of a local variable declared in a block, that means the portion of program where this variable can be referenced, is the rest of the block, including its own initializer. The first line of code starts with a comment that's marked by // characters All Java programs and so all applications consist of class definitions. In Java you cant program in C way. A class is a template of an object definition. We will explain objects and classes later on during this course. The class keyword starts the class definition in Java and must be followed by a class name, in our case Welcome. The class contains a special method called main. Every Java application must have a programmer-defined main(), which defines where the program begins. All Java applications begins execution at the main() method. The method signature for the main method contains three modifiers:
public static void main(String[] args)

public indicates that the main method can be called by any object. static indicates that the main method is a class method. void indicates that the main method doesn't return any value. The main method accepts a single argument: an array of elements of type String.
Java Notes #1 Page 6 of 15

Advanced Java Programming I

COMP-228

This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. The user enters command-line arguments when invoking the application and specifies them after the name of the class to run. For example, suppose you have a Java application, called Sort, that sorts lines in a file. To sort the data in a file named friends.txt, you would run it like this:
java Sort friends.txt

In the Java language, when you invoke an application, the runtime system passes the command-line arguments to the application's main method via an array of Strings. Each String in the array contains one of the command-line arguments. In the previous example, the command-line arguments passed to the Sort application is an array that contains a single String: "friends.txt". Java programs normally go through five phases edit compile load verify execute Phase 1 consists of editing a file with an editor program (normally known simply as an editor). Type a Java program (source code) using the editor Make any necessary corrections Save the program A file name ending with the .java extension indicates that the file contains Java source code. Linux editors: vi and emacs. Windows editors: Notepad, etc Integrated development environments (IDEs) Provide tools that support the software-development process, including editors for writing and editing programs and debuggers for locating logic errorserrors that cause programs to execute incorrectly. Popular IDEs: Eclipse (www.eclipse.org) NetBeans (www.netbeans.org) JBuilder (www.codegear.com)
Java Notes #1 Page 7 of 15

Advanced Java Programming I

COMP-228

JCreator (www.jcreator.com) BlueJ (www.blueJ.org) jGRASP (www.jgrasp.org) Phase 2 To compile a Java application use the javac compiler from the command line: javac Welcome.java Java compiler translates Java source code into bytecodes that represent the tasks to execute. Bytecodes are executed by the Java Virtual Machine (JVM)a part of the JDK and the foundation of the Java platform. JVM hides the underlying operating system and hardware from the programs that interact with it. If the same VM is implemented on many computer platforms, applications that it executes can be used on all those platforms. If the compilation succeeds, the compiler creates a file named Welcome.class in the same directory as the Java source file (Welcome.java). This class file contains Java bytecodes, which are platform-independent codes interpreted by the Java runtime system. You can execute the application using java interpreter as in the line below: java Welcome Notice that no file extension is supplied. Phase 3 The JVM places the program in memory to execute it. This is known as loading. Class loader takes the .class files containing the programs bytecodes and transfers them to primary memory. Also loads any of the .class files provided by Java that your program uses. The .class files can be loaded from a disk on your system or over a network. Phase 4 As the classes are loaded, the bytecode verifier examines their bytecodes. It Ensures that they are valid and do not violate Javas security restrictions. Java enforces strong security to make sure that Java programs arriving over the network do not damage your files or your system (as computer viruses and worms might). Phase 5 The JVM executes the programs bytecodes.

Java Notes #1

Page 8 of 15

Advanced Java Programming I

COMP-228

JVM typically uses a combination of interpretation and just-in-time (JIT) compilation. Analyzes the bytecodes as they are interpreted, searching for hot spotsparts of the bytecodes that execute frequently. A just-in-time (JIT) compiler (the Java HotSpot compiler) translates the bytecodes into the underlying computers machine language. When the JVM encounters these compiled parts again, the faster machinelanguage code executes. Java programs actually go through two compilation phases: One in which source code is translated into bytecodes (for portability across computer platforms) A second in which, during execution, the bytecodes are translated into machine language for the actual computer on which the program executes. Providing simple input/output functionalities for Java Applications: Now let consider a more complex application that calculates the sum of two integer numbers:
// Addition.java // An addition program import javax.swing.JOptionPane; // import class JOptionPane

public class Addition { public static void main( String args[] ) { String firstNumber, // first string entered by user secondNumber; // second string entered by user int number1, // first number to add number2, // second number to add sum; // sum of number1 and number2 // read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String to type int number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber ); // add the numbers sum = number1 + number2; // display the results JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

Java Notes #1

Page 9 of 15

Advanced Java Programming I

COMP-228

System.exit( 0 ); } }

// terminate the program

The first statement


import javax.swing.JOptionPane;

imports the class JOptionPane of the package swing, which provides the Java capabilities to input and output data in a Java console application. JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something By importing classes or packages, a class can more easily refer to classes in other packages. In the Java language, packages are used to group classes, similar to the way libraries are used to group C functions

Figure 1.2 Providing input for Java applications All the variable declarations take place at the beginning of the method body. These variables, like i, grade, total, average are called local variables. The variables that are declared at the beginning of class body are called instance variables. Local variables have a method scope, instance variables have a class scope. The following statement:
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

uses the method showInputDialog that shows a question-message dialog requesting input from the user. The method has the following syntax:
static String showInputDialog (Object message)

The input is assigned to the variable firstNumber that is a String variable. Later this value is returned to integer using the method parseInt of the Integer class.
number1 = Integer.parseInt( firstNumber );

The calculated sum is displayed on the screen using the method showMessageDialog of JoptionPane class:
JOptionPane.showMessageDialog(

Java Notes #1

Page 10 of 15

Advanced Java Programming I

COMP-228

null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

This method brings up a dialog that displays a message using a default icon determined by the message Type parameter. The syntax is as below:
static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)

The statement
System.exit( 0 );

terminates the program using the exit method of System class:


static void exit(int status)

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. Developing Java Applications with Eclipse IDE
Run Eclipse IDE by clicking on its icon:

Select File /New Project. Select Java and click Next. Name the project and specify other settings as is shown in figure 1.3:

Java Notes #1

Page 11 of 15

Advanced Java Programming I

COMP-228

Figure 1.3 Naming a Java project

Click Finish .

Java Notes #1

Page 12 of 15

Advanced Java Programming I

COMP-228

Figure 1.4 Package Explorer

Right-click on the Project name (AdditionTest) and select New/Class. Name the class as shown here:

Java Notes #1

Page 13 of 15

Advanced Java Programming I

COMP-228

Figure 1.5 Adding a new class to your project Make sure that you include the main method to this class as is shown above and click Finish. Write the following statement inside the main method: package test; import java.util.*; public class Addition { public static void main(String args[])

Java Notes #1

Page 14 of 15

Advanced Java Programming I

COMP-228

{ int x=0,y=0; Scanner scan = new Scanner(System.in); // Get the input System.out.println("\nEnter x: "); x = scan.nextInt(); System.out.println("\nEnter y: "); y = scan.nextInt(); int sum = x+y; System.out.println("\nsum= "+sum); } }

Run the application by selecting Run menu/ Run as/ Java application:

Figure 1.6 Running a Java application in Eclipse 3.4 IDE Cool eh!

References: Java Documentation Textbook

Java Notes #1

Page 15 of 15

You might also like