MCS-024 1.(a) What is Object Oriented Programming? Explain features of Object Oriented Programming . Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data. Features of Object Oriented Programming Class and object A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog would consist of traits shared by all dogs. A class is collection of the properties and methods are called members. Object is an instance of class. Data abstraction: - it is a process that provides only essential features by hiding its background details. A data abstraction is a simple view of an object that includes required features and hides the unnecessary details. Data encapsulation:- it is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. Inheritance: it is a process to create a new class from existing class or classes. Class ‘B’ is a sub class that is derived from class ‘A’. Thus class ‘A’ is a parent class and class ‘B’ is a child class. It provides reusability of code. Polymorphism: - Generally, it is the ability to appear in different forms. In oops concept, it is the ability to process objects differently depending on their data types. It’s the ability to redefine methods for derived classes. 1|Page (b) What is platform independence? Explain why java is platform independent. Platform independence is a term that describes a technology (usually a Programming Language or a FrameWork) that you can use to implement things on one machine and use them on another machine without (or with minimal) changes. java is a platform independent language becoz of the bytecode magic of java. In java, when we execute the source code...it generates the .class file comprising the bytecodes. Bytecodes are easily interpreted by JVM which is available with every type of OS we install. Whereas C and C++ are complied languages which makes them platform dependent. The source code written in C / C++ gets transformed into an object code which is machine and OS dependent. That's the reason why C and C++ languages are termed as Platform Dependent. (c) Write a program to explain how array of objects may be created in java. class myarray { void disp(int a) { System.out.println("\n my number="+a); } } class callme { public static void main(String arg[]) { myarray ob[] =new myarray[5]; for(int i=0;i<=4;i++) 2|Page { ob[i]=new myarray(); ob[i].disp(i); } } } 2.(a) Write a java program to demonstrate use of different data types available in java. public class data { public static void main(String arg[]) { byte b =103; short s =13; int v = 123443; int calc = -3872245; long amount = 1234444441; float Rate = 12.25f; double sineVal = 12345.234d; boolean flag = true; boolean val = false; char ch1 = 65; // code for X char ch2 = 'Y'; System.out.println("byte Value = "+ b); System.out.println("short Value = "+ s); System.out.println("int Value = "+ v); System.out.println("int second Value = "+ calc); System.out.println("long Value = "+ amount); 3|Page System.out.println("float Value = "+ Rate); System.out.println("double Value = "+ sineVal); System.out.println("boolean Value = "+ flag); System.out.println("boolean Value = "+ val); System.out.println("char Value = "+ ch1); System.out.println("char Value = "+ ch2); } } (b) Explain followings in context of java, with the help of examples. (i) Class and objects-A class is a blueprint that describes characteristics and functions of entity.. For example, the class Dog would consist of traits shared by all dogs. A class is collection of the properties and methods are called members. Object is an instance of class. ii) Abstraction and encapsulation-it is a process that provides only essential features by hiding its background details. A data abstraction is a simple view of an object that includes required features and hides the unnecessary details. it is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. (iii) Application program and applet programJava Application: A java application is a stand-alone program. This means it can be run by itself. It cannot access from web browser. It is run by JVM. It can access on local machine on which program is reside. Applet Applet cannot run as independent program. Applet program can run from within a web browser or similar java enabled application such as an applet viewer Java applets are included in HTML pages using <applet> tag. Applet communicates with server only. Applets are not allowed to read or write to files on the local system. 3.(a) What is static variable and static method? Explain why main method in java is always static. When a variable is declared with the keyword “static”, its called a “class variable”. All instances share the same copy of the variable. A class 4|Page variable can be accessed directly with the class, without the need to create a instance. Static Method: It is a method which belongs to the class and not to the object(instance) A static method can access only static data. It can not access non-static data (instance variables) A static method can call only other static methods and can not call a non-static method from it. A static method can be accessed directly by the class name and doesn’t need any object Syntax : <class-name>.<method-name> A static method cannot refer to “this” or “super” keywords in anyway Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined. If we omit statickeyword before main Java program will successfully compile but it won't execute. (b) What is inheritance? Explain the advantage of inheritance with an example program. What are different types of inheritance supported by java? Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related 5|Page classes, the hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to result in a better organization of code and smaller, simpler compilation units. Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably Advantages of Inheritence Reusability -- facility to use public methods of base class without rewriting the same Extensibility -- extending the base class logic as per business logic of the derived class Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class. Below are Various types of inheritance in Java. Single Inheritance Multiple Inheritance Multilevel Inheritance 6|Page Hierarchical Inheritance Hybrid Inheritance (c) Explain the steps involved in creating a distributed application using Remote Method Invocation (RMI). Using RMI to develop a distributed application involves the following general steps: 7|Page 1. Designing and implementing the components of the distributed application. 2. Compiling sources. 3. Making classes network accessible. 4. Starting the application. 4.(a) What is polymorphism? Is Interfaces in Java, a kind of polymorphism? Justify your answer with the help of an example. Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. No. Interfaces in Java are a construct to get polymorphism ( subtype polymorphism ) working in Java, but they are not a "kind" of polymorphism. In polymorphism happens when two objects respond to the same message ( method call ) in different way ( hence poly -> many, morphism -> way or shape : polymorphism -> many ways). In Java to be able to send the same message to two different objects you have to either inherit the same parent, or implement the same interface. (b) Explain the need of package in Java. Write a java program to show how package is created. Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub packages. Many implementations of Java use a hierarchical file system to manage source and class files. It is easy to organize class files into packages. All we need to do is put related class files in the same directory, give the directory a name that relates to the purpose of the classes, and add a line to the top of each class file that declares the package name, which is the same as the directory name where they reside. In java there are already many predefined packages that we use while programming. 8|Page For example: java.lang, java.io, java.util etc. However one of the most useful feature of java is that we can define our own packages Need of Package: . • Reusability: Reusability of code is one of the most important requirements in the software industry. Reusability saves time, effort and also ensures consistency. A class once developed can be reused by any number of programs wishing to incorporate the class in that particular program. • Easy to locate the files. • In real life situation there may arise scenarios where we need to define files of the same name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collision Defining a Package: This statement should be used in the beginning of the program to include that program in that particular package. package <package name>; Example: package tools; public class Hammer { public void id () { System.out.println ("Hammer"); } } (c) What is rule of accessibility? Explain different level of accessibility in java. Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control: • At the top level—public, or package-private (no explicit modifier). • At the member level—public, private, protected, or package-private (no explicit modifier). 9|Page A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.) At the member level, you can also use the public modifier or no modifier (package-private) just as with toplevel classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package. The following table shows the access to members permitted by each modifier. Access Levels Class Package Subclass World Y Y Y Y Modifier public protected Y no modifier Y private Y Y Y N Y N N N N N The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member. Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have. 5.(a) What is abstract class? Explain need of abstract class with the help of an example. Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method. Suppose we were modeling the behavior of animals, by creating a class hierachy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an 10 | P a g e abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking). public abstract Animal { public void eat(Food food) { // do something with food.... } public void sleep(int hours) { try { // 1000 milliseconds * 60 seconds * 60 minutes * hours Thread.sleep ( 1000 * 60 * 60 * hours); } catch (InterruptedException ie) { /* ignore */ } } public abstract void makeNoise(); } Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class. public Dog extends Animal { public void makeNoise() { System.out.println ("Bark! Bark!"); } } public Cow extends Animal { public void makeNoise() { System.out.println ("Moo! Moo!"); } } (b) What is an exception? Explain haw an exception is handled in Java. Explain hierarchy of different exception classes in java. Also explain why is it not necessary to handle runtime exception? 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. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: 11 | P a g e try { //Protected code }catch(ExceptionName e1) { //Catch block } The code which is prone to exceptions is placed in the try block, when an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a class block or finally block. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method paramet Hierarchy of Java Exception classes RuntimeExceptions are rare errors that could be prevented by fixing your code in the first place. For example, dividing a number by 0 will generate a run time exception, ArithmeticException. But rather than catching the error, you could modify your program to check the arguments for division function and make sure that the denominator > 0. (c) Write a java program to create two threads with different priority. class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name){ 12 | P a g e threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } } 13 | P a g e 6.(a) 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. Ans: The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc. A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic functionality related to streams and I/O. import java.io.*; class myfile { public static void main(String arg[]) throws IOException { FileInputStream in=new FileInputStream(arg[0]); System.out.print(byte ibuf[]=new byte[x]; int r=in.read(ibuf,0,x); if(r!=1) System.out.print(“File is empty”); else System.out.print(new String(ibuf)); System.out.print(“Size of File is=”+x); String s= new String(ibuf); FileOutputStream ot=new FileOutputStream(arg[1]); for(int i=0;i<s.length();i++) ot.write(s.charAt(i)); System.out.print(“File is Copied”); ot.close(); in.close(); }} 14 | P a g e (b) Create an Applet program to display your brief profile with your photograph. Make necessary assumptions and use appropriate layout in your program. import java.applet.*; import java.awt.*; public class pix extends Applet{ Image img; MediaTracker tr; public void paint(Graphics g) { tr = new MediaTracker(this); img = getImage(getCodeBase(), "demoimg.gif"); tr.addImage(img,0); g.drawImage(img, 0, 0, this); g.drawString("Name:Ashok Kumar",100,200); g.drawString("DOB:12/jun/1985",120,200); g.drawString("Address: Delhi",130,200); g.drawString("Qly: BCA 4th Sem",140,200); } } (c) Differentiate between String and StringBuffer classes. Also write a program to find the length of a given string. No. 1) String String class is immutable. StringBuffer StringBuffer class is mutable. 2) String is slow and consumes more StringBuffer is fast and memory when you concat too many consumes less memory strings because every time it creates when you cancat strings. new instance. 15 | P a g e 3) String class overrides the equals() StringBuffer class doesn't method of Object class. So you can override the equals() compare the contents of two strings method of Object class. by equals() method. Program to find length of a given String: public class StringLengthExample { public static void main(String[] args) { //declare the String object String str = "Hello World"; //length() method of String returns the length of a String. int length = str.length(); System.out.println("Length of a String is : " + length); } } 7.(a) What is need of layout manager? Explain different layouts available in java for GUI programming. The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers: 1. java.awt.BorderLayout 2. java.awt.FlowLayout 3. java.awt.GridLayout 4. java.awt.CardLayout 5. java.awt.GridBagLayout 6. javax.swing.BoxLayout 7. javax.swing.GroupLayout 8. javax.swing.ScrollPaneLayout 9. javax.swing.SpringLayout etc. FlowLayout 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. This is the default LayoutManager for applets and panels. FlowLayout fl = new FlowLayout(); 16 | P a g e BorderLayout A BorderLayout organizes an applet into North, South, East, West, and Center sections. North, South, East, and West are the rectangular edges of the applet. They' are continually resized to fit the sizes of the widgets included in them. A BorderLayout places objects in the North, South, East, West, and Center of an applet this.setLayout(new BorderLayout()) Grid Layout 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 similarly named Layout known as GridBagLayout. As Components are added to the layout, they are placed in the cells, CardLayout A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. Grid bag layout:- it is similar to grid layout in which elements are arragned in row and colums but it allows to insert a component in span of two cells. 17 | P a g e (b) What is a TCP/IP socket? Write a java program to create socket. Java programs communicate through programming abstraction called a socket. A socket represents the endpoint of a network communication. Sockets provide a simple read/write interface and hide the implementation details network and transport layer protocols. It is used to indicate one of the client wishes to make connection to a server, it will create a socket at its end of the communication link.. import java.net.*; import java.io.*; public class Client { public static void main(String args[]) throws UnknownHostException,IOException { int port=4455; String servername="server"; Socket ss=new Socket(servername,port); while(!done) { //Communication with Server } ss.close(); } } (c) Explain the need of JDBC? Explain steps involved in connecting a databases using JDBC. Java Database Connectivity (JDBC) is an application program interface (API) specification for connecting programs written in Java to the data in popular databases. The application program interface lets you encode access 18 | P a g e request statements in Structured Query Language (SQL) that are then passed to the program that manages the database. It returns the results through a similar interface. JDBC is very similar to the SQL Access Group's Open Database Connectivity (ODBC) and, with a small "bridge" program, you can use the JDBC interface to access databases through the ODBC interface. For example, you could write a program designed to access many popular database products on a number of operating system platforms. When accessing a database on a PC running Microsoft's Windows 2000 and, for example, a Microsoft Access database, your program with JDBC statements would be able to access the Microsoft Access database. The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps − Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code. Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests. Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect. Create Connection Object: Finally, code a call to the DriverManager object'sgetConnection( ) method to establish actual database connection. 8. (a) Explain basic networking features of java. Ans: Java provides the programmer with an extensive set of core classes and interfaces to handle a wide range of network protocols. Java has classes that range from low level TCP/IP connections to ones that provide instant access to resources on the World Wide Web. Sockets:- Java programs communicate through programming abstraction called a socket. A socket represents the endpoint of a network communication. Sockets provide a simple read/write interface and hide the implementation details network and transport layer protocols. It is used to indicate one of the client wishes to make connection to a server, it will create a socket at its end of the communication link. 19 | P a g e Ports:- A port number identifies a specific application running in the machine. A port is a number in the range 165535. It is a transport layer address used by TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) to handle communication between applications. For example, an email application on one machine wants to communicate with an email application on another machine. The machines are identified by the IP address but the email applications are identified by the port number at which they communicate i.e. Port 25. The JAVA.NET Package The java.net package provides classes and interfaces for implementing network applications such as sockets, network address, Uniform Resource Locators (URLs) etc. Java.net package contains many classes and interface but for this article will cover only those which will use in our application. ServerSocket Class The ServerSocket class is used to create a server that listens for incoming connections from one or more clients. A Server socket binds itself to a specific port so that clients can connect to it. (b) What are principles of event delegation model? Explain different sources of events and event listener. In Java, events represent all activity that goes on between the user and the application. Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events. When the user interacts with a program by clicking a command button, the system creates an event representing the action and delegates it to the event-handling code within the program. This code determines how to handle the event so the user gets the appropriate response. Components of an Event: Event Object: When the user interacts with the application by clicking a mouse button or pressing a key an event is generated. The Operating System traps this event and the data associated with it. For example, info about time at which the event occurred, the event types (like key press or mouse click). This data is then passed on to the application to which the event belongs. In Java, events are represented by objects, which describe the events themselves. And Java has a number of classes that describe and handle different categories of events. 20 | P a g e 2. Event Source: An event source is the object that generated the event. Example if a button is clicked by the user, an ActionEvent Object is generated. The object of the ActionEvent class contains information about the event. 3. Event-Handler It is a method that understands the event and processes it. The eventhandler method takes the Event object as a parameter. Java uses Event-Delegation Model: with JDK1.1 onwards; user can specify the objects that are to be notified when a specific event occurs. If the event is irrelevant, it is discarded. The four main components based on this model are Event classes, Event Listeners, Explicit event handling and Adapters. (c) What is servlet? Explain various ways of session management in servlet programming. Ans: A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services. Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. There are several ways through which we can provide unique identifier in request and response. 21 | P a g e A. User Authentication – This is the very common way where we user can provide authentication credentials from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers. B. HTML Hidden Field – We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session. C. URL Rewriting – We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters. D. Cookies – Cookies are small piece of information that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session. We can maintain a session with cookies but if the client disables the cookies, then it won’t work. E. Session Management API – Session Management API is built on top of above methods for session tracking. Some of the major disadvantages of all the above methods are: Most of the time we don’t want to only track the session, we have to store some data into the session that we can use in future requests. This will require a lot of effort if we try to implement this. All the above methods are not complete in themselves, all of them won’t work in a particular scenario. So we need a solution that can utilize these methods of session tracking to provide session management in all cases. That’s why we need Session Management API and J2EE Servlet technology comes with session management API that we can use. 22 | P a g e 23 | P a g e