Sie sind auf Seite 1von 9

Chapter 1: Get Started and sip your first Java cup... (4.

5 hrs)
Chapter Objective:
Describe the key features of Java
List the three flavors of Java
Describe the function of the Java Virtual Machine (JVM)
Describe the function of the Java Runtime Environment (JRE)
Describe the job of Garbage Collector
Describe the three task performed by Java in handling code security.
Create Your First Java Application. The HelloWorld Program.
Debugging compile time errors and runtime errors
Examine Java Classes.
Java key features
Object Oriented
Object Oriented Programming Languages supports three main features: encapsulation,
Inheritance, and polymorphism. In Java, we create programs that is patterned to real life objects.
These objects may interact with other objects like a Student object can interact with a Teacher
object. Also, the nice thing about object oriented programming is its capability to reuse code. You
can create an object that will be used in a project and reuse it in another. Like if you've created an
application you can reuse the same classes for a web application.

Let's say in a Banking Application, you may write a code that represents a Bank
Customer calling it Customer class. This Customer class can actually be reused in other
Application not related to a Banking Project, let's say in an Order and Purchasing Application
System. You don't have to reinvent the wheel or rewrite the Customer class code. What you can
do is to reuse them as they fit in your system.
Simple
Most of the Java syntax was based from C and C++, so if you are a C or C++
programmer, migrating to Java would be very easy.

Java made it easier for C programmers to absorb the concepts of pointers. Instead of
pointers, Java uses the concept of references.
Multi threaded
Java applications can run several threads. A thread is a Virtual CPU. It contains three
things, the CPU (Thread Class), Code and Data.

Multithreading is extremely useful in practice. For example, a browser should be able to


simultaneously download multiple images. A web server needs to be able to serve concurrent
requests, each request served is a thread processed. Graphical user interface (GUI) programs
have a separate thread for gathering user interface events from the host operating environment.

Page 1 of 9

Prepared by: Lawrence G. Decamora III, scjp

Network aware
Java applications can run across most types of network.

Cross Platform
Java can run in most popular platform. This feature is valuable to a lot of customers who
have invested on a lot of hardware like minicomputers, mainframes or even desktop computers.
They do not want to throw away these investments when they use another set of standards.

One of the nice things about Java is its capability to run in most platforms once you've
compiled it. You need to compile your *.java file to produce a *.class file which also contains your
Java byte code. Then you can let your *.class run in any Java Runtime Environment on any
platform.

Page 2 of 9

Prepared by: Lawrence G. Decamora III, scjp

Secure
Java is said to be secured because it runs the applications on top of the Java Virtual
Machine (JVM) and your JVM sits on top of your operating system. It simply means that your
Java application does not have a direct attachment or a direct contact with your operating system.

Supports GUI
Using Java, you can also create Graphical User Interface (GUI) Applications which
enables the user to make use of Buttons, Frames and TextFields. Java has a built-in Abstract
Window Toolkit (AWT) which makes use of the standard GUI components. Besides AWT, Java
also supports Java Foundation Classes (JFC) / Swing, which is supported under the javax (java
extension) package. JFC / Swing is the second generation GUI toolkit and it is light weight as
well.

Using JFC / Swing, you can customize your look and feel of your GUI application and it
has a wider range of GUI components that you can choose from.
Three (3) Flavors of Java

1. JavaME Java Micro Edition


2. JavaSE Java Standard Edition
3. JavaEE Java Enterprise Edition
In the good old days, it used to be J2ME, J2SE, J2EE, but as of version 5.0, they decided
to drop the 2. JavaSE contains the standard class libraries. JavaSE can be used to create applet
and/or desktop applications.
JavaEE contains the standard libraries and other extended API's (Application Program
Interface). These extended API's or class libraries are usually needed for Enterprise Applications.
JavaME contains a strip-down version of the standard library of JSE, it is used for
creating small applications that can run on palm-tops, mobile phones and other embedded
devices.
This is how JavaME, JavaSE and JavaEE interact with one another.

Page 3 of 9

Prepared by: Lawrence G. Decamora III, scjp

Job Responsibility of your Java Virtual Machine (JVM)


