Sie sind auf Seite 1von 9

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1)

1. Why is security required in Java? Discuss? Ans: Java was the first programming language that could be used to send interactive programs over the World Wide Web. Since these programs run on the users system, Java requires highly restrictive security to prevent a malicious programmer from using the language to cause to happen on the systems of anyone who run programs from a web page. As we are likely aware, every time that we download a normal program, we are risking a viral infection. Prior to Java, most users did not download executable programs frequently and those who did scan them from viruses prior to execution. Even so, most users still worried about the possibility of infecting their systems with a virus. In addition to viruses, another type of malicious program exists that must be guarded against. This type of program can gather private information, such as credit card number, bank account balances, and passwords, by searching the contents of our computers local file system. Java provides Firewall between a networked application and our computer. When we use a Java-compatible web browser, we can safely download Java applets without fear of viral infection or malicious intent. Java achieves this protection by confining a java program to the Java Execution Environment and not allowing it access to the other parts of the computer. 2. How do you compile and execute a Java Program? Explain. Ans: A programming language has to be portable and also provide enough ground for security. The key factor that allows Java to solve both the security and Portability problems is that the output of a Java Compiler is not executable code. Rather, it is Byte Code. Java program into ByteCode helps it to run much easier in a wide variety of environments. 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. Although the details of the JVM will differ from platform to platform, all interpret the same Java bytecode. If a Java program should exists for each bytecode, then different versions of the same program should exist for each type of CPU connected to the internet. Thus the interpretation of bytecode is the easiest way to create truly portable programs. Working of JAVA: A compiler converts the java program into intermediate language representation called bytecode which is platform independent. A java file will have the extension .java. Let us assume that there exists a Java File name Hello.java. When this is compiled we a get a file called Hello.class. This class file is run using an interpreter as and when necessary. The following steps show the compilation and execution of java program. Step 1. Let there exist a java program Hello.java as follows: public class Hello { public static void main ( String arg[ ] ) { System.out.println(Hello! How are you?); } } Step 2: Steps for compilation and execution.

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) The program is stored in a subdirectory called java. Compilation is done in DOS prompt. c:\java>javac Hello.java c:\java>dir Volume in drive C is ACADEMIC Volume Serial Number is 4C19-52B1 Directory of C:\java 06/07/2007 12:44 AM <DIR> . 06/07/2007 12:44 AM <DIR> .. 06/07/2007 12:44 AM 159 Hello.java 06/07/2007 12:44 AM 425 Hello.class 2 File(s) 528 bytes 2 Dir(s) 6,100,964,944 bytes free. C:\java>java hello Hello! How are you? C:\java>

Command for compilation is javac filename.java and command for execution is java filename. 3. Question: Explain for loop and while loop in Java with example. Answer: Iterative statements: A loop repeatedly executes the same set of instructions until a termination condition is met. Javas iterative statements are for, while and do-while. These statements create loops. FOR LOOP: The simplest form of for loop is as follows: for(initial statement; condition; iteration expression) { Statement 1; Statement 2; Statement n; } The initial statement portion of the loop sets a loop control variable to an initial value. The condition portion is Boolean expression that tests the loop control variable. If the outcome of that condition is true, the for loop continues to iterate, otherwise the loop terminates. The iteration expression determines how the loop control variable is changed each time the loop iterates. Example: The following example illustrates the simple form of FOR loop. This program displays natural numbers from 1 to 5.

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) class Sample { public static void main( String args[ ] ) { int i; for(i =1; i<=5; i++) { System.out.println(This is i: + i); } } } Output of the program will be as follows: This This This This This is is is is is i: i: i: i: i: 1 2 3 4 5

Explanation: In the above example, i is the loop control variable. It is initialized to 1 in the initialization portion of the for loop. At the start of each iteration, including the first one, the condition test i<=5 is performed. If the outcome of the test is true, the println() statement is executed and then the iteration portion (i++) of the loop is executed. This process continues until the conditional test is false. NESTED FOR LOOP: To define a loop with in a loop is called nest loop. Syntax of nested loop is as follows: for(initial statement; condition; iteration expression) { Statements; for(initial statement; condition; iteration expression) { Statement 1; Statement 2; Statement n; } Statement n; } Example: class Nested { public static void main( String args[ ] ) { int i,j; for(i =1; i<=4; i++) { for(j = 1; j<=i; j++) System.out.print(j);

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) } System.out.println(); } } The output of this program will be as follows: 1 12 123 1234

First of all value of i is set to 1. The test i < 4 gives true. Now the inner loop will start execution and value of j is set to 1. The test j < i (1 < = 1) gives true. The first row in the output will be printed as 1 Now value of j will be changed by 1, now the test (2 < 1) gives false. The inner loop will terminate here. Now value of i is incremented by 1. Again test (2 < =4 ) gives true. The inner loop will execute twice and print second row in output i.e. 12 The steps will be applied for rest 2 rows. WHILE LOOP: While loop repeats a statement or block while its controlling expression is true. Here is its general form: while(condition) { // Body of loop } The condition can be boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. Example: Following program is to get of first 10 natural numbers. (1+2+310) class sum { public static void main(String args[]) { int I = 1; while (I <= 10) { S = S+I; I++; } System.out.println(Sum = , + S); } } 4. Question: Define an array? Discuss one dimensional array. Ans: An array in Java represents a number of variables which occupy contiguous spaces in the memory. Each element in the array is distinguished by its spaces in the memory. Each element in the array is distinguished by its index. All elements in an array must be of the same data type. For example, we cannot have one element with int data type and another belonging to the Boolean data type in the

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1)

