Anda di halaman 1dari 13

BCA 4th Semester Reg. No.

521111721

Java Programming BC0047

1. How is Java different than any other OOP language like C++? Explain. Ans: The syntax of Java is similar to C++. Unlike C++, in which the programmer handles memory manipulation, Java handles the required memory manipulations, and thus prevents errors that arise due to improper memory usage. Java defines data as objects with methods that support the objects. Java is purely object-oriented and provides abstraction, encapsulation, inheritance and polymorphism. Even the most basic program has a class. Any code that you write in Java is inside a class. Java is different than other OOP languages like C++ for following few reasons: Simple: Java was designed to be easy for the professional programmer to learn and use effectively. Assuming that you have some programming experience, you will not find Java hard to master. If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java. Also, some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. Beyond its similarities with C/C++, Java has another attribute that makes it easy to learn: it makes an effort not to have surprising features. In Java, there are a small number of clearly defined ways to accomplish a given task. Object-Oriented: Although influenced by its predecessors, Java was not designed to be source-code Compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purist's "everything is an object" paradigm and the pragmatist's "stay out of my way" model. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high performance non objects. Robust: The multi platformed environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key areas, to force you to find your mistakes early in program development. At the same time, Java frees you from having to worry about many of the most common causes of programming errors. Because Java is a strictly typed language, it checks your code at compile time. For example, in C/C++, the programmer must manually allocate and free all dynamic memory. This sometimes leads to problems, because programmers will either forget to free memory that has been previously allocated or, worse, try to free some memory that another part of their code is still using. Java virtually eliminates these problems by managing memory allocation and deallocation for you. (In fact, deallocation is completely automatic, because Java provides garbage collection for unused objects.) Multithreaded: Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an
Page 1 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems. Java's easyto-use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem. Architecture-Neutral: A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was "write once; run anywhere, any time, forever." To a great extent, this goal was accomplished. Interpreted and High Performance: Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. Most previous attempts at crossplatform solutions have done so at the expense of performance. Other interpreted systems, such as BASIC, Tcl, and PERL, suffer from almost insurmountable performance deficits. Java, however, was designed to perform well on very low-power CPUs. Distributed: Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intra-addressspace messaging. This allowed objects on two different computers to execute procedures remotely. Java has recently revived these interfaces in a package called Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to client/server programming. Dynamic: Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of bytecode may be dynamically updated on a running system. Secure: Java is considered more secure than other languages for several reasons: The Java compiler catches more compile-time errors; other languages (like C++) will compile programs that produce unpredictable results. Java does not allocate direct pointers to memory. This makes it impossible to accidentally reference memory that belongs to other programs or the kernel.

========================================================================

Page 2 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

