You are on page 1of 9

Birla Institute of Technology and Science, Pilani CS/IS C313: Object Oriented Programming and Design Lab Handout

1 Moving from C to Java


Lab Objectives: 1. Understanding the structure of a Java program. 2. Understand the basic differences between C and Java programs. 3. Learn how to write, compile and execute a typical Java programs? Note: Make sure that java is installed on your terminal. If not then change the terminal. Possible Lookout locations for java compiler are C:\Program Files\Java\jdk1.6.0\bin OR D:\Java\jdk1.6.0\bin The primary shift from C to Java is that you will have to learn how to think in an object-oriented sense. A C program is a collection of functions. A Java program is a collection of classes. A class is a block of code enclosed in a pair of braces {} that provides the definition for attributes (instance fields in Java) and operations (methods in Java) for that class. Java is more powerful and versatile than C. You can define how the methods and data from a class can be accessed by outside users (by declaring any attribute or method as public, private, protected or by default friendly access). Java Programming Language Java is true object oriented programming language in the sense that it supports all the three important pillars of object oriented systems namely encapsulation, inheritance and polymorphism in its truest sense. 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 (file having extension .java) is submitted to Java compiler (javac) for compilation then the source code (.java file) is compiled into binary file - 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 A Java program file (having extension .java) may contain any number of classes. If you want to execute any source java file after compilation then that source java file must contain driver class i.e. a class that contains the main() method implementation with following signature. public static void main(String[] args)

Page 1 of 9

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 package statement import statements 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.

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

xyz.java file

[Assume source file is named as xyz.java]

Java Compiler

javac

xyz.java

ByteCode