same array. An array is a collection of elements of the same type that are referenced by a common name. Each element of an array can be referred to by an array name and a subscript or index. To create and use an array in Java, you need to first declare the array and then initialize it. One-dimensional arrays: One-dimensional arrays: A one-dimensional array is a list of like-typed variables. The general form of a one dimensional array declaration is: type var-name[ ]; Here, type declares the base type of the array and determines the data type of each element that makes the array. Hence the base type determines the type of data the array will hold. For example, int numbers[ ]; declares an array named numbers with type array of int. This declaration says the numbers is an array variable but no array actually exist because the value of numbers is set to null, which represents an array with no value. To link numbers with an actual physical array of integers, we must allocate one using new and assign it to numbers. Here new is used to allocate memory for arrays. The general form of new as it applies to one-array-var = new type [size]; for example: numbers = new int[10]; allocates a 10 element array of integers and links them to numbers. In java all arrays are dynamically allocated. 5. Question: Discuss the different types of relationships. Ans: Types of relationship: Relationships are classified as follows: A Kind-Of relationship: A truck is a kind of an automobile. A Is-A relationship: A ford is a car. A Part-Of relationship: An engine is a part of an automobile. A Has- A relationship: An automobile has an engine. A Kind-Of Relationship: Taking the example of a human being and an elephant, both are Kind-Of mammals. As human beings and elephants are kind-of mammals, they share the attributes and behaviors of mammals. Human being and elephants are subsets of the mammal class. The following figure depicts the relationship between the Mammals and Human Being classes.
A Kind-Of

Human Being

Mammals

Is-A Relationship: Lets take an instance of the human being class peter, who is-a human being and therefore a mammal. The following figure depicts the is-a relationship.
Is-A

Peter

Human Being
Is-A

A Kind-Of

Mammals

Has-A

Human Being

Part-Of

Heart

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) 6. Question: What is Exception? What are the different types of Exceptions? Ans: What Is an Exception? The term exception is shorthand for the phrase "exceptional event."

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. The call stack. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates. Searching the call stack for the exception handler.

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1)

Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:

A try statement that catches the exception. The try must provide a handler for the exception, as described in Catching and Handling Exceptions. A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

The Three Kinds of Exceptions The first kind of exception is the checked exception. These are exceptional conditions that a wellwritten application should anticipate and recover from. Example Suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name. The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Example Suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem but it also might make sense for the program to print a stack trace and exit. Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses. The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. Example consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur. Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses. Errors and runtime exceptions are collectively known as unchecked exceptions. Question 7: Write a note on Random Access Files. Ans: RANDOM ACCESS FILE Random access files permit non-sequential, or random, access to a file's contents. To access a file randomly, we open the file, seek a particular location, and read from or write to that file.

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) The RandomAccessFile class in the Java IO API allows you to move around a file and read from it or write to it as you please. You can replace existing parts of a file too. This is not possible with the FileInputStream or FileOutputStream. Creating a RandomAccessFile Before you can work with the RandomAccessFile class you must instantiate it. Here is how that looks: RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw); Notice the second input parameter to the constructor: "rw". This is the mode you want to open file in. "rw" means read/write mode. Check the JavaDoc for more details about what modes you can open a RandomAccessFile in.

Moving Around a RandomAccessFile To read or write at a specific location in a RandomAccessFile you must first position the file pointer at the location to read or write. This is done using the seek() method. The current position of the file pointer can be obtained by calling the getFilePointer() method. Here is a simple example: RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw); file.seek(200); long pointer = file.getFilePointer(); file.close(); Reading from a RandomAccessFile Reading from a RandomAccessFile is done using one of its many read() methods. Here is a simple example: RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw); int aByte = file.read(); file.close(); The read() method reads the byte located a the position in the file currently pointed to by the file pointer in the RandomAccessFile instance. The read() method increments the file pointer to point to the next byte in the file after the byte just read! This means that you can continue to call read() without having to manually move the file pointer. Writing to a RandomAccessFile Writing to a RandomAccessFile can be done using one it its many write() methods. Here is a simple example: RandomAccessFile file = new RandomAccessFile("c:\\data\\file.txt", "rw); file.write("Hello World".getBytes()); file.close(); Just like with the read() method the write() method advances the file pointer after being called. That way you don't have to constantly move the file pointer to write data to a new location in the file.

Master of Science in Information Technology (MScIT-N2-1) - Semester 1 MIT103 Object Oriented Programming (Assignment set -1) RandomAccessFile Exception Handling A RandomAccessFile must be closed properly after use, just like with a stream or reader / writer. Using a Random Access File: try { File f = new File("filename"); RandomAccessFile raf = new RandomAccessFile(f, "rw"); // Read a character char ch = raf.readChar(); // Seek to end of file raf.seek(f.length()); // Append to the end raf.writeChars("aString"); raf.close(); } catch (IOException e) { }

Das könnte Ihnen auch gefallen