2. Write a program in Java to find the highest of any five numbers. How do you compile and execute this Java program? Ans: import javax.swing.JOptionPane; public class a3c4e23 { public static void main (String args[]) { int counter = 0; int number; int largest = 0; int second = 0; while (counter<10) { counter++; number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer")); if (number >= largest) largest=number; else if (number >= second && number <= largest) second=number; } System.out.println("Largest number input: " + largest); } }

========================================================================

Page 3 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

3. Write a simple Java program to illustrate the use of for loop statement. Ans: for Loop: The usage of for loop is as follows for (initial statement; termination condition; increment instruction) statement; When multiple statements are to be included in the for loop, the statements are included inside flower braces. for (initial statement; termination condition; increment instruction) { statement1; statement2; } The example below prints numbers from 1 to 10

The results of the above program is shown below

Page 4 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops: // Loops may be nested. class Nested { public static void main(String args[ ]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } } The output produced by this program is shown here: .......... ......... ........ ....... ...... .....

========================================================================

Page 5 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

4. What do you mean by an array? Explain with an example. Ans: Arrays: An array represents a number of variables which occupy contiguous 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. In other words an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. For example, you cannot have one element of the int data type and another belonging to the boolean data type in the 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. An array is a sequence of variables of the same data type (homogenous). The data type can be any of Javas primitive types or a class (user-defined as well). Each variable in the array is an element. We use an index to specify the position of each element in the array. Arrays are useful for many applications, including calculating statistics or representing the state of a game. Arrays are always homogeneous, or of the same data type. Array indexes always begin with zero (0). Examples: int[] array; int[] array = new int[9]; int[] array = {1,2,3,4,5}; Auto[] array = {new Auto()}; Declaration of an array: In Java Arrays are objects, so they need to be declared and instantiated. Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type. data type [ ] variablename; Example int [ ] numbers; The above statement will declare a variable that can hold an array of the int type variables. After declaring the variable for the array, the array needs to be allocated in memory. This can be done using the new operator in the following way:
Page 6 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

numbers = new int [10]; This statement assigns ten contiguous memory locations of the type int to the variable numbers. The array can store ten elements. Iteration can be used to access all the elements of the array, one by one. Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as: int num[] = {50,20,45,82,25,63}; In this program we will see how to declare and implementation. This program illustrates that the array working way. This program takes the numbers present in the num[] array in unordered list and prints numbers in ascending order. In this program the sort() function of the java.util.*; package is using to sort all the numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending order by default. This function held the argument which is the array name num.

Fig: An array of ten elements Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. Accessing Array Elements: Placing an integer-valued expression inside square brackets can access an array element, where the brackets are proceeded by the name of the array. Copying Arrays: The system class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

Page 7 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

Changing an Arrays Size in Array: An arrays length is a fixed length; to grow an array size you need to create a new array of the required size, and copy the existing elements in the old array to the new array, and fill in the rest with your new values. Two ways to make a copy of an array: 1. Use loops (for, while, etc) to copy individual elements // Create the original array int[] originalArray = { 1,5, 14, 33 }; // Define 2nd array int[] arrayCopy = new int[originalArray.length]; // Copy individual elements for (int element = 0; element < originalArray.length; element++) { arrayCopy[element] = originalArray[element]; } 2. Use System.arraycopy() method int[] originalArray = { 7, 4, 5, 2 }; int[]arrayCopy = new int[originalArray.length]; // Copy using arrayCopy() System.arraycopy(originalArray, // Source array 0, // Source array position arrayCopy, // Target array 0, // Target array position originalArray.length); Advantages of Java Array: An array can hold primitive types data. An array has its size that is known as array length. An array knows only its type that it contains. Array type is checked at the compile-time. Disadvantages of Java Array: An array has fixed size. An array holds only one type of data (including primitive types).

Page 8 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

========================================================================

Page 9 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

5. Write a program to explain the Exception Handling mechanisms in Java using the keywords: try, catch and finally. Ans: The error or exception handling mechanisms in Java enables programmers to write more robust and secure codes. Java enforces the programmers to specify the exceptions that might occur while executing a method. When an unexpected error occurs in a method, Java creates an object of the appropriate exception class. After creating the exception objects, Java passes it to the program, by an action called throwing an exception. The exception object contains information about the type of error and the state of the program when the exception occurred. You need to handle the exception using exception-handler and process the exception. We can implement exception-handling in a program by using following keywords: try catch finally The try Block: You need to guard the statements that may throw an exception in the try block. The following skeletal code illustrates the use of the try block try { // statement that may cause an exception } The try block governs the statements that are enclosed within it and defines the scope of the exception handlers associated with it. In other words, if an exception occurs within try block, the appropriate exception-handler that is associated with the try block handles the exception. A try block must have at least one catch block that follow it immediately. The catch Block: You associate an exception-handler with the try block by providing one or more catch handlers immediately after try block. The following skeletal code illustrates the use of the catch block. try { //statements that may cause an exception } catch () { // error handling code }

Page 10 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

The catch statement takes an object of an exception class as a parameter. If an exception is thrown, the statements in the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only. The finally Block: When an exception is raised, the rest of the statements in the try block are ignored. Sometimes, it is necessary to process certain statements irrespective of whether an exception is raised or not. The finally block is used for this purpose. try { openFile(); writeFile(); //may cause an exception } catch () { //process the exception } In the above example, the file has to be closed irrespective of whether an exception is raised or not. You can place the code to close the file in both the try and catch blocks. To avoid duplication of code, you can place the code in the finally block. The code in the finally block is executed regardless of whether an exception is thrown or not. The finally block follows the catch blocks. You have only one finally block for an exception-handler. However, it is not mandatory to have a finally block. finally { closeFile ();
}

===============================================================================

Page 11 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

6. Define (i) Inheritance (ii) Package and (iii) Interface. Ans: (i) Inheritance: Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements. 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. (ii) Package: To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. (This is why you haven't had to worry about packages before now.) While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, you will define a package for your code. This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most real-world packages are spread across many files. You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here:
Page 12 of 13

BCA 4th Semester Reg. No. 521111721

Java Programming BC0047

package pkg1 [.pkg2 [.pkg3]]; A package hierarchy must be reflected in the file system of your Java development system. For example, a package declared as package java.awt.image; needs to be stored in java/awt/image, java\\awt\\image, or java:awt:image on your UNIX, Windows, or Macintosh file system, respectively. Be sure to choose your package names carefully. You cannot rename a package without renaming the directory in which the classes are stored. (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. Interfaces add most of the functionality that is required for many applications which would normally resort to using multiple inheritance in a language such as C++. Defining an Interface An interface is defined much like a class. This is the general form of an interface: access interface name { return-type method-name1 (parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; return-type method-nameN (parameter-list); type final-varnameN = value; } Here, access is either public or not used. When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it is declared as public, the interface can be used by any other code. name is the name of the interface, and can be any valid identifier. Notice that the methods which are declared have no bodies. They end with a semicolon after the parameter list. They are, essentially, abstract methods; there can be no default implementation of any method specified within an interface. Each class that includes an interface must implement all of the methods. Variables can be declared inside of interface declarations. They are implicitly final and static, meaning they cannot be changed by the implementing class. They must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public. ========================================================================
Page 13 of 13