Sns College of Technology: Java Programming
Sns College of Technology: Java Programming
Sns College of Technology: Java Programming
2 Marks Question and Answer Subject Code & Name: 080230019 & COMPUTER NETWORKS Prepared by: T.Rajendran Associate Professor/CSE B.Vinodhini Lecturer/CSE
2 Marks (Part A)
1. What is JAVA ?
Java is a pure object oriented programming language, which has derived C syntax and C++ object oriented programming features.
Is a compiled and interpreted language and is platform independent and can do graphics, networking, multithreading. It was initially called as OAK. 2. What are the four cornerstones of OOP ? a. Abstraction : Can manage complexity through abstraction. Gives the complete overview of a particular task and the details are handled by its derived classes. Ex : Car. b. Encapsulation : Nothing but data hiding, like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. c. Inheritance : Is the process in which one object acquires the properties of another object, ie., derived object. d. Polymorphism : One method different forms, ie., method overriding and interfaces are the examples of polymorphism. 3. What is down casting? Doing a cast from a base class to a more specific class. The cast does not convert the object, just asserts it actually is a more specific extended object. e.g. Dalamatian d = (Dalmatian) aDog; Most people will stare blankly at you if you use the word downcast. Just use cast. 4. What is Java Interpreter? It is Java Virtual Machine. ie., a java program compiles the Unicode to intermediary code called as Byte code which is not an executable code, that is executed by Java interpreter.
Page 1
JAVA PROGRAMMING
5. What are Java Buzzwords? Simple : Easy to learn. Secure : Provided by firewalls between networked applications. Portable : Can be dynamically downloaded at various platforms connect to internet. OOP : Four Corner stones. Multithread : Can perform more than one task concurrently in a single program. Robust : overcomes problems of de-allocation of memory and exceptions. Interpreted : Convert into byte code and the executes by JVM. Distributed : Concept of RMI. Dynamic : Verifying and accessing objects at run time. 6. What are public static void main(String args[]) and System.out.println() ? Public keyword is an access specifier. Static allows main() to be called without having to instantiate a particular instance of class. Void does not return any value. main() is the method where java application begins. String args[] receives any command line arguments during runtime. System is a predefined class that provides access to the system. out is output stream connected to console. println displays the output. 7. What are identifiers and literals? Identifiers are the variables that are declared under particular datatype. Literals are the values assigned to the Identifiers. 8. What is typed language?
This means that the variables are at first must be declared by a particular data type whereas this is not the case with JavaScript.
9. Scope and lifetime of variables? scope of variables is only to that particular block lifetime will be till the block ends. variables declared above the block within the class are valid to that inner block also. 10. Casting Incompatible types?
Can be done either implicitly and explicitly. ie., int b = (int) c; where c is float. There are two types of castings related to classes : 1) unicast and 2)multicast.
Page 2
JAVA PROGRAMMING
12. What does String define ? String is an array of characters, but in java it defines an object. and the variable of type string can be assigned to another variable of type String.
13. What are bitwise operators and bitwise logical operators ? ~, &, |, ^, >>, >>>, <<, &=, != and ~, &, | 14. How do you define break and Label? We can declare as break <label name > and the label is declared as <label name> : { .. }; The break statement can be declared anywhere in the program ie either inside the label or outside the label. 15. Define class ? A class is a one which defines new datatype, and is template of an object, and is a prototype. 16. Types of Constructors? Default Constructor, Parameterized Constructor,
Copy Constructors
17. Garbage collector takes the responsibility releasing the memory of object implicitly. 18. Define this , finalize, and final( for variables, methods, classes ) ? this is used inside any method to refer to the current object. and is mostly avoided. finalize method is used to perform the actions specified in this method just before an object is destroyed. ie just before garbage collector process. final with variables is we cant change the literals of the variables ie nothing but const. final with method means we cant override that method. final with class means we cannot have derived classes of that particular class. 19. What is passed by reference?
Objects are passed by reference.
In java we can create an object pointing to a particular location ie NULL location by specifying : <class name> <object name>; and also can create object that allocates space for the variables declared in that particular class by specifying : <object name > = new <class name>(); 20. Explain about Static? When a member is declared as static it can be accessed before any objects of its class are created and without any reference to any object. these are global variables, no copy of these variables can be made. static can also be declared for methods. and cannot refer to this or super. 21. What are nested classes?
There are two types : static and non-static. SNSCT Department of Compute Science and Engineering Page 3
JAVA PROGRAMMING
static class means the members in its enclosing class (class within class) can be accessed by creating an object and cannot be accessed directly without creating the object. non-static class means inner class and can be accessed directly with the object created for the outer class no need to create again an object like static class. 22. Briefly about super ()? This is used to initialize constructor of base class from the derived class and also access the variables of base class like super.i = 10. 23. method overloading : same method name with different arguments. 24. method overriding : same method name and same number of arguments. 25. What is Dynamic Method Dispatch? This is the mechanism by which a call to an overridden function is resolved at runtime rather than at compile time. And this is how Java implements runtime polymorphism. 26. What are abstract classes? To create a super class that only defines generalized form that will be shared by all its subclasses, leaving it to each subclass to fill in the details.
We cannot declare abstract constructors and abstract static methods. An abstract class contains at least one abstract method. And this abstract class is not directly instantiated with new operator. Can create a reference to abstract class and can be point to subclass object.
28. What are packages and why? how to execute a program in a package ?
Package is a set of classes, which can be accessed by themselves and cannot be accessed outside the package. and can be defined as package <pkg name>.
Package name and the directory name must be the same. And the execution of programs in package is done by : java mypack.account where mypack is directory name and account is program name. 29. What does a java source file can contain ? specifying package name. importing more than one package specifying classes and there methods
Page 4
JAVA PROGRAMMING
30. Define interface.
Interface is similar to abstract classes. This defines only method declarations and definitions are specified in the classes which implements these interfaces. one interface multiple methods signifies the polymorphism concept. Here an interface can extend another interface and a class implements more than one interface.
try : statements that you want to monitor the exceptions contain in try block. catch : the exception thrown by try is catched by this. throw : to manually throw exception we go for this. throws : Exception that is thrown out of a method must be specified by throws after the method declaration. finally : this block is executed whether or not an exception is thrown. and also it is executed just before the method returns. and this is optional block. 32. What are checked and unchecked Exceptions ? Unchecked Exceptions are those which r not included in throws list and are derived from RuntimeException which are automatically available and are in java.lang. Checked Exceptions are those which cannot handle by itself.
MultiThreading writes more efficient programs and make maximum use of CPU ie., it minimizes its idle time.
A Thread is created in two ways :
By implementing the runnable interface. By extending the Thread class itself. First way is used to update only run() method. ie we can use only run() method in this class. Second way is used to define several methods overridden by derived class.
Generally we override only run() method so we go for runnable interface.
34. What are the various states and methods of thread ? States : Running, Ready to run, Suspended, Resumed, blocked and terminated. Methods : getName, getPriority, isAlive, join, run, sleep, start. a. Thread priorities are MIN_PRIORITY, MAX_PRIORITY, NORM_PRIORITY.
Page 5
JAVA PROGRAMMING
35. What is interprocess synchronization ? ( also called Monitor, Semaphore )
a. Consider a small box namely MONITOR that can hold only one thread. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor. b. In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time. c. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object.
36. What is Stream ? a. It is an Abstraction that either produces or consumes information. b. Two types : Byte Stream and Character Stream. 37. Print Writer is to Print output in Real World Programs. 38. How to enter data in java? a. First specify : BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); then say br.read(), and this is put in do while loop to receive as many as we require.
39. What are the four components in URL ? a. http:// www. yahoo .com : 8080 / index.html http: --- > is protocol www. yahoo .com --- is IP address 8080 -- port number and is a pointer to memory location. index.html -- file path to be loaded 40. What is a StringTokenizer ? a. String Tokenizer provide parsing process in which it identifies the delimiters provided by the user , by default delimiters are spaces, tab, newline etc. and separates them from the tokens. Tokens are those which are separated by delimiters. 41. What is Serialization ?
The process of writing the state of an object to a byte stream. and can restore these objects by using deserialization. Is also need to implement RMI, which allows a java object of one machine to invoke java object of another machine. ie., the object is passed as an argument by serializing it and the receiving machine deserializes it.
Page 6
JAVA PROGRAMMING
Intefaces : Cloneable, Comparable, Runnable.
43. What is user defined exception? To handle situations specific to our applications we go for User Defined Exceptions. and are defined by User using throw keyword. 44. What is the difference between process and threads? Process is a heavy weight task and is more cost. Thread is a light weight task which is of low cost. A Program can contain more than one thread. A program under execution is called as process.
45. What is update method called? a. This method is called when your Applet has requested that a portion of its window to be redrawn. Default version of update() first fills an applet with the default background color and then calls paint(); This is a default method in the applet class to which we can extend it. 46. What are Vector, Hashtable, LinkedList and Enumeration? Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object's keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements( ) and nextElement( ). HasMoreElemnts( ) tests if this enumeration has more elements and nextElement method returns successive elements of the series. 47. What are statements in Java (JDBC) ? Statement -- To be used createStatement() method for executing single SQL statement PreparedStatement -- To be used preparedStatement() method for executing same SQL statement over and over CallableStatement -- To be used prepareCall( ) method for multiple SQL statements over and over. 48. What is a JAR file? a. Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. b. The package java.util.zip contains classes that read and write jar files.
Page 7
JAVA PROGRAMMING
49. What is JNI? java native interface : The machanism to integrate C code with a java program is called the Java Native Interface. 50. What is the base class for all swing components? Jcomponent 51. What is JFC? java foundation classes (i) Pluggable Look-and-Feel (ii) Accessibility API (iii)Java 2D/API(JDK 1.2). (iv) Drag and Drop Support(JDK 1.2) 52. Canvas Its a component A rectangular area where the application vertical can draw or trap input events. ScrollPane Its a container. horizontal and
Implements
scrolling.
53. What is the difference between JDBC and ODBC? a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can't be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC. 54. What are the types of JDBC Driver Models and explain them? Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.
Page 8
JAVA PROGRAMMING
55. What are the steps involved for making a connection with a database or how do you connect to a database?
a)
Loading the driver : To load the driver, Class.forName( ) method is used. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); When the driver is loaded, it registers itself with the java.sql.DriverManager class as an available database driver. b) Making a connection with database : To open a connection to a given database, DriverManager.getConnection( ) method is used. Connection con = DriverManager.getConnection ("jdbc:odbc:somedb", "user", "password"); c) Executing SQL statements : To execute a SQL query, java.sql.statements class is used. createStatement( ) method of Connection to obtain a new Statement object. Statement stmt = con.createStatement( ); A query that returns data can be executed using the executeQuery( ) method of Statement. This method executes the statement and returns a java.sql.ResultSet that encapsulates the retrieved data: ResultSet rs = stmt.executeQuery("SELECT * FROM some table"); d) Process the results : ResultSet returns one row at a time. Next( ) method of ResultSet object can be called to move to the next row. The getString( ) and getObject( ) methods are used for retrieving column values: while(rs.next( ) ) { String event = rs.getString("event"); Object count = (Integer) rs.getObject("count");
Ans: Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
57. How to create and call stored procedures?
Ans: To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END;
CallableStatement csmt = con.prepareCall("{call procedure name(?,?)}"); csmt.registerOutParameter(column no., data type); csmt.setInt(column no., column name) csmt.execute( );
59. What is servlet?
Ans: Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking
Page 9
JAVA PROGRAMMING
data in an HTML order-entry form and applying the business logic used to update a company's order database.
60. What is the difference between an applet and a servlet? Servlets are to servers what applets are to browsers.
Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
61. What is the difference between doPost and doGet methods? a) doGet() method is used to get information, while doPost( ) method is used for posting information.
b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost( )requests passes all of its data, of unlimited length.
62. What are Class, Constructor and Primitive data types?
Ans: Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. 63. Primitive data types are 8 types and they are: a. byte, short, int, long b. float, double c. boolean d. char 64. What is an Object and how do you allocate memory to it? Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.
65. What is the difference between constructor and method?
Ans: Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
66. What are methods and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.
Page 10
JAVA PROGRAMMING
67. What is the use of bin and lib in JDK?
Ans: Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.
68. What is casting?
Ans: While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
70. What is Garbage Collection and how to call it explicitly?
Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System.gc() method may be used to call it explicitly.
71. What is finalize() method ?
Ans: finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.
72. What are Transient and Volatile Modifiers?
Ans: Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
73. What is method overloading and method overriding?
Ans: Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
74. What is difference between overloading and overriding?
Ans: a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding,subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.
Page 11
JAVA PROGRAMMING
75. What is meant by Inheritance and what are its advantages?
Ans: Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
76. What is the difference between this() and super()?
Ans: this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.
77. What is the difference between superclass and subclass?
Ans: A super class is a class that is inherited whereas sub class is a class that does the inheriting.
78. What modifiers may be used with top-level class?
Ans: public, abstract and final can be used for top-level class.
79. What are inner class and anonymous class?
Ans: Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
80. What is a package?
Ans: A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.
81. What is a reflection package?
Ans: Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a) Declaring methods that one or more classes are expected to implement b) Capturing similarities between unrelated classes without forcing a class relationship. c) Determining an object's programming interface without revealing the actual body of the class.
83. What is the difference between Integer and int?
Ans: a) Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other.
Page 12
JAVA PROGRAMMING
b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
84. What is the difference between abstract class and interface?
Ans: a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods Whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can't have subclasses.
85. Can you have an inner class inside a method and what variables can you access?
Ans: Yes, we can have an inner class inside a method and final variables can be accessed.
86. What is the difference between exception and error?
Ans: The exception class defines mild error conditions that your program encounters. Ex: Arithmetic Exception, FilenotFound exception Exceptions can occur when try to open the file, which does not exist the network connection is disrupted operands being manipulated are out of prescribed ranges the class file you are interested in loading is missing The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered. Ex: Running out of memory error, Stack overflow error. 87. What is the class and interface in java to create thread and which is the most advantageous method? Ans: Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.
88. When you will synchronize a piece of your code?
Ans: When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
89. What is daemon thread and which method is used to create the daemon thread?
Ans: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
90. Are there any global variables in Java, which can be accessed by other part of your program?
Page 13
JAVA PROGRAMMING
Ans: No, it is not the main method in which you define variables. Global variables are not possible because concept of encapsulation is eliminated here.
91. What is the difference between applications and applets?
Ans: a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.
92. How does applet recognize the height and width?
Ans:When the applet class file is not in the same directory, codebase is used.
94. How do you set security in applets?
Ans: An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model
96. What is source and listener ?
Ans: source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
97. What is adapter class?
Ans: An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested.
98. What is meant by controls and what are different types of controls in AWT?
Ans: Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Page 14
JAVA PROGRAMMING
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.
99. What is the difference between choice and list?
Ans: A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items. 100. What is a layout manager and what are different types of layout managers available in java.awt? Ans: A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
101.
Ans: Window, Frame and Dialog classes use a BorderLayout as their layout.
102. Which containers use a Flow layout as their default layout?
Ans: Panel and Applet classes use the FlowLayout as their default layout.
103. What are wrapper classes?
Ans: Wrapper classes are classes that allow primitive types to be accessed as objects.
104. What is the difference between set and list?
Ans: Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements. 105. what is the basic difference in rmi & corba.
both are distributed technologies. rmi is used when both client & server are in java. corba is used when client & server are written in different lang. IDL comes into picture. as it changes native calls to java or vice versa.
106. what does class.forName(driver) do? it requests for the driver & loads the driver. statement.execute() returns resultset. what type of resultset is it? ---> sql result set
SNSCT Department of Compute Science and Engineering Page 15
JAVA PROGRAMMING
Page 16