Anda di halaman 1dari 23

Course Code Course Titlle Assignment Number Assignment Marks Maximum Marks Last Date of Submission

: : : : : :

MCS-024 Object Oriented Technologies and Java Programming MCA (1)/024/Assign/2010 100 25% 15th October, 2010 (for July, 2010 session) 15th April, 2011 (for January, 2011 session)

There are eight questions in this assignment which carries 80 marks. Rest of 20 marks are for viva-voce. Answer all the questions. Also in your programs give appropriate comments to increase understandability. Please go through the guidelines regarding assignments given in the Program Guide for the format of presentation.

Question 1: a) What is Object Oriented Paradigm? Why Object Oriented Programming is preferred over structured programming. (5 Marks) Object-oriented programming (OOP) technique is merely a way of organizing programs, and it can be accomplished using any language. Working with a real object-oriented language and programming environment, however, enables you to take full advantage of object oriented methodology and its capabilities for creating flexible, modular programs and reusing code. Object-oriented programming (OOP) is a programming paradigm that uses "objects data structures consisting of data field and methods together with their interactions to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance.

Object Oriented Programming V/s. Structured Programming


Object-oriented programming has taken the best ideas of structured programming and has combined them with several powerful concepts that allow you to organize your programs more effectively. When programming in an object-oriented fashion, you decompose a problem into its constituent parts. Each component becomes a self-contained object that contains its own instructions and data related to that object. We still maintain a resemblance of the one entry, one exit paradigm for control structures which is at the heart of structured programming. Objects are Heart of the Object Oriented Programming Language. Task-centric vs. Data-centric Structured Programming is Task-centric. Object Oriented Programming is Data-centric. Based On Structured programming is based around data structures and subroutines. Object oriented programming shifts primary focus to the data itself. Re-usability In Structured Programming we can not reuse of code, but in Object Oriented Programming we reuse of code. Information Hiding When we have ways to reuse our code through one way or other, we are also in need of some security regarding our source code. To protect it from unauthorized access/ alteration in object oriented programming, this is called Information Hiding. Example Structured Programming supported by languages such as C. Object Oriented Supported By languages such as VB, Java.

b) What is platform independence? Explain advantages of a programming language which is platform independent. (3 Marks) Platform Independence: Platform-independence is a programs capability of moving easily from one computer system to another. Java is compiled to an intermediate form called Java byte-code or simply byte code. A Java program never really executes immediately after compilation on the host machine. Rather, this special program called the Java interpreter or Java Virtual Machine reads the byte code, translates it into the corresponding host machine instructions and then executes the machine instruction. A Java program can run on any computer system for which a JVM (Java Virtual Machine) and some library routines have been installed. The second important part which makes Java portable is the elimination of hardware architecture dependent constructs. For example, Integers are always four bytes long and floating-point variables follow the IEEE 754.You dont need to worry that the interpretation of your integer is going to change if you move from one hardware to another hardware like Pentium to a PowerPC. You can develop the Java program on any computer system and the execution of that program is possible on any other computer system loaded with JVM. For example, you can write and compile the Java program on Windows 98 and execute the compiled program on JVM of the Macintosh operating system. The same concept is explained in Figure given below.

Java programs can run on any machine and operating system that support Java Virtual Machine as we are showing following figure where we have shown that a program after compiling converts into a byte code which is able to execute on any platform Windows/Linux/Macintosh.

c) Explain why Java is platform independent.

(2 Marks)

Platform independence is one of the most significant advantages that Java has over other programming languages, particularly for systems that need to work on many different platforms. Java is platform-independent at both the source and the binary level. At the source level, Javas primitive data types have consistent sizes across all development platforms. Javas foundation class libraries make it easy to write code that can be moved from platform to platform without the need to rewrite it to work with that platform. Platform-independence doesnt stop at the source level, however. Java binary files are also platform-independent and can run on multiple platforms without the need to recompile the source. At the binary level Java binary files are actually in a form called bytecodes. Bytecodes are a set of instructions that look a lot like machine code, but are not specific to any one processor.

Question 2: a) List different data types available in java. DataType available in Java are as following: Integer DataType Byte DataType Short DataType Int DataType Long DataType Floating DataType Double DataType Char DataType Boolean DataType (2 Marks)

b) What are different bitwise operators available in Java? Write a Java program to explain the use of bitwise operators. (6 Marks)
Following are Bitwise operators.

Operator
& | ^ << >> >>> ~ <<= >>= >>>= x&=y x|=y x^=y

Use of bitwise Operators


Bitwise AND Bitwise OR Bitwise XOR Left shift Right shift Zero fill right shift Bitwise complement Left shift assignment (x = x << y) Right shift assignment (x = x >> y) Zero fill right shift assignment (x = x >>> y) AND assignment (x = x & y) OR assignment (x + x | y) XOR assignment (x = x ^ y)

