You are on page 1of 8

Birla Institute of Technology and Science, Pilani CS F213/IS F213 Object Oriented Programming Lab 1 Moving from C to Java

a Lab Objectives: 1. Understanding the structure of a Java program. 2. Understand the basic differences between C and Java program. 3. Learn how to write, compile and execute a typical Java program.

Java Programming Language Java is an object-oriented programming language. Object-oriented programming uses objects to mimic real life. Our world is filled with objects that interact with one another. For example, let's consider a class of objects called Car. If I tell you that I just bought a new car, you would have a basic idea of what I purchased. A Car has both characteristics such as make, model, and color, and behaviors such as the ability to start, accelerate and stop. In object-oriented terminology we say, a class describes the characteristics and behaviors that objects of this type have. The class is not the same as the object. Rather, the class is a template from which objects can be created. Therefore, we say an object is an instance of a class. My car is an object that is a specific instance of the class Car. It is a new Car whose make is Maruti, model is Swift and color is red. I can send messages to my car to invoke its behaviors. For example, inserting a key into the ignition and turning it clockwise sends a message to my car to start. When I want to send a message to my car to accelerate, I step on the gas pedal. Stepping on the brake, sends the message to stop. Let's list some other examples of a class and objects that are created from the class. Class Movie Clock Student Attributes Length, Cast, Name Time, color Name, Id Methods getMovieName(),findBudget() Settime(),changeTime() Changeid(),findname() Object Bol Baccahn, Robot. kitchen clock, classroom clock Ramesh, Mahesh

Java is compiled as well as an interpreted programming language. Any Java program file must have the extension (.java). Java is compiler oriented from compilation point of view. When a source .java file is submitted to Java compiler (javac) for compilation then the source code (.java file) is compiled into binary file which is also called a byte code file (.class files). [Note that every class defined in the source file will be converted into its corresponding .class file iff there are no compiler errors]. Now you need an interpreter called Java Virtual Machine (JVM) to run it. Java source code is first translated into Java bytecodes which are (virtual) machine-readable class files having a .class extension, using the Java compiler javac. If a source file has more than one class, each class is compiled into a separate .class file. These .class files can be loaded by any Java Virtual Machine (JVM). The format of the bytecode is the same on all implementations of the JVM. The JVM interprets the byte code and executes it. Figure 1 explains the whole compilation and execution process. Java compiler is called javac.exe, and interpreter is called java.exe. Figure 1 shows a Java technology overview.

Figure 1
Structure of any Java Program

Page 1 of 8

A Java program file (having extension .java) may consist any number of classes. If you want to execute any source java file after compiling then the source file must contain driver class i.e a class that contains the main() method implementation with following signature. public static void main(String[] args) One similarity between Java and C is that both languages use a main() function (or method from javas point of view) to define the entry point for program execution. The system calls the main() function when the program is run. The following figure shows the various program components of a source java file. Component Documentation Section /** */ Documentation Comments // Single Line Comment /* */ Multi line Comments Purpose Documentation comments are written to explain to humans what the program does. These comments are ignored by the Java compiler; they are included in the program for the convenience of the user to understand it. It specifies the package name to which classes defined in current source file belong to. In a single source .java file only one package statement can exists. The import statement in Java allows referring to classes which are declared in other packages. Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. A class definition defines instance and class variables and methods to instantiate objects belonging to that class. A "Driver class" is just the class that contains a main() method which defines the starting point for a program execution.

package statement

import statements

interface definitions

class definitions

Driver class (If you want to execute the program)

The source .java file is compiled by java compiler javac.exe. The compilation process will create bytecodes corresponding to source code. Since a java file may consist of more than one classes therefore one .class file is created corresponding to each class definition in source file. These .class files are equivalent bytecodes. Then java interpreter java.exe interprets these bytecodes to the machine code of local machine architecture.

Source Code file

[Assume source file is named as]

Java Compiler



[if the compilation is successful then every class defined in the above source file will be converted to .class file]

Java Interpreter

java <name of the driver class>

Machine Code

Page 2 of 8