The Java Virtual Machine, also known as the JVM can read compiled byte codes which is
embedded inside your *.class file. Your Java byte code ensures that the *.class that your running
came from a valid compilation.
The JVM can also be customized. Certain companies would prefer to customize their own
JVM, this is allowed by Sun Microsystems as long as the implementation of this JVM can run any
valid *.class file and is approved by Sun Microsystems.
Majority of the objects type is being checked by the compiler, but there are still some
parts of the code that should be checked during runtime. This enables the dynamism of Java,
being able to check and evaluate forms and types during runtime.
The JVM can execute on multiple operating environments. You just need to download the
correct Java Runtime Environment (JRE) for your operating system.
The Java Runtime Environment
The Java Runtime Environment contains two main components:
1. Java Virtual Machine (JVM)
2. Application Programming Interface (API), in other programming language it can be
thought of as a set of class libraries.
Every time you run an application you need to execute the runtime environment first.
Once you've done this, your actually launching the JVM on top of the Operating System so that
your valid *.class can now be interpreted. Your API on the other hand, just provides all the
standard libraries that your program needs during runtime. The manner of accessing this
standard API is basically the same across all platform.
Before actually downloading your JRE, you need to know first what type of operating
system you are using, there is a unique JRE for each operating system but the implementation of
the API for these JRE's are the same.

Page 4 of 9

Prepared by: Lawrence G. Decamora III, scjp

Here's your friendly neighborhood Garbage Collector


Garbage Collection is the process of deallocating memory spaces that is no longer
needed. In other programming language, this is the job of the programmer.
In Java, this is the job of the Garbage Collector. The Garbage Collector, (GC) is a system
level thread that runs at the background. If the JRE is up and running, the GC also runs at the
background. It tracks and monitors created objects. So if an object is ready for garbage collection
the GC runs and clears up the memory space that the object occupied.
The implementation of the GC varies on different platform, since its a system level thread,
the thread scheduler of the Operating System decides when the GC should run. Although you can
set the GC in a runnable state by executing the method System.gc(); this method call does not
force the GC to run, it just puts it in a runnable state.
The runnable state is the state of the thread that is ready to run, it does not mean that it
is actually running.
Three task performed by Java in handling code security
This job is handled by following:
1. Class loader
2. Byte code verifier
3. Interpreter.
Class Loader
The Class Loader loads all classes needed for the application to run. It also adds security
by separating the name spaces for the classes of the local file system (FAT, UFS, NTFS, ZFS)
from those imported from network resources. This limits any Trojan Horse applications to
penetrate your machine because local classes are always loaded first. After all the classes have
been loaded, memory layout occurs during runtime.
Byte Code Verifier
Your Java source file (*.java) once compiled will be transformed to a class file (*.class)
which contains your Java Byte Code.
The JVM lets your class file pass through a byte verifier to ensure that your code
complied with the JVM specification and your class file is an actual product of a valid Java
compilation and not just a product of saving a file having an extension of .class.
The Byte Code Verifier ensures that your code adheres to the JVM specification and does
not violate any system integrity. The Byte Code Verifier also checks for all operational codes and
ensures that they are correct. It also ensures that there are no illegal data conversion that will
happen in your code (e.g. pointer value to integer value and vice versa).
Interpreter
After loading the local class to the memory and verifying if its a valid class file, the next
step is to interpret the class file. Runtime occurs during the interpretation of a valid class file. It is
during this time that RuntimeExceptions can occur.
RuntimeException will be discussed on a separate chapter.
HelloWorld...Your First Java Application.

Page 5 of 9

Prepared by: Lawrence G. Decamora III, scjp

Program 1.1: TestHelloWorld.java


1 /***********************************************
2 *
*
3 * This is a simple HelloWorld Application *
4 *
*
5 ************************************************/
6
7 public class TestHelloWorld
8 {
9
public static void main(String args[])
10
{
11
HelloWorld hw = new HelloWorld();
12
hw.printGreetings();
13
}
14 }
Program 1.2: HelloWorld.java
1 public class HelloWorld
2 {
3
public void printGreetings()
4
{
5
System.out.println("Hello, Java World..");
6
}
7 }
TestHelloWorld.java
Lines 1 to 5: are Java Comments.
Comments are part of the program code that is skipped by the compiler.
Line 7: public class TestHelloWorld
public means that the class can be accessed anywhere by anyone.
class is a keyword in Java that represents a class construct
TestHelloWorld is a user defined identifier that represents the name of your class. Since
TestHelloWorld has a public access modifier it means that it can be accessed anywhere by
anyone. Also, if a class has a public access modifier, it means that the file name should be the
same as your class name.
RULE: Your public class name should have the same name as your filename (*.java file).
{ }: a pair of braces represents a scope. It is used to group related program segments. It can be
used for control structures, methods and classes.
RULE: In your Java code,
there should be an equal number of begin brace ( { ) and end brace ( } ).
Line 9: public static void main(String args[])
public means that your method is accessible anywhere
static is a type of modifier that means that your method will not be owned by any object but the
exclusive ownership will belong to the class.
Page 6 of 9