[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
Consider the following sample java program written in file named Test.java: 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 Test.java 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 {

Page 2 of 9

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 Test.java 5. class Demo 6. { 7. public static void main(String[] args) 8. { 9. System.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. Compile the source code 3. Run the program 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

Page 3 of 9

Save your program file as "HelloWorld.java" in some locatable directory in your hard disk. Dont forget to change Save as type to All Files instead of default Text Document (.txt). If you look at the code you will see the statement: class HelloWorld{ Its an instruction to call the class "HelloWorld". The filename must match this class name, hence the name "HelloWorld.java". The extension of ".java" tells the computer that its a Java code file.

Change it to All Files

Open a terminal window, press the "Windows key" and the letter R. You will see the "Run Dialog Box". Type "cmd", and press "OK". 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.

Page 4 of 9

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 where it is located on your disk. In your lab machine its in a directory called "C:\Program Files\Java\jdk\1.6.0_06\bin" OR D:\Java\jadk1.6.0\bin. If you dont have this directory, then do a file search in Windows Explorer for "javac" to find out where it located. Once youve found its location, type the following command into the terminal window: path= C:\Program Files\Java\jdk\1.6.0_06\bin if and only if javac is located in bin directory as mentioned otherwise set the path to the directory where javac is located E.g., 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. However, the path to the compiler has now been set.

If you have admin permissions then you can make the path entry permanent by creating a environmental variable named path as follows
(i) (ii) (iii) (iv) (v) Right Click My Computer icon Select Properties Select Environmental Advanced Select Environment Variables Check the User Variables for Administrator and look for variable named path. If exists, then select edit option to append the location of javac entry at the end such as C:\Program Files\Java\jdk1.6.0\bin at the end. If path variable does not exists then create the same by selecting new option with the same mentioned entry.

Next, navigate to where your HelloWorld.java file is saved. To change the directory in the terminal window, type in the command: cd *directory where HelloWorld.java file is saved* E.g., cd C:\Documents and Settings\Nirmal\My Documents\Java You can tell if youre at the right directory by looking to the left of the cursor. Were now ready to compile the program. To do so, enter the command: javac HelloWorld.java After you hit Enter, the compiler will look at the code contained within the HelloWorld.java file, and attempt to compile it. If it cant, it will display a series of errors to help you fix the code.

Page 5 of 9

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. All thats left to do is run the program. In the terminal window type the 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[] args) { int main(void) { System.out.println("Hello World!"); printf("Hello World!\n"); } return 0; } } 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.
S.No. 1. Code byte x = 640; byte b=10; float f = 10.56; byte b1 = 10; b1++; // or you can write b1--; System.out.println(b1); short s1 = 40; s1++; // or you can write s1--; System.out.println(s1); byte b1 = 10; b1 = b1 + 1; System.out.println(b1); // Try by changing the type of b1 as short and long byte b = 10; b *= 50; // you can try with +=, -=, etc System.out.println(b); short s = 4000; s *= 100; System.out.println(s); byte b = 10; b = b*50; Output

2.

Page 6 of 9

7.

8.

9.

10.

11.

System.out.println(b); short s = 4000; s = s*100; System.out.println(s); int a = 1; if(a=1) System.out.println(Hello); else System.out.println(Hi); float x = 10.5f; double y = 10.5; if(x==y) System.out.println(Hello); else System.out.println(Hi); float x1 = 10.57f; double y1 = 10.57; if(x1==y1) System.out.println(Hello); else System.out.println(Hi); byte b = -128; System.out.println(--b); byte b1 = 127; System.out.println(++b); for(byte b=0;b<200;b++) System.out.println(b); byte b=(byte)670; System.out.println(b); short s = (short) 40000; if(10) System.out.println(Hello); else System.out.println(Hi); System.out.println(10+20+10+20); System.out.println(10+(20+10)+20); System.out.println(10+20+10+20); System.out.println(10+20+(10+20));

Exercise 2: [Command Line Arguments] 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; 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: [How to read user input from System.in i.e. keyboard] Write a program in java to compute and print the sum of two numbers entered via System.in i.e. keyboard. // Method 1 Using try catch block import java.io.*; // import the package java.io for BufferedReader class class Ex3 { public static void main(String[] args) { int num1,num2,sum; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try

Page 7 of 9

{ System.out.println(Enter First Number :); /* 1. You can use readLine() method of BufferedReader class to read string form of data from System.in 2. Use parseInt() Method of Integer class. parseInt() is static method of Integer class. It converts String to integer provided string is in integer form. Otherwise it throws a NumberFormatException */ num1 = Integer.parseInt(br.readLine()); // Read First Number num2 = Integer.parseInt(br.readLine()); // Read Second Number sum = num1 + num2; System.out.println(Sum of the numbers is :+sum); } // End of try block catch(IOException ex){} }// End of main() Method }// End of class ex3 // Method 2 Using throws clause import java.io.*; // import the package java.io class Ex3 { public static void main(String[] args) throws IOException { int num1,num2,sum; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(Enter First Number :); num1 = Integer.parseInt(br.readLine()); num2 = Integer.parseInt(br.readLine()); sum = num1 + num2; System.out.println(Sum of the numbers is :+sum); }// End of main() Method }// End of class ex3 Exercise 4: (a) Predict the output of the following code fragments and note down the reason for the same. // name of source file Ex4.java // name of source file Ex4.java class A { } class A class Test { { public String toString() public static void main(String args[]) { { System.out.println(Hello); A a1 = new A(); } System.out.println(a1); } }// End of main() Method class Test }// End of clas Test { public static void main(String args[]) { A a1 = new A(); System.out.println(a1); }// End of main() Method }// End of clas Test (b) Predict the output of the following code fragments and note down the reason for the same. // name of source file Ex4.java // name of source file Ex4.java class A { } class A class Test { { public boolean equals(A other) public static void main(String args[]) { { return true; A a1 = new A(); } A a2 = new A(); } System.out.println(a1.equals(a2)); class Test }// End of main() Method {

Page 8 of 9

}// End of clas Test

public static void main(String args[]) { A a1 = new A(); A a2 = new A(); System.out.println(a1.equals(a2)); }// End of main() Method }// End of clas Test

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 in java which when executed prints the following output. * ** *** **** ***** ****** ***** **** *** ** *

Page 9 of 9

You might also like