c) Explain the need of Unicode.

(2 Marks)

Unicode is a computing industry standard designed to consistently and uniquely encodes characters used in written languages throughout the world. The Unicode standard uses hexadecimal to express a character. For example, the value 0x0040 represents the Latin character A. The Unicode standard was initially designed using 16 bits to encode characters because the primary machines were 16-bit PCs. When the specification for the Java language was created, the Unicode standard was accepted and the char primitive was defined as a 16-bit data type, with characters in the hexadecimal range from 0x0000 to 0xFFFF. Because 16-bit encoding supports 216, (65,536) characters, which is insufficient to define all characters in use throughout the world, the Unicode standard was extended to 0x10FFFF, which supports over one million characters. The definition of a character in the Java programming language could not be changed from 16 bits to 32 bits without causing millions of Java applications to no longer run properly. To correct the definition, a scheme was developed to handle characters that could not be encoded in 16 bits. The characters with values that are outside of the 16-bit range, and within the range from 0x10000 to 0x10FFFF, are called supplementary characters and are defined as a pair of char values.

Question 3: a) What is an array? Explain how an array of variable size is defined in Java.

(3 Marks)

An array is a structure that holds multiple values of the same type, the length of an array is established when the array is created (at runtime). After creation, an array is a fixed-length structure. When a variable of an array type is declared, the size of the array is not identified, and the array object is not allocated. To allocate storage for an array, you can use the new operator to create an array object of a specific size. The following statement: char ch[]=new char[24]; creates a char array of length 24, the individual component variables of which can be referenced by ch[0], ch[1],.,ch[23]. The following statement creates an array of type Dice[] of length 6: Dice[] d= new Dice[6]; Array can also be allocated by specifying their initial values. For example, the following allocates a String array of length 7 that contains abbreviations for the days of the week: String days[]={sun, mon, tue, wed, thu, fri, sat}; The length of an array can always be found by appending Length to the name of the array. For example, days returns the integer 7 as the length of days[]. Alternate Array Declaration Syntax Arrays are declared by declaring a variable to be of an array type. For example, the following declares nums to the array of type int: int[] nums: the declaration can also be written as follows: int nums[]; You can place the brackets after either the type of the variable name.

b) Explain why main method in Java is always static.

(2 Marks)

The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: public class JavaClass { protected JavaClass(int x) { } public void main(String[] args) { } } The keyword static indicates that the method is a class method, which can be called without the requirement to instantiate an object of the class. This is used by the Java interpreter to launch the program by invoking the main method of the class identified in the command to start the program.

c) What is a constructor? Explain the advantage of constructors overloading with an example of a Java program. (5 Marks)
Constructor A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object. It is always used with the keyword new and then the Class name. For instance, new String(); constructs a new String object. When we create an object, we typically want to initialize its member variables. The constructor is a special method we can implement in all classes. it allows to initialize variables and perform any other operations when an object is created from the class. The constructor is always given the same name as the class. A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarationsexcept that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } To create a new Bicycle object called myBike, a constructor is called by the new operator: Bicycle myBike = new Bicycle(30, 0, 8); new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields. Although Bicycle only has one constructor, it could have others, including a no-argument constructor: public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike. Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. Java platform execute the constructor according to the there Name & the Passing Arguments. This is calls an Encapsulation. This is the Main Advantage of the Constructor Overloading.

Question 4: a) What is polymorphism? Is Interfaces in Java, a kind of polymorphism? Justify your answer.

(4 Marks)

Polymorphism is one of the most important features in Java. The capability of a method to do different things based on the object through which it is invoked or object it is acting upon. Generally, polymorphism refers to the ability to appear in many forms Polymorphism in a Java program The ability of a reference variable to change behavior according to what object instance it is holding. This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass. Polymorphism can be and very often is implemented with interfaces. Interfaces differ from classes in that they don't include any implementation. You cannot extend an interface. You can only implement an interface by another class. You cannot create objects from an interface, only from classes that implement interfaces. To support polymorphism, define an interface that accepts an object of the type Object, and implement it in classes that support actual types as int, double, and user-defined classes. Interface names usually start with I, to distinguish them from classes. The following example defines the ICopyObj interface. It includes one member, Copy(), which returns a copy of the object of type Object: interface ICopyObj { function Copy() : Object; } The class CopyInt implements the ICopyObj interface for integers. It includes one property (i), and two methods. One method is the class constructor, CopyInt(). The other method is the interface method, Copy(): class CopyInt implements ICopyObj { public var i : int; public function CopyInt(i : int) { this.i = i; } public function Copy() : Object { return new CopyInt(i) } } (may be this answer is wrong)