Prepared by: Lawrence G. Decamora III, scjp

void is the return type of the main method. It means that the main method should not return any
type of value.
main this is the name of the method. However, the main method is a special type of method that
tells Java that this is the starting point of your application. All Java application starts its execution
at the main method and its method signature should be public static void main(String
args[]).
String args[] this goes inside the parameter list of your main method. This means that your
main method should accept an array of String objects as its parameter.
RULE: The execution of any Java Application always starts with your main method.
The signature of your main method should be:
public static void main(String args[])
Line 11: HelloWorld hw = new HelloWorld();
Line11 can be rewritten this way:
1a
2a

HelloWorld hw;
hw = new HelloWorld();

// object reference declaration


// object creation

Line 1a allows you to declare an object reference called hw. This


is just an object reference, no actual object has been created at
this point.
Line 2a new HelloWorld() creates the actual HelloWorld
object from the HelloWorld class. This object now is assigned to
a reference called hw.
HelloWorld.java
Line 1: public class HelloWorld
Declares your class HelloWorld.
Lines 3 to 6: printGreetings() is a method that will print the String Hello Java World..
3
public void printGreetings()
4
{
5
System.out.println("Hello, Java World..");
6
}
Line 5: System.out.println("Hello, Java World.."); Allows you to print a String
value to the standard output device. The monitor.
Bug-off!!! Debugging compile time errors and runtime errors
Common Compile time errors.
The following are the common compile time errors encountered by Java newbies. Once
you've encountered these compile time errors you need to debug them, save your code and
recompile. After fixing all the compile time errors, you can now run your sample application.

javac command not found


The javac command is located under the subdirectory \bin of the installed Java Development
Kit (JDK) directory. You must update your path directory and include the location of your
javac executable file.

Page 7 of 9

Prepared by: Lawrence G. Decamora III, scjp

HelloWorld.java:5: cannot resolve symbol


symbol : method printl (java.lang.String)
location: class java.io.PrintStream
System.out.printl(Hello, Java World);
^
The println() method is type incorrectly.

Class and file naming


Your .java file should have the same name as your public class. If this rule is not followed
correctly you will have a compiler error similar to this:
TestHelloWord.java:7: public class TestHelloWorld must be
defined in a file called TestHelloWorld.java

Number of public classes in a Java source file


You can only have one public class in a Java source file. If you declared more than one public
top level class, you will have a similar compilation error.
You can have many class declarations inside a Java source file as long as there is only one
class that will be declared public and the file name of the Java source file should be the same
as the name of your public class.

Common Runtime errors


After having a clean compile, it's now time for you to run your sample application. During
runtime, you may encounter some runtime errors along the way. Here are some examples of
runtime errors:

Can't find class TestHelloWorld


This runtime error will occur if you attempt to run a file that is not existing or if your attempting
to run a misspelled file. The filename should have the same spelling as the filename.class
file.

Exception in thread main java.lang.NoSuchMethodError: main


This means that your main method is incorrectly declared. Your main method must be
public, and it should also be static and must have a return type of void and it should
also be called main and must accept an array of String object as its parameter list.
Another probable reason why this runtime error occurs is when you attempt to run a class file
that does not have a public static void main(String args[]) method in it. The
main method is the entry point of your application execution, thus it should be present when
you try to run your Java Application.

When Java had a class....

Page 8 of 9

Prepared by: Lawrence G. Decamora III, scjp

TestHelloWorld.java

HelloWorld.java

Also
compiles
Javac

Java

TestHelloWorld.class

HelloWorld.class

J VM
You only need to compile one file TestHelloWorld.java and the other file
HelloWorld.java will automatically compile. This is because before TestHelloWorld.java
can successfully compile Java looks for a compiled version of HelloWorld.java first. Thus
HelloWorld.java will be the first file that will be compiled before TestHelloWorld.java
completes its compilation.

Page 9 of 9

Prepared by: Lawrence G. Decamora III, scjp

Das könnte Ihnen auch gefallen