You are on page 1of 8

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 codes. 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 were based from C and C++, so if your a C or C++ programmer, migrating to Java would be very easy.

Java also took away the concept of pointers which is the waterloo of most C programmers. Instead of pointers, what Java has are references.

Multi threaded Java applications can run several threads.

Page 1 of 8

Prepared by: Lawrence G. Decamora III, scjp

Network aware Java applications can run across any type of network.

Cross Platform Java can run in any platform. This feature is valuable to a lot of customers who have invested on a lot of hardware 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 any platform 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.

Secure Java is said to be secured because it runs 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.

Page 2 of 8

Prepared by: Lawrence G. Decamora III, scjp

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. JME Java Micro Edition 2. JSE Java Standard Edition 3. JEE Java Enterprise Edition Before it used to be J2ME, J2SE, J2EE, but as of version 5.0, they decided to drop the 2. JSE contains the standard class libraries. JSE can be used to create applet and/or desktop applications. JEE 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. JME 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 JME, JSE and JEE interact with one another.

Page 3 of 8

Prepared by: Lawrence G. Decamora III, scjp

Job Responsibility of your Java Virtual Machine (JVM) The JVM, also known as the Java Virtual Machine can read complied byte codes which is embedded inside your *.class file. Your Java byte code ensure 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 dynamicness of Java, being able to check and evaluate forms and types during runtime. The JVM can execute on multiple operating environment. 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 that 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. 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 occupies. 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.

Page 4 of 8

Prepared by: Lawrence G. Decamora III, scjp

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 to 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 (pointers to integer 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. 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 {
Page 5 of 8 Prepared by: Lawrence G. Decamora III, scjp

3 4 5 6 7

public void printGreetings() { System.out.println("Hello, Java World.."); }

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. 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 where your application suppose to start. All Java applications 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:

Page 6 of 8

Prepared by: Lawrence G. Decamora III, scjp

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. 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

Page 7 of 8

Prepared by: Lawrence G. Decamora III, scjp

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, its 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.... 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 8 of 8

Prepared by: Lawrence G. Decamora III, scjp

You might also like