b) Explain the need of package in Java.

(3 Marks)

we know that reusability of the most important feature of any OOP reusability means it is a ability to reuse the code which is already develop one can achieve the concept of reusability with the help of classes & interfaces but both this concepts have limitation that is we can extends class or we cannot implement the interface beyond one program java has given us a special solution to use our one class into the separate program this feature is known as package.

In other words we can say package is a container of the classes here in this container we can group the classes related to each other by making a single package mainly there are two types of packages. 1. Java API Packages

c) What is rule of accessibility? Explain different level of accessibility in Java.

(3 Marks)

The rules of accessibility are governed by the access modifiers. An Access Modifier is a key word in java that determines what level of access or visibility a particular java variable/method or class has. There are 4 basic access modifiers in java. They are: 1. 2. 3. 4. Public Private Protected and Default

Public Access Modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. Private Access Modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. Protected Access Modifier The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class. Default Access Modifier Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

Question 5: a) What is an exception? Explain haw an exception is handled in Java. Also explain hierarchy of different exception classes in Java. (5 Marks) An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. An exceptional condition is considered as a problem, which stops program execution from continuation from the point of occurrence of it. Exception stops you from continuing because of lack of information to deal with the exception condition. In other words it is not known what to do in specific conditions. Exception Handling: An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions: Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of Memory. Normally programs cannot recover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class.

b) Write a java program to find whether a given string is a palindrome or not. import java.io.*;

(5 Marks)

public class Palindrome { public static void main(String [] args){ try{ BufferedReader object = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter number"); int num= Integer.parseInt(object.readLine()); int n = num; int rev=0; System.out.println("Number: "); System.out.println(" "+ num); for (int i=0; i<=num; i++){ int r=num%10; num=num/10; rev=rev*10+r; i=0; } System.out.println("After reversing the number: "+ " "); System.out.println(" "+ rev); if(n == rev){ System.out.print("Number is palindrome!"); } else{ System.out.println("Number is not palindrome!"); } } catch(Exception e){ System.out.println("Out of range!"); } } }

Question 6: a) What is multithreading? Explain advantages of multithreaded programming with the help of a Java program. (5 Marks) Multithreading is a technique in which a process executing an application is divided into threads that can run concurrently. The advantages of multithreading are: i. Concurrency can be used within a process to implement multiple instances of simultaneous services. Multithreading requires less processing overhead than multiprogramming because concurrent threads are able to share common resources more efficiently. A multithreaded web server is one of the examples of multithreaded programming. Multithreaded web servers are able to efficiently handle multiple browser requests. They handle one request per processing thread. ii. Multithreading enables programmers to write very efficient programs that make maximum use of the CPU. Unlike most other programming languages, Java provides built-in support for multithreaded programming. The Java run-time system depends on threads for many things. Java uses threads to enable the entire environment to be synchronous. Example of The MultiThreading class A extendsThread { public void run() { for(int i=1;i<=5;i++) { System.out.println(From Thread A-i=+i); } System.out.println(Exit From Thread A); } } class B extendsThread { public void run() { for(int i=1;i<=5;i++) { System.out.println(From Thread B-i=+i); } System.out.println(Exit From Thread B); } } class C extendsThread { public void run() { for(int i=1;i<=5;i++) { System.out.println(From Thread C-i=+i); } System.out.println(Exit From Thread C); } } Class test {

public static void main(String arg[]) { new A().start(); new B().start(); new C().start(); } }

b) What is I/O stream in Java? Write a program in Java to create a file and copy the content of an already existing file into it. (5 Marks) Java input and output is based on the use of streams, or sequences of bytes that travel from a source to a destination over a communication path. If a program is writing to a stream, you can consider it as a streams source. If it is reading from a stream, it is the streams destination. The communication path is dependent on the type of I/O being performed. It can consist of memory-to-memory transfers, a file system, a network, and other forms of I/O. Streams are powerful because they abstract away the details of the communication path from input and output operations. This allows all I/O to be performed using a common set of methods. These methods can be extended to provide higher-level custom I/O capabilities. Three streams given below are created automatically: System.out - standard output stream System.in - standard input stream System.err - standard error An InputStream represents a stream of data from which data can be read. Again, this stream will be either directly connected to a device or else to another stream. An OutputStream represents a stream to which data can be written. Typically, this stream will either be directly connected to a device, such as a file or a network connection, or to another output stream. Program import java.io.*; public class CopyFile{ private static void copyfile(String srFile, String dtFile){ try{ File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); // //For Append the file. OutputStream out = new FileOutputStream(f2,true); //For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); }

catch(IOException e){ System.out.println(e.getMessage()); } } public static void main(String[] args){ switch(args.length){ case 0: System.out.println("File has not mentioned."); System.exit(0); case 1: System.out.println("Destination file has not mentioned."); System.exit(0); case 2: copyfile(args[0],args[1]); System.exit(0); default : System.out.println("Multiple files are not allow."); System.exit(0); } } }

Question 7: a) How a Java Applet is different from Java Application program? Create an Applet program to display your Bio-Data. Make necessary assumptions and use appropriate layout in your program. (6 Marks) Differences between Java applets and application programs Java Application Programs Java Application Program can be executed independently. Applications are executed at command line by Java.exe It contain main () method. It has a single point for entry to execution Applications have no inherent security restrictions, and can perform read/write to files in local System. Applications have no special support in HTML for embedding or downloading Program: import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code=program12 width=500 height=500></applet>*/ public class program12 extends Applet { public void init() { setLayout(new flowLayout(flowLayout.LEFT,5,5); add(new Label(Name : ABC XYZ\n)); add(new Label(Address : 1,Subhash Nagar, \n)); add(new Label( Rajkot-360 002. \n)); add(new Label(Std : MCA-2nd Sem.\n)); add(new Label(Phone : 8866178920\n)); add(new Label(City : Rajkot.\n)); } } Java Applets Applet cannot be executed independently. Applets can only be executed inside a Java compatible container, such as a browser or appletviewer. It does not contain main () method, and does not have a single point of entry for execution. Applets cannot perform read/write to files in local system This is to provide security. Applets can be embedded in HTML pages and downloaded over the Internet

b) What is need of Layout Manager? Explain different layouts available in Java.

