You are on page 1of 9

1. What do you mean by Java Virtual Machine? Explain.

Answer: The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is byte code. Byte code is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for byte code. This may come as a bit of a surprise. As you know, C++ is compiled to executable code. In fact, most modern languages are designed to be compiled, not interpreted mostly because of performance concerns. However, the fact that a Java program is executed by the JVM helps to solve the major problems associated with downloading programs over the Internet. Here is why. Translating a Java program into byte code helps make it much easier to run a program in a wide variety of environments. The reason is straightforward: only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all interpret the same Java byte code. If a Java program were compiled to native code, then different versions of the same program would have to exist for each type of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the interpretation of byte code is the easiest way to create truly portable programs. The fact that a Java program is interpreted also helps to make it secure. Because the execution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside of the system. As you will see, safety is also enhanced by certain restrictions that exist in the Java language. When a program is interpreted, it generally runs substantially slower than it would run if compiled to executable code. However, with Java, the differential between the two is not so great. The use of byte code enables the Java run-time system to execute programs much faster than you might expect.

2. Write a program in Java to find factorial of a number. How do you compile and execute this Java program? Answer: import java.io.*; class Factorial { public static void main(String[] args) { BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the number"); int a= Integer.parseInt(object.readLine()); double fact= 1; System.out.println("Factorial of " +a+ ":"); for (int i= 1; i<=a; i++) { fact=fact*i; } System.out.println(fact); } } Compiling the Program: A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmerreadable text in your program file (also called source code) and converting it to byte codes, which are platform-independent instructions for the Java VM. The Java compiler is invoked at the command line on Unix and DOS shell operating systems as follows: javac Factorial.java Interpreting and Running the Program Once your program successfully compiles into Java byte codes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. Interpreting and running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent machine codes so your computer can understand and run the program. The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows: java Factorial
2

3. Write a simple Java program to illustrate the use of if else statement. Answer: Syntax: If (Boolean-expression) { If-code; } Else { Else-code; } Rest-of-code;

If the Boolean-expression is true If-code gets executed. If Boolean-expression is false Else-code gets executed. In this decision making statements generally either of the block gets executed whether its Ifcode or Else-code, after either execution Rest-code gets executed. Using if-else statement to check whether a given number is even or odd public class EvenOrOdd { public static void main(String[ ] args) { int[ ] numbers = new int[ ]{11,23,34,45,56,67,78,89,90,104}; for(int i=0; i < numbers.length; i++) { if(numbers[i]%2 == 0) System.out.println(numbers[i] + " is even number."); else System.out.println(numbers[i] + " is odd number."); } } }

4. What do you mean by an array? Explain with an example. Answer: An array is a contiguous memory allocation of same-sized or homogeneous data-type elements. The word contiguous means the array elements are located one after the other in memory. The term same-sized means that each array element occupies the same amount of memory space. The size of each array element is determined by the type of objects an array is declared to contain.

Declaring an Array int[] Values; // brackets before name (recommended) Declaring an array of object references: Ferrari[] Ferraris; // Recommended Constructing an Array Constructing an array means creating the array object on the heap i.e., doing a new on the array type. To create an array object, Java must know how much space to allocate on the heap, so you must specify the size of the array at creation time. The size of the array is the number of elements the array will hold. Constructing One-Dimensional Arrays The most straightforward way to construct an array is to use the Keyword new followed by the array type, with a bracket specifying how many elements of that type the array will hold. The following is an example of constructing an array of type int: int[] myArray; // Declares the array of ints myArray = new int[4]; // constructs an array and assigns it // to the myArray variable The preceding code puts one new object on the heap-an array object holding four elements-with each element containing an int with a default value of 0. Think of this code as saying to the compiler,

int[] myArray = new int[4];

5. Write a program to explain the Exception handling mechanisms in Java using the keywords: try, catch and finally. Answer: Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program. Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the try keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the catch keyword. You may also write an optional finally block. This block contains code that is ALWAYS executed, either after the try block code, or after the catch block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)

*Program to show try catch and finally block import java.io.*; class Factorial1 { public static void main(String[] args) { try { BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the number"); int a= Integer.parseInt(object.readLine()); double fact= 1; System.out.println("Factorial of " +a+ ":"); for (int i= 1; i<=a; i++) { fact=fact*i;
7

} System.out.println(fact); } catch (Exception e) { System.out.println("Array out of bounds exaception"); ) Finally { System.out.println("finally"); } } }

6. Define (i) Inheritance (ii) Package and (iii) Interface. Answer: (i) Inheritance: The philosophy behind inheritance is to portray things as they exist in the real world. For instance, a child inherits properties from both the parents. Inheritance means that a class derives a set of attributes and related behaviors from another class. Inheritance helps you to: -Reduce redundancy in code. Code redundancy means writing the same code in different places, leading to unnecessary replication of code. Inheritance helps you to reuse code. - Maintain code easily, as the code resides at one place (superclass). Any changes made to the superclass automatically change the behavior automatically. - Extend the functionality of an existing class by adding more methods to the subclass. The following are some limitations of Java class inheritance: - A subclass cannot inherit private members of its superclass. - Constructor and initializer blocks cannot be inherited by a subclass. - A subclass can have only one superclass (ii) Package: Package is basically a collection of predefined or ready-made classes that can be used in your java program to make shorter as well as easier. Package- import java.lang.*; is always implicitly called when you write a java program. Packages are containers-for-classes used to keep the class namespace compartmentalized. (iii) Interface: Using the keyword interface, you can fully abstract a class' interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. In practice, this means that you can define interfaces which don't make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. To implement an interface, a class must create the complete set of methods defined by the interface. However, each class is free to determine the details of its own implementation. By providing the interface keyword, Java allows you to fully utilize the "one interface, multiple methods" aspect of polymorphism. Interfaces are designed to support dynamic method resolution at run time. Normally, in order for a method to be called from one class to another, both classes need to be present at compile time so the Java compiler can check to ensure that the method signatures are compatible. This requirement by itself makes for a static and non extensible classing environment. Inevitably in a system like this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms will be available to more and more subclasses. Interfaces are designed to avoid this problem. They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in terms of the class hierarchy to implement the same interface.

You might also like