Consider the following sample java program written in file named class A { } class B { } class C { } The compilation of this file would create three .class files namely A.class, B.class and C.class. [Note is simply the name of the source file. But after successful compilation there will be no class file with name Test.class because the file does not have a class named Test] Since none of the classes contain main method, program can be compiled but can not be executed. Let us change the above program a little and include a main method in class C. class A { } class B { } class C { public static void main(String[] args) { } // ---- Driver Method } The above program will be compiled and can be executed also using class C as the driver class. But it will do nothing because no executable statements are included in main method definition. Two or more classes can also contain their main method definition in the same file. But which main method will be executed will depend on the class which is interpreted by using java.exe. An example is given below: 1. /* 2. Simple program to print Hello! World. 3. */ 4. // name of the source file 5. class Demo 6. { 7. public static void main(String[] args) 8. { 9. Sytem.out.println("Hello! World"); 10. } 11. } Line 1-4 Line 5 Line 7 Commented Section. Start of definition for class Demo First line of main method. Each word has the following meaning. public main method has global scope static main method is class method not a object method void return type for main method String[] args String array used to hold command line arguments passed during program execution. Java statement for displaying Hello! World on System.out

Line 9

In java there is print() and println() methods. Both are used to output text to a stream but the difference is that println() appends a new line automatically and if we print something after println() it will be in a new line but print() wont add a new line. The following examples show the difference with equivalent C statements for print() and println() methods in Java. In Java In C System.Out.print(hello); printf(hello); System.Out.println(hello); printf(hello\n); Writing your first program in Java The basic steps we will follow for our Hello World program are: 1. Write the program in Java 2. Saving file 3. Setting Environment 4. Run the program

Page 3 of 8

Step 1: Writing Java Program

You can use any text editor program (such as notepad, notepad++,wordpad) for typing Java programs. Various IDEs (Integrated Development Environment) for Java (e.g. netbeans) are also available which assist in writing, compiling and executing java applications. For your first program, open up the simplest text editor you have on your computer. Let us use Notepad. The program code looks like this: // The classic Hello World program! class HelloWorld { public static void main(String[] args) { //Write Hello World to the terminal window System.out.println("Hello World!"); }// End of main() Method } // End of class HelloWorld

Step 2: Saving file

Save your program file as "" in some locatable directory in your hard disk. Dont forget to change Save as type to All Files instead of default Text Document (.txt).

Step 3: Setting Environment

Open a terminal window, press the "Windows key" and the letter R. You will see the "Run Dialog Box". Type "cmd", and press "OK".

Page 4 of 8

A terminal window will appear on your screen, it will let you navigate to different directories on your computer, look at the files they contain, and run programs. This is all done by typing commands into the window.

Every Java program you write will have to be compiled before it can be run. To run javac from the terminal window, you first need to tell your computer where it is. In your lab machine its in a directory called "C:\Program Files\Java\jdk\1.6.0_06\bin". If you dont have this directory, then do a file search in Windows Explorer for "javac.exe" to find out where it lives. Once youve found its location, type the following command into the terminal window: set path=C:\Program Files\Java\jdk\1.6.0_06\bin Press Enter. The terminal window wont do anything flashy, in fact it will just return to the command prompt. To look the current path type the following command at command prompt path

Next, to navigate your file, change the drive by typing the following command drivename: // (D:) To change the directory the following command cd floder name // (cd sunita)

Step:4 Compile and Run Program

To compile type the following command javac

Page 5 of 8

After you hit Enter, the compiler will look at the code contained within the file, and attempt to compile it. If it cant, it will display a series of errors to help you fix the code. Hopefully, if you have no errors otherwise if thats not the case, go back and check the code youve written. Make sure it matches the example code and re-save the file. Keep doing this until you can run javac without getting any errors. To run type the following command java HelloWorld When you hit Enter, the program runs and you will see "Hello World!" written to the terminal window. Well done. Youve written your very first Java program!

Now you know the steps every Java program has to go through: 1. Write the Java code in a text file 2. Save the file 3. Compile the source code 4. Fix any errors 5. Run the program If we compare the above HelloWorld program with the equivalent C program then it can be written as: Java Program C Program class HelloWorld { #include<stdio.h> public static void main(String[] int main(void) { args) { printf("Hello World!\n"); System.out.println("Hello return 0; World!"); } } } Exercise1: Consider the following class definition: class DriverTest { public static void main(String[] args) { } } What will be the output [Either Compile Time Error or RunntimeException] if an attempt is made to compile and execute the above java file by writing each of the following code fragments in the main method. Observe the output and write it in the Output column. Exercise2: Write a program in java to compute and print the sum of numbers entered via command line arguments. class Ex2 { public static void main(String[] args) { int sum=0;

Page 6 of 8

for(int i=0; i<args.length;i++) sum = sum + Integer.parseInt(args[i]); System.out.println(Sum of the numbers is :+sum); }// End of main() Method }// End of class Ex2 What will be output of above program if it is executed with following commands? a). java Ex2 b). java Ex2 a 12 c). java Ex2 a b d). java Ex2 12 13 6 34 56 Exercise 3: A. Define a class Greeter Class Greeter { private String name; // attribute Greeter(String Name) // it will initialize greeter class { name = Name; } public string sayHello() // This method will print the hello with name {System.out.println(Hello + name); } } // end of Greeter class B. Define a driver class that wills instantiated the Greeter class Class Driver { public static void main(String args[]) { Greeter sunitaGreeter = new Greeter(Sunita); sunitaGreeter.sayHello(); // calling the method } // end of main } // end of class C: Now compile and run program. Exercise 4: A. Define a class Car which encapsulates following attributes and methods Attributes: private scope year - The year field is an int that holds a car's year model (e.g. 2010) make - The make field is a String object that holds the make of the car (e.g. "TATA") speed - The speed field is an double that holds a car's current speed (e.g. 25.0)

//instantiated the reference object

Constructor: class scope The constructor should accept the car's year, make, and beginning speed as arguments /* These values should be used to initialize the Car's year, make, and speed fields */ Methods: public scope getYear() getMake() getSpeed()

// These methods return the values stored in an object's fields.

Accelerate() /* This method adds 1 to the speed attribute each time it is called. For example: if the car was going 3 mph, accelerate would set the speed to 4 mph */

Page 7 of 8

Accelerate(int increment) /* This method adds the increment into current speed. Break(int b) /* This method decrements the current speed by square root of b. For example: if the car was going 30 mph, break is called with 4 then speed would set the speed to 28 mph */ B. Define a RaceTrack class that has main method do the following activities. Create a new Car object (using the Car constructor method), passing in the year, make, and speed. Display the current status of the car object using the getter methods getYear(), getMake(), and getSpeed() Call the car's Accelerate method and then re-display the car's speed using getSpeed() Call the car's Accelerate(10) method and then re-display the car's speed using getSpeed(). Call the car's break method by passing some value and then re-display the car's speed using getSpeed() Now, create a new Car object without passing arguments. Compile and observe the output.

Exercise 5: Write a program in java which computes and prints the sum of the following series. x x3/!3 + x5 / !5 x7 / !7 +x9 / !9 - .N terms [Note: x and N are supplied via command line arguments] Exercise 6: Write a program that takes a string as command line input and check whether a given URL(uniform resources locator) is valid or not. A valid URL contains at least two dots (.) separated by at least one character. For example and are valid URL while is not valid.

Page 8 of 8