(4 Marks)

The actual appearance of the AWT components on the screen is determined by two things: the order in which they are added to the panel that holds them and the layout manager that panel is currently using to lay out the screen. The layout manager determines how portions of the screen will be sectioned and how components within that panel will be placed. Following are different layout available in java FlowLayout BorderLayout CardLayout GridLayout GridBagLayout

FlowLayout This is the default LayoutManager for applets and panels. FlowLayout is the default layout for java.awt.Panel of which java.applet.Applet is subclasses. A FlowLayout arranges widgets from left to right until there's no more space left. Then it begins a row lower and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. BorderLayout A BorderLayout organizes an applet into North, South, East, West and Centre sections. North, South, East and West are the rectangular edges of the applet. They're continually resized to fit the sizes of the widgets included in them. Centre is whatever is left over in the middle. CardLayout A CardLayout breaks the applet into a deck of cards, each of which has its own Layout Manager. Only one card appears on the screen at a time. The user flips between cards, each of which shows a different set of components. The common analogy is with HyperCard on the Mac and Tool book on Windows. In Java this might be used for a series of data input screens, where more input is needed than will comfortably fit on a single screen. GridLayout A GridLayout divides an applet into a specified number of rows and columns, which form a grid of cells, each equally sized and spaced. It is important to note that each is equally sized and spaced as there is another similar named Layout known as GridBagLayout .As Components are added to the layout they are placed in the cells, starting at the upper left hand corner and moving to the right and down the page. Each component is sized to fit into its cell. This tends to squeeze and stretch components unnecessarily. GridBagLayout GridBagLayout is the most precise of the five AWT Layout Managers. It is similar to the GridLayout, but components do not need to be of the same size. Each component can occupy one or more cells of the layout. Furthermore, components are not necessarily placed in the cells beginning at the upper left-hand corner and moving to the right and down.

Question 8: a) What is a socket? Explain how a network socket is created using Java. Socket

(5 Marks)

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes-Socket and ServerSocket that implement the client side of the connection and the server side of the connection, respectively. Clients and servers establish connections and communicate via sockets. Connections are communication links that are created over the Internet using TCP. Some client/server applications are also built around the connectionless UDP. These applications also use sockets to communicate. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets. Socket echoSocket = null; echoSocket = new Socket("taranis", 7); The Above statement in this sequence creates a new Socket object and names it echoSocket. The Socket constructor used here requires the name of the machine and the port number to which you want to connect.

b) Explain the need of JDBC? Explain steps involved in connecting a databases using JDBC.

(5 Marks)

Need Of JDBC The JDBC API will allow you to user SQL language command directly from the Java. You can also use the JDBC API from SERVLET or JSP to access your database. You can use the JDBC API in EJB when you over write the default container or the bean they can access the database. Connecting a Database Using JDBC Using DriverManager: 1. Load the driver class using class.forName(driverclass) and class.forName() loads the driver class and passes the control to DriverManager class 2.DriverManager.getConnection() creates the connection to the database Using DataSource: DataSource is used instead of DriverManager in Distributed Environment with the help of JNDI. 1. Use JNDI to lookup the DataSource from Naming service server. 2. DataSource.getConnection method will return Connection object to the database.

Anda mungkin juga menyukai