Getting ready for the midterm of CS506 (Web Design and Development)? Here is everything in one place: solved MCQs, subjective questions with answers and short notes and key terms, gathered from past papers and files shared by students. No duplicates and all the answers are checked and verified. Use the tabs above to switch between Objective, Subjective and Short Notes & Key Terms, and tap Show answer only after you have tried the question yourself. Best of luck with your exam!
Part 1: Objective (MCQs)
Q1. What happens if the static modifier is removed from the signature of the main method?
- The program does not compile
- The program compiles but does not run
- The program compiles and runs properly
- The program throws an exception at compile time
Show answer
Answer: (b) The program compiles but does not run
Why: It compiles, but the JVM cannot start it: the launcher reports "Main method is not static". Shared answer keys disagreed ("exception in main", "compile-time exception"); this was checked by compiling and running it.
Q2. What happens if the String array parameter is removed from main (public static void main())?
- The program does not compile
- The program compiles but does not run
- The program compiles and runs successfully
- None of the given options
Show answer
Answer: (b) The program compiles but does not run
Why: It compiles as an ordinary method, but without main(String[]) the JVM finds no entry point ("Main method not found"). Checked by compiling and running it.
Q3. What happens if the main method is declared as private?
- The program does not compile
- The program compiles but does not run
- The program compiles and runs properly
- The program throws an exception at compile time
Show answer
Answer: (b) The program compiles but does not run
Why: main must be public so the JVM can call it. The code compiles, then the launcher reports "Main method not found". Checked by compiling and running it.
Q4. Java was developed in ________.
- 1990
- 1995
- 1997
- 2000
Show answer
Answer: (b) 1995
Why: Java was publicly released in 1995.
Q5. Which of the following methods are invoked by the AWT to support paint and repaint operations?
- paint( )
- repaint( )
- draw( )
- redraw( )
Show answer
Answer: (a) paint( )
Why: The AWT calls paint() itself; repaint() is the method the programmer calls to request a repaint.
Q6. When defining a method you must include a ______ to declare any exception that might be thrown but is not caught in the method.
- try block
- finally block
- catch block
- throws-clause
Show answer
Answer: (d) throws-clause
Q7. Aside from the Scanner class, which of the following classes can be used for text-file input?
- ObjectInputStream
- BufferedReader
- StringTokenizer
- None of these
Show answer
Answer: (b) BufferedReader
Why: The source gave no key. BufferedReader (wrapped around FileReader) reads text files line by line; ObjectInputStream reads serialized objects and StringTokenizer only splits a String.
Q8. Which of the following statements is true regarding Vectors with no specified base type?
- A base type is needed, because Java needs to know how to allocate memory.
- No base type is needed, because Java will use the Object class as a base type.
- If a base type is not specified the code will not compile.
- No base type is needed because Vectors default to storing String objects.
Show answer
Answer: (b) No base type is needed, because Java will use the Object class as a base type.
Q9. A serializable class must implement the method(s) ________.
- readObject and writeObject
- Either readObject or writeObject, or both, depending upon the desired behavior
- No need to implement any method
- None of the given option
Show answer
Answer: (c) No need to implement any method
Why: Serializable is a marker interface with no methods.
Q10. You can ________ to a network using sockets.
- Read
- Write
- Read/Write
- None of these
Show answer
Answer: (c) Read/Write
Q11. A socket is a ________ communication channel between hosts.
- Uni-directional
- Bi-directional
- Multi-directional
- None of these
Show answer
Answer: (b) Bi-directional
Q12. Which of the following objects is passed as an argument to the paint( ) method?
- A Canvas object
- A Graphics object
- An Image object
- A paint object
Show answer
Answer: (b) A Graphics object
Q13. The code below draws a line. What color is the line? g.setColor(Color.red.green.yellow.red); g.drawLine(0, 0, 100, 100);
- Red
- Green
- Yellow
- Black
Show answer
Answer: (a) Red
Why: The shared key said Black, which is wrong. green, yellow and red are static fields of Color, so each ".name" just replaces the value, and the last one is Color.red. Checked by compiling it (Java gives only a warning about accessing static fields through an instance).
Q14. Which line creates a DatabaseMetaData object?
- DatabaseMetaData db = con.getMetaData();
- ResultSetMetaData rsmd = rs.getMetaData();
- ResultSetMetaData rsmd = rs.setMetaData();
- DatabaseMetaData db = con.setMetaData();
Show answer
Answer: (a) DatabaseMetaData db = con.getMetaData();
Why: The course handout prints the names with typos (DataBaseMetaData, getMeataData); the real API names are DatabaseMetaData and getMetaData(). It is obtained from the Connection object.
Q15. An event source can have ________ listeners registered on it.
- Single
- Double
- Triple
- Multiple
Show answer
Answer: (d) Multiple
Q16. An abstract class ________ instantiated.
- Can't be
- Can be
- Must
- None of these
Show answer
Answer: (a) Can't be
Why: An instance of an abstract class cannot be created; only its concrete subclasses can be instantiated.
Q17. A ________ defines the way and method of communication between two parties.
- Compiler
- Protocol
- Tool
- Technique
Show answer
Answer: (b) Protocol
Q18. A member variable or method prefixed by the protected access modifier can be accessed:
- Within the same class
- Within the sub-class
- Within the same package
- All of the above
Show answer
Answer: (d) All of the above
Q19. A top level class without any modifier is accessible to
- any class
- any class within the same package
- any class within the same file
- any subclass of this class
Show answer
Answer: (b) any class within the same package
Q20. A top level class may have only the following access modifier.
- Package
- Private
- Protected
- Public
Show answer
Answer: (d) Public
Why: Judgment call: the lesson's answer is Public. (In real Java a top-level class can also have no modifier, i.e. package access, but "Package" is not a keyword modifier.)
Q21. In Java an abstract class cannot be sub-classed.
- True
- False
Show answer
Answer: (b) False
Why: An abstract class exists to be sub-classed; it just cannot be instantiated.
Q22. Given a one-dimensional array arr, what is the correct way of getting the number of elements in arr?
- arr.length
- arr.length - 1
- arr.size - 1
- arr.length()
Show answer
Answer: (a) arr.length
Q23. When a recursive method is called to solve a problem, the method is actually capable of solving only the simplest case(s), or base case(s).
- True
- False
Show answer
Answer: (a) True
Q24. Which of these are valid declarations for the main method?
- public void main();
- public static void main(String args[]);
- static public void main(String);
- public static int main(String args[]);
Show answer
Answer: (b) public static void main(String args[]);
Q25. The Map interface is derived from the Collection interface.
- True
- False
Show answer
Answer: (b) False
Why: Map is a separate root interface; it does not extend Collection.
Q26. In Java, which of these classes implements the LayoutManager interface?
- RowLayout
- ColumnLayout
- GridBagLayout
- FlowLayoutManager
Show answer
Answer: (c) GridBagLayout
Q27. BorderLayout is the default layout manager for a JFrame's content pane.
- True
- False
Show answer
Answer: (a) True
Q28. You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective?
- public
- private
- protected
- transient
- default access
Show answer
Answer: (e) default access
Q29. In Java, garbage collection is done by ________.
- JVM (Java Virtual Machine)
- Programmer
- Both JVM and Programmer
- OS (Operating System)
- None of given
Show answer
Answer: (a) JVM (Java Virtual Machine)
Q30. Which of the following can be thrown using the throw statement?
- Error
- Throwable
- Exception
- RuntimeException
- All of Given
Show answer
Answer: (e) All of Given
Why: The shared key said Exception only. Any Throwable can be thrown, and Error, Exception and RuntimeException are all Throwable, so "All of Given" is correct.
Q31. ________ is/are the JSP implicit object(s).
- session
- application
- config
- All of Given
- None of Given
Show answer
Answer: (d) All of Given
Q32. JavaBeans are?
- A special Java class file
- Servlets
- Applets
- A special form of JSP
- None of Given
Show answer
Answer: (a) A special Java class file
Why: The source key said "A special form of JSP", which is wrong. A JavaBean is a reusable Java class that follows conventions (private properties with getters/setters, a public no-argument constructor, serializable).
Q33. An expression tag contains a scripting language expression that is evaluated.
- True
- False
Show answer
Answer: (a) True
Q34. A final class can't be extended.
- True
- False
Show answer
Answer: (a) True
Q35. ServletConfig defines a set of methods that a servlet uses to communicate with its servlet container.
- True
- False
Show answer
Answer: (b) False
Why: That description belongs to ServletContext. ServletConfig carries a servlet's own initialization parameters.
Q36. A method cannot be made final unless the whole class is made final.
- True
- False
Show answer
Answer: (b) False
Why: A single method can be declared final on its own (it then cannot be overridden). The source gave no key.
Q37. Servlet session and JSP session have different abilities.
- True
- False
Show answer
Answer: (b) False
Why: The source gave no key. The JSP session implicit object is the same HttpSession a servlet uses, so they have the same abilities.
Q38. Which of the following is NOT a part of an HTTP request?
- Request method
- URI
- Status code
- Header fields
Show answer
Answer: (c) Status code
Why: The status code is part of the HTTP response.
Q39. Which method needs to be overridden while handling threads in Java?
- init()
- start()
- run()
- runnable()
Show answer
Answer: (c) run()
Why: The source key said init(), which is wrong (init() belongs to applets and servlets). A thread's work goes into run().
Q40. Which of the following problems occurs with lower priority threads?
- Race condition
- Starvation
- Average waiting time
- Process death
Show answer
Answer: (b) Starvation
Q41. Which of the following is NOT a web technology of Java?
- Servlet
- JSP
- ASP
- JSF
Show answer
Answer: (c) ASP
Q42. Which interface needs to be implemented while creating threads?
- Serializable
- Runnable
- ActionListener
- WindowListener
Show answer
Answer: (b) Runnable
Q43. Which approach is used to create threads in Java?
- inheritance
- interface
- Both inheritance and interface
- None of these
Show answer
Answer: (c) Both inheritance and interface
Why: Extend the Thread class (inheritance) or implement Runnable (interface).
Q44. Which method allows any other thread of the same priority to execute?
- sleep()
- wait()
- notify()
- yield()
Show answer
Answer: (d) yield()
Q45. Which method call causes the currently executing thread to return to the Ready (runnable) state?
- sleep()
- yield()
- wait()
- None of these
Show answer
Answer: (b) yield()
Why: The source key said "None of these", but yield() moves the running thread back to the ready state so another thread can run. sleep() and wait() put it in a waiting state.
Q46. Which environment variable tells the system about the root directory of Tomcat?
- JAVA_HOME
- CATALINA_HOME
- CLASSPATH
- PATH
Show answer
Answer: (b) CATALINA_HOME
Q47. Which of the following is NOT true about HTTP?
- HTTP is a stateless protocol
- HTTP is a request-response communication model
- HTTP maintains user session between successive requests.
- HTTP has no built-in state management between successive requests.
Show answer
Answer: (c) HTTP maintains user session between successive requests.
Q48. Which range of response codes signifies an error by the server?
- 200-299
- 300-399
- 400-499
- 500-599
Show answer
Answer: (d) 500-599
Q49. Which range of response codes indicates that the request was successful?
- 100-199
- 200-299
- 300-399
- 400-499
Show answer
Answer: (b) 200-299
Q50. Which folder contains the configuration file?
- classes
- lib
- bin
- WEB-INF
Show answer
Answer: (d) WEB-INF
Q51. web.xml is a ________.
- java file
- configuration file
- jar file
- servlet
Show answer
Answer: (b) configuration file
Q52. The keyword "this" is used to
- invoke the constructor of the super class from a sub class
- invoke an alternate constructor of the same class
- invoke the constructor of another class
- invoke the constructor of a sub class from the super class
Show answer
Answer: (b) invoke an alternate constructor of the same class
Why: The source gave no key. this(...) calls another constructor of the same class (super(...) calls the parent's).
Q53. Which of the following features does Java provide?
- Multiple Inheritance
- Overriding
- Pointers
- Operator Overloading
Show answer
Answer: (b) Overriding
Q54. To call the toString() method of the parent class in Java, which statement is used?
- super.toString();
- sub.toString();
- new.toString();
- this.toString();
Show answer
Answer: (a) super.toString();
Q55. Overloading is ________ whereas overriding is ________.
- Run time binding, compile time binding
- Late binding, compile time binding
- Compile time binding, run time binding
- Run time binding, late time binding
Show answer
Answer: (c) Compile time binding, run time binding
Q56. Which command is used to compile Java code?
- javac filename.java
- javac filename
- java filename.java
- java filename
Show answer
Answer: (a) javac filename.java
Q57. Which command is used to run a Java program?
- java filename.java
- java filename
- javac filename.java
- javac filename
Show answer
Answer: (b) java filename
Why: Run the class name without the .java extension; javac is the compiler. (The same idea appears in several quiz questions about running and compiling a file such as JavaTest.)
Q58. Which of the following is true about primitive data types and reference data types?
- Primitive data types are created on heap whereas references are created on stack
- Both primitive data types and references are created on stack
- Primitive data types are created on stack whereas references are created on heap
- Both primitive data types and references are created on heap
Show answer
Answer: (c) Primitive data types are created on stack whereas references are created on heap
Why: The source gave no key. This is the course's answer: primitives live on the stack, objects (reference types) on the heap. (Strictly, the reference variable itself sits on the stack and points to the object on the heap.)
Q59. Which of the following statements regarding Java is false?
- Java programs can run on any CPU or operating system.
- Its object-oriented model enables programmers to benefit from its large set of existing classes.
- Java needs to be compiled only once.
- Java can run only on a Windows operating system.
Show answer
Answer: (d) Java can run only on a Windows operating system.
Q60. Which operator is used to concatenate strings?
- +=
- +-
- ++
- +
Show answer
Answer: (d) +
Why: Both + and += can join strings; + is the concatenation operator.
Q61. If there is a class "Student", then the Java file must be saved with the name ________.
- Student_File.java
- student.java
- Any name
- Student.java
Show answer
Answer: (d) Student.java
Why: Judgment call: the lesson answer is Student.java. The file name must match when the class is public; a non-public class could be saved under another name.
Q62. Which one of the following understands the byte code?
- Operating system
- Java compiler
- Java Virtual Machine
- Java Interpreter
Show answer
Answer: (c) Java Virtual Machine
Why: The JVM executes bytecode. (An interpreter is part of the JVM; the course answer is the JVM.)
Q63. What happens if we write static public void instead of public static void?
- Program does not compile
- Program compiles but does not run
- Program compiles and runs successfully
- Program throws an exception
Show answer
Answer: (c) Program compiles and runs successfully
Why: The order of modifiers does not matter. The source gave no key.
Q64. The collection API is defined in the ________ package.
- java.io
- java.util
- java.awt
- java.sql
Show answer
Answer: (b) java.util
Q65. Which one of the following features is not available in Java?
- Data hiding
- Data encapsulation
- Single inheritance
- Multiple inheritance
Show answer
Answer: (d) Multiple inheritance
Why: Java has no multiple inheritance of classes (interfaces give a form of it).
Q66. Converting a bigger data type into a smaller data type is called ________.
- Up-casting
- Down-casting
- Normal-casting
- High-casting
Show answer
Answer: (b) Down-casting
Q67. If a super class method is protected, then the overriding method ________.
- must be protected
- must be public
- must be private
- may be either protected or public
Show answer
Answer: (d) may be either protected or public
Why: The shared key said "must be public", which is wrong. An overriding method may keep the same access or widen it, so protected or public are both legal.
Q68. Which keyword is used for inheritance in Java?
- implements
- extends
- : (colon)
- inherit
Show answer
Answer: (b) extends
Q69. ArrayList is an example of ________ collection type.
- Sequence based
- Set based
- Hashmap based
- None of the given
Show answer
Answer: (a) Sequence based
Q70. Static methods can only access ________.
- Instance methods
- Instance variables
- Both static and instance members
- Static variables and methods
Show answer
Answer: (d) Static variables and methods
Q71. Which feature is not included in Java?
- Data encapsulation
- Pointer manipulation
Show answer
Answer: (b) Pointer manipulation
Why: The source showed only these two options.
Q72. Which of the following is a valid variable name in Java?
- long
- NumberOfStudent
- vu.506
- 1xu
Show answer
Answer: (b) NumberOfStudent
Why: long is a keyword, vu.506 contains a dot, and 1xu starts with a digit.
Q73. A variable declared as static in a class is a/an ________.
- Const variable
- Global variable
- Class variable
Show answer
Answer: (c) Class variable
Why: The source showed only three options.
Q74. Java program code is compiled into a form called ________.
- Machine code
- Native code
- Byte code
- Source code
Show answer
Answer: (c) Byte code
Q75. Which modifier is provided by default if no access modifier is written explicitly?
- public
- private
- protected
- default
Show answer
Answer: (d) default
Why: This is package-level (default) access.
Q76. Which of the following syntax is used to attach an input stream to the console?
- FileReader fr = new FileReader("input.txt");
- FileReader fr = new FileReader(FileDescriptor.in);
- FileReader fr = new FileReader(FileDescriptor);
- FileReader fr = new FileReader(console);
Show answer
Answer: (b) FileReader fr = new FileReader(FileDescriptor.in);
Why: The source key marked the first option, which reads a file, not the console. FileDescriptor.in is the standard input (keyboard).
Q77. Which of the following syntax attaches an output stream to the console?
- FileWriter fw = new FileWriter("output.txt");
- FileWriter fw = new FileWriter(FileDescriptor.out);
- FileWriter fw = new FileWriter(FileDescriptor.in);
- FileWriter fw = new FileWriter(FileDescriptor);
Show answer
Answer: (b) FileWriter fw = new FileWriter(FileDescriptor.out);
Q78. Window frame and dialog use ________ as their default layout.
- Border layout
- Flow layout
- GridBag layout
- Grid layout
Show answer
Answer: (a) Border layout
Q79. There are ________ types of exceptions in Java.
- 2
- 3
- 4
- 5
Show answer
Answer: (b) 3
Why: Course answer: three kinds of throwables to handle (checked exceptions, unchecked/runtime exceptions and errors). Judgment call, as other books count two.
Q80. Which of the following belongs to the category of checked exceptions?
- NullPointerException
- IOException
- ArrayIndexOutOfBoundsException
- NumberFormatException
Show answer
Answer: (b) IOException
Q81. Which of the following exceptions belongs to the category of unchecked exceptions?
- IOException
- NullPointerException
- AWTException
- ClassNotFoundException
Show answer
Answer: (b) NullPointerException
Q82. All the exceptions and errors in Java are inherited from the ________ class.
- Exception
- Error
- Throwable
- IOException
Show answer
Answer: (c) Throwable
Q83. Exceptions must be handled while handling files, otherwise it may lead to ________.
- Logical error
- Syntax error
- Run-time error
- No error
Show answer
Answer: (c) Run-time error
Q84. Which package needs to be imported while handling files?
- java.util
- java.io
- java.awt
- javax.swing
Show answer
Answer: (b) java.io
Q85. The classes which contain the word ________ are byte oriented streams.
- Reader
- Writer
- Stream
- Byte
Show answer
Answer: (c) Stream
Q86. Which of the following streams reads/writes data in the form of bytes?
- FileReader
- FileWriter
- PrintWriter
- FileInputStream
Show answer
Answer: (d) FileInputStream
Q87. The relationship between a class and an interface is called ________.
- 'Is a' relationship
- 'Has a' relationship
- 'Responds to' relationship
- None of the given options
Show answer
Answer: (a) 'Is a' relationship
Why: Course answer; a class that implements an interface can be treated as that interface type.
Q88. Which of the following is called a 'pure abstract class'?
- Concrete class
- Wrapper class
- Interface
- Abstract class with no abstract method
Show answer
Answer: (c) Interface
Q89. Which of the following is true about an abstract class?
- An abstract class must have all methods declared as abstract methods.
- A class must have at least one abstract method to be an abstract class.
- A class without any abstract method can be declared as an abstract class.
- An instance of an abstract class can be created.
Show answer
Answer: (c) A class without any abstract method can be declared as an abstract class.
Q90. Which of the following streams is a filter stream?
- FileWriter
- FileReader
- BufferedReader
- All of given options
Show answer
Answer: (c) BufferedReader
Q91. JPanel and Applet use ________ as their default layout.
- Flow layout
- Border layout
- Grid layout
- GridBag layout
Show answer
Answer: (a) Flow layout
Q92. Which of the following is true about AWT and Swing components?
- AWT components create a process whereas Swing components create a thread.
- AWT components create a thread whereas Swing components create a process.
- Both AWT and Swing components create a process.
- Both AWT and Swing components create a thread.
Show answer
Answer: (a) AWT components create a process whereas Swing components create a thread.
Why: This is the course's wording of heavyweight (AWT, native peer) versus lightweight (Swing) components; it is the answer marked in the solved quiz files.
Q93. Which of the following is a general purpose container?
- JFrame
- Dialog
- JPanel
- JApplet
Show answer
Answer: (c) JPanel
Q94. BorderLayout divides the area into ________ regions.
- 3
- 4
- 5
- 6
Show answer
Answer: (c) 5
Q95. Which function is used to register an event handler with an event generator (button)?
- addAction()
- addActionListener()
- addListener()
- registerListener()
Show answer
Answer: (b) addActionListener()
Q96. If a class needs to handle events generated by a button, which interface does it need to implement?
- ComponentListener
- KeyListener
- MouseListener
- ActionListener
Show answer
Answer: (d) ActionListener
Q97. Which of the following functions is declared in the MouseMotionListener interface?
- public void mousePressed (MouseEvent me);
- public void mouseDragged (MouseEvent me);
- public void mouseClicked (MouseEvent me);
- public void mouseEntered (MouseEvent me);
Show answer
Answer: (b) public void mouseDragged (MouseEvent me);
Q98. The WindowListener interface contains ________ methods.
- Four
- Six
- Seven
- Eight
Show answer
Answer: (c) Seven
Q99. Mouse events can be trapped for ________ GUI component.
- JPanel
- JFrame
- JButton
- All of given
Show answer
Answer: (d) All of given
Q100. Adapter classes have been defined for listener interfaces except the ________ interface.
- MouseListener
- KeyListener
- WindowListener
- ActionListener
Show answer
Answer: (d) ActionListener
Why: ActionListener has only one method, so an adapter is not needed.
Q101. Which package needs to be imported while interacting with a relational database?
- java.io
- java.sql
- javax.swing
- java.awt
Show answer
Answer: (b) java.sql
Q102. DSN stands for ________.
- Data System Name
- Domain system Name
- Data Source Name
- Database System Name
Show answer
Answer: (c) Data Source Name
Q103. Which method is used to execute SELECT SQL statements?
- executeUpdate(sql);
- ExecuteUpdate(sql);
- executeQuery(sql);
- ExecuteQuery(sql);
Show answer
Answer: (c) executeQuery(sql);
Q104. CREATE, ALTER, DROP are ________ SQL statements.
- DML
- DDL
- DCL
- None of given
Show answer
Answer: (b) DDL
Q105. Which method is used to execute INSERT, UPDATE and DELETE SQL statements?
- executeQuery(sql);
- ExecuteQuery(sql);
- executeUpdate(sql);
- ExecuteUpdate(sql);
Show answer
Answer: (c) executeUpdate(sql);
Q106. Which statement object is used to execute stored procedures?
- Statement
- PreparedStatement
- CallableStatement
- None of given options
Show answer
Answer: (c) CallableStatement
Q107. HashMap takes a key as a/an ________.
- Object
- Array
- Primitive value
- Function
Show answer
Answer: (a) Object
Q108. Which of the following features provides the facility for multiple inheritance?
- Adapter Classes
- Wrapper Classes
- Interface
- Collection
Show answer
Answer: (c) Interface
Q109. Consider the following code segment: ArrayList al = new ArrayList(); Person p = new Person(); al.add(p); What is the syntax to get an object from the first index of the ArrayList?
- Person p = al.get(0);
- Person p = al.get(1);
- Person p = (Person) al.get(0);
- Person p = (Person) al.get(1);
Show answer
Answer: (c) Person p = (Person) al.get(0);
Why: A raw ArrayList returns Object, so a cast is needed; the first index is 0. (The third option was partly garbled in the scan and has been restored.)
Q110. Based on functionality, the streams can be categorized as ________.
- Byte oriented stream and Node stream
- Filter stream and Character oriented stream
- Byte oriented stream and Character oriented stream
- Node stream and Filter stream
Show answer
Answer: (d) Node stream and Filter stream
Why: The solved quiz file with reference marks "Node stream and Filter stream" as correct (by functionality: node and filter streams; by data: byte and character oriented).
Q111. Which is the correct syntax to create a ResultSetMetaData object?
- ResultSetMetaData rsmd = con.getMetaData(); // con is a Connection
- ResultSetMetaData rsmd = rs.getMetaData(); // rs is a ResultSet
- ResultSetMetaData rsmd = stmt.getMetaData(); // stmt is a Statement
- ResultSetMetaData rsmd = pstmt.getMetaData(); // pstmt is a PreparedStatement
Show answer
Answer: (b) ResultSetMetaData rsmd = rs.getMetaData(); // rs is a ResultSet
Q112. Which of the following statements is TRUE regarding the default ResultSet?
- The default ResultSet is updatable and moves only forward.
- The default ResultSet is not updatable and moves only forward.
- The default ResultSet is not updatable and moves forward as well as backward.
- The default ResultSet is updatable and moves forward as well as backward.
Show answer
Answer: (b) The default ResultSet is not updatable and moves only forward.
Q113. What will be the output of the following statement? System.out.println(29+5);
- 34
- 29+5
- 295
- None of the given options
Show answer
Answer: (a) 34
Q114. What will be the output of System.out.println(5+9);?
- 59
- 5+9
- 14
- syntax error
Show answer
Answer: (c) 14
Why: Both operands are ints, so they are added. (The scan printed "system" in lower case, which would be a typo.)
Q115. The JVM puts the events generated by the event generator in a ________.
- Stack
- Queue
- List
- Hash table
Show answer
Answer: (b) Queue
Q116. Which statement object is used for executing precompiled SQL statements?
- Statement
- PreparedStatement
- CallableStatement
- None of the given options
Show answer
Answer: (b) PreparedStatement
Q117. HTTP lies on which layer?
- Presentation Layer
- Data Layer
- Network Layer
- Application Layer
Show answer
Answer: (d) Application Layer
Q118. Which package contains ArrayList?
- java.awt
- java.util
- javax.swing
- java.lang
Show answer
Answer: (b) java.util
Q119. Which driver is the network type driver?
- Type 1
- Type 2
- Type 3
- Type 4
Show answer
Answer: (c) Type 3
Why: Type 3 is the net-protocol / all-Java driver.
Q120. When you maximize an applet which was minimized some time before, which method will be called?
- start()
- stop()
- init()
- destroy()
Show answer
Answer: (a) start()
Why: Minimizing calls stop(); restoring calls start() again.
Q121. In multi-tier architecture, object transfer can only happen if which statement about the objects is correct?
- Objects should be always present.
- Object reference should be set.
- Objects should be abstract.
- Objects need to be serialized.
Show answer
Answer: (d) Objects need to be serialized.
Q122. Objects are always written/read in which form?
- method
- variables
- class
- binary
Show answer
Answer: (d) binary
Q123. The bytecodes are verified by the ________ to make sure they do not violate Java security restrictions.
- editor
- bytecode verifier
- class loader
- compiler
Show answer
Answer: (b) bytecode verifier
Why: The scanned stem was damaged; it has been restored from the usual wording of the lesson.
Q124. Given code adds two integers: int i = 7; int j = 8; int k = i + j; System.out.println("Seven " + i + " plus Eight " + j + " is " + k); What is the output?
- Seven i plus Eightj is + 15
- Seven 7 plus Eight 8 is 15
- Seven plus Eight is k
- Seven i plus Eightj is k
Show answer
Answer: (b) Seven 7 plus Eight 8 is 15
Why: Checked by running it. The scanned code was damaged and has been restored.
Q125. Which of the following methods is used to determine whether a database is read only or not?
- isReadOnly()
- IsReadOnly()
- isReadonly()
- isreadonly()
Show answer
Answer: (a) isReadOnly()
Q126. AWT is also called
- Heavy weight components
- Light weight components
- Both Light weight and heavy weight components
- Neither Light weight nor heavy weight
Show answer
Answer: (a) Heavy weight components
Q127. Assume that we do not want to serialize the phoneNum attribute of the PersonInfo class. This can be done by:
- server String phoneNum;
- transient String phoneNum;
- client String phoneNum;
- serializable String phoneNum;
Show answer
Answer: (b) transient String phoneNum;
Q128. A scrollable and updatable ResultSet object has the following capabilities except
- insert new rows
- insert new columns
- delete rows
- update rows
Show answer
Answer: (b) insert new columns
Q129. previous() is a method of the ________ object.
- ResultSetMetaData
- Statement
- ResultSet
- Connection
Show answer
Answer: (c) ResultSet
Q130. TELNET works on port ________.
- 23
- 21
- 84
- 80
Show answer
Answer: (a) 23
Q131. Which code statement is used to define a connection URL?
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
- String asd = "jdbc:odbc:DSNname";
- Statement xyz = abc.createStatement();
- Connection abc = DriverManager.getConnection(conURL);
Show answer
Answer: (b) String asd = "jdbc:odbc:DSNname";
Q132. The "mouseDragged" and "mouseMoved" methods are defined in the ________ interface.
- ItemListener
- MouseMotionListener
- MouseListener
- ActionListener
Show answer
Answer: (b) MouseMotionListener
Q133. An applet is typically embedded in a Web page and can be run from a browser.
- True
- False
Show answer
Answer: (a) True
Q134. Following are code statements used in Java event handling. Identify the statement that is used for generating an event source.
- frame.setSize(150, 150)
- b1 = new JButton("OK")
- b1.addActionListener(this)
- frame = new JFrame
Show answer
Answer: (b) b1 = new JButton("OK")
Why: The source gave no key. Event handling has three parts: the event generator (the button), the event handler, and registering the handler with the generator.
Q135. In the context of socket programming, the client does NOT know the hostname of the machine on which the server is running.
- True
- False
Show answer
Answer: (b) False
Why: The client must know the server's host name (or IP address) and port to connect.
Q136. Identify the code statement that is used for handling an event.
- public void actionPerformed(ActionEvent e)
- container.setLayout(new FlowLayout());
- button = new JButton("Reset")
- button.addActionListener(this)
Show answer
Answer: (a) public void actionPerformed(ActionEvent e)
Q137. The ________ is directly connected with the keyboard.
- Filter stream
- Node stream
- Character oriented stream
- File stream
Show answer
Answer: (b) Node stream
Why: Judgment call (source gave no key): a node stream connects directly to a source such as a file or the keyboard.
Q138. All AWT and Swing components generate events.
- True
- False
Show answer
Answer: (a) True
Why: Judgment call (key missing in one file, "True" in another): every component inherits mouse, key, focus and component events from java.awt.Component.
Q139. getColumnCount() is a method of the ________ object.
- Statement
- DatabaseMetaData
- ResultSet
- ResultSetMetaData
Show answer
Answer: (d) ResultSetMetaData
Q140. Which of the following is NOT true about a JavaBean?
- It should not have any public variable.
- It must be serializable.
- It must not have any zero-argument constructor.
- Private instances must be accessed via setters/getters.
Show answer
Answer: (c) It must not have any zero-argument constructor.
Q141. Which one is used to collect data when a user navigates between web pages?
- Session Tracking
- User Tracking
- Both User Tracking and Session Migration
Show answer
Answer: (a) Session Tracking
Why: One option was unreadable in the scan, so three options are shown.
Q142. What is the relationship between JSP and servlets?
- Servlets are built on JSP semantics and all servlets are compiled to JSP pages for runtime usage
- JSP and servlets are unrelated technologies
- Servlets and JSP are competing technologies for handling web requests; the two are not useful in combination
- JSPs are built on servlet semantics and all JSPs are compiled to servlets for runtime usage
Show answer
Answer: (d) JSPs are built on servlet semantics and all JSPs are compiled to servlets for runtime usage
Q143. Which of the following methods cannot be overridden in the JSP page?
- _jspService()
- jspDestroy()
- Both jspDestroy() and jspInit()
Show answer
Answer: (a) _jspService()
Why: One option was unreadable in the scan, so three options are shown.
Q144. Which statement is correct to assign the maximum priority to thread t2?
- t2.setPriority(Thread.PRIORITY_MIX);
- t2.setPriority(Thread.PRIORITY_MAX);
- t2.setPriority(Thread.MAX_PRIORITY);
- t2.setPriority(Thread.MIX_PRIORITY);
Show answer
Answer: (c) t2.setPriority(Thread.MAX_PRIORITY);
Why: The constant is Thread.MAX_PRIORITY (10). The scanned options were slightly damaged.
Q145. Session tracking is done through which of the following techniques?
- Hidden fields
- URL Rewriting
- Cookies, Hidden fields and URL Rewriting
Show answer
Answer: (c) Cookies, Hidden fields and URL Rewriting
Why: One option was unreadable in the scan, so three options are shown.
Q146. Packages are the way to organize files into different ________ according to their functionality, usability as well as the category they should belong to.
- Directories
- Folders
- Libraries
- None of these
Show answer
Answer: (a) Directories
Why: Judgment call: the Java tutorial wording that the course follows is "directories" (a folder is the same thing in everyday language).
Q147. Exception handling code is written in the ________.
- try block
- catch block
- finally block
- throws clause
Show answer
Answer: (b) catch block
Why: The source gave no key. The handler code goes in the catch block; the try block holds the code that may throw.
Q148. An event in Java is represented as ________.
- Operator
- Function
- Object
- Primitive data type
Show answer
Answer: (c) Object
Q149. If you want to animate something like a ball moving from one place to another, we constantly need to call the paint() method.
- True
- False
Show answer
Answer: (b) False
Why: We call repaint(), which asks the system to call paint()/paintComponent(); we never call paint() directly.
Q150. Which of the following features is not available in Java?
- Pointers
- Operator overloading
- Global variables
- All of given options
Show answer
Answer: (d) All of given options
Q151. Which of the following methods is used to convert a string into an int value?
- intValue()
- parseInt()
- ParseInt()
- parseInteger()
Show answer
Answer: (b) parseInt()
Why: Integer.parseInt(String). Java is case sensitive.
Q152. Which of the following streams is a Node stream?
- PrintWriter
- FileWriter
- BufferedReader
- All of given option
Show answer
Answer: (b) FileWriter
Q153. When a JSP page is compiled, it is translated into?
- Applet
- Application
- Servlet
- Web Browser
Show answer
Answer: (c) Servlet
Q154. To define the error page in JSP we use which tag?
- exception-type
- error-type
- error-page
- exception-page
Show answer
Answer: (c) error-page
Q155. The toString() method returns a ________ representation of ________.
- int, string
- string, int
- string, object
- object, string
Show answer
Answer: (c) string, object
Q156. The == operator compares ________ of strings whereas the equals() method compares ________ of strings.
- Value, Addresses
- Address, Values
- Size, Addresses
Show answer
Answer: (b) Address, Values
Why: One option was unreadable in the scan, so three options are shown.
Q157. Which of the following statements is true regarding the paintChildren() method?
- It tells the component to paint its border.
- It first paints the background and then performs custom painting.
- It first performs custom painting and then paints the border.
- It tells any components contained by this component to paint themselves.
Show answer
Answer: (d) It tells any components contained by this component to paint themselves.
Why: Some option text was cut off in the scan and has been restored from the paintBorder() and paintComponent() descriptions in the lesson.
Q158. Which method of the Graphics object is used to draw a rectangle?
- DrawRect(10,10,20,20);
- drawRect(10,10,20,20);
- drawRectangle(10,10,20,20);
- DrawRectangle(10,10,20,20);
Show answer
Answer: (b) drawRect(10,10,20,20);
Q159. A class that is defined in another class is called ________.
- Private class
- Public class
- Inner class
- Derived class
Show answer
Answer: (c) Inner class
Q160. Which ID is transmitted between the client and the server?
- Session ID
- Network ID
- Server ID
- None of these
Show answer
Answer: (a) Session ID
Part 2: Subjective Questions
Q1. What is the typical use of a Hashtable? (2 marks)
A Hashtable is used when a program wants to store data as key-value pairs and get a value back quickly by giving its key. Keys and values are both objects, no duplicate keys are allowed, and a Hashtable is synchronized (thread-safe).
Q2. Why do we use the paintChildren() method? (2 marks)
paintChildren() tells any components contained by this component to paint themselves. It is called by paint() after paintComponent() and paintBorder(). It is suggested that you do not override or invoke this method yourself.
Q3. Write any two steps of the painting strategy. (2 marks)
- Subclass JPanel.
- Override the paintComponent(Graphics g) method (and call super.paintComponent(g) first) and do the drawing with the Graphics object.
Then add the panel to the frame's content pane.
Q4. Painting a Swing component involves three methods. Define the functionality of each, and mention which methods are not recommended to override or invoke. (5 marks)
| Method | Functionality |
|---|---|
| paintComponent(Graphics g) | Paints the component itself: first the background (if opaque), then the custom painting. This is the method we override. |
| paintBorder(Graphics g) | Tells the component's border (if any) to paint. |
| paintChildren(Graphics g) | Tells any components contained by this component to paint themselves. |
paint() calls them in the order paintComponent(), paintBorder(), paintChildren(). We override only paintComponent(). paintBorder() and paintChildren() are not recommended to be overridden or invoked directly, and calling paint() or paintComponent() ourselves is also not recommended (use repaint() instead).
Q5. paintBorder(), paintComponent() and paintChildren() are used in Java painting. Write their order of execution. For a JPanel with a triangle drawn on it and a button painted on it, which paint methods are called and in what order? (3 marks)
- paintComponent() is called first: it paints the panel background and our custom drawing (the triangle).
- paintBorder() is called next: it paints the border of the panel, if it has one.
- paintChildren() is called last: it makes the contained components, here the button, paint themselves.
So the order is paintComponent() → paintBorder() → paintChildren().
Q6. Write three functions (tasks) of the paintComponent() method. (3 marks)
- It paints the background of the component first (when the component is opaque).
- It then performs the custom painting that we write using the Graphics object (shapes, text, images).
- Calling super.paintComponent(g) at its start clears whatever was painted earlier, so the new drawing starts fresh.
Note: Model answer built from the lesson description of paintComponent().
Q7. Why is calling paintComponent() directly not recommended? (2 marks)
Painting is managed by the system. Calling paintComponent() (or paint()) directly is not recommended because such code may be invoked at a time when it is not appropriate to paint, for instance before the component is visible or before it has access to a valid Graphics object. To refresh a component we call repaint() and let the system call paint.
Q8. What is the difference between the paint() and repaint() methods? (3 marks)
- paint(): the method where the actual painting occurs. To change the way a component is drawn we override it (in Swing, paintComponent()). The Java API warns never to call it directly.
- repaint(): tells the component that it should call its paint method as soon as it can. This is the method we call to force a component to update itself.
Q9. Differentiate between named and anonymous objects. Give an example with code. (5 marks)
An anonymous object is used when there is just a one-time use of the object. When the object is needed repeatedly, we keep a named reference and use it again and again.
class Student {
void display() { System.out.println("I am a student"); }
}
public class NamedAnon {
public static void main(String[] args) {
Student s = new Student(); // named object: reference s
s.display();
s.display(); // reused again and again
new Student().display(); // anonymous object: no reference, used once
}
}In the same way, String s = "hello"; System.out.println(s); uses a named reference, while System.out.println("hello"); uses an anonymous string.
Q10. How was the problem of implementing all the methods of an interface solved? What is the disadvantage of interface implementation? (3 marks)
A class that implements an interface must give a body to every method of that interface, even the ones it does not need (for example WindowListener has seven methods). The problem was solved with adapter classes: they implement the listener interface and give empty bodies to all its methods, so we extend the adapter and override only the methods we need.
Q11. What will happen if a class implements the WindowListener interface but provides definitions of only one (or not all) of its methods? (3 marks)
WindowListener has seven methods. A class that implements it must define all of them; otherwise the class does not compile as a concrete class (it would have to be declared abstract, and then no object of it can be created). To avoid writing empty methods we can extend WindowAdapter and override only windowClosing().
Q12. Why does ActionListener never have an adapter class? (3 marks)
An adapter class is useful only for listener interfaces that have more than one method. ActionListener has just one method, actionPerformed(), so a class can implement it directly and nothing is left to be skipped.
Q13. What problem can you face when using an adapter class, and how will you handle it? (3 marks)
An adapter is a class, and Java has single inheritance. If our class already extends another class (for example JFrame), it cannot also extend the adapter.
Solution: write the handler as an inner class or an anonymous inner class that extends the adapter, and register an object of it, for example frame.addWindowListener(new WindowAdapter() { ... });.
Q14. Rewrite an event-handling class that implements MouseMotionListener and WindowListener so that it uses adapter classes instead (it shows the mouse coordinates in a label and shows "Good Bye" when the window closes). (5 marks)
Extend MouseMotionAdapter, override only mouseMoved(), and use an anonymous WindowAdapter for the window event:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventsEx extends MouseMotionAdapter { // adapter, not interface
JFrame frame;
JLabel coordinates;
public void initGUI() {
frame = new JFrame();
Container cont = frame.getContentPane();
cont.setLayout(new BorderLayout());
coordinates = new JLabel();
cont.add(coordinates, BorderLayout.NORTH);
frame.addMouseMotionListener(this); // registering handler
frame.addWindowListener(new WindowAdapter() { // anonymous inner class
public void windowClosing(WindowEvent we) {
JOptionPane.showMessageDialog(null, "Good Bye");
System.exit(0);
}
});
frame.setSize(350, 350);
frame.setVisible(true);
}
public void mouseMoved(MouseEvent me) { // only the needed method
coordinates.setText("X=" + me.getX() + " Y=" + me.getY());
}
public EventsEx() {
initGUI();
}
public static void main(String[] args) {
EventsEx ex = new EventsEx();
}
}Q15. Write a program that extends an adapter class for the mouse click event. When the mouse is clicked in the area of the frame, it should show a dialog box with the message "mouse clicked". (5 marks)
import java.awt.event.*;
import javax.swing.*;
public class ClickEx extends MouseAdapter { // adapter class
JFrame frame;
public void initGUI() {
frame = new JFrame();
frame.addMouseListener(this); // register with the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 350);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent me) { // only this method
JOptionPane.showMessageDialog(null, "mouse clicked");
}
public ClickEx() {
initGUI();
}
public static void main(String[] args) {
new ClickEx();
}
}Q16. Write the MouseListener code for "Mouse Clicked" and "Mouse Exited". (5 marks)
MouseListener has five methods, so all five must be defined:
import java.awt.event.*;
import javax.swing.*;
public class MouseDemo implements MouseListener {
public void mouseClicked(MouseEvent me) {
System.out.println("Mouse Clicked");
}
public void mouseExited(MouseEvent me) {
System.out.println("Mouse Exited");
}
// the interface forces us to define the other three as well
public void mousePressed(MouseEvent me) { }
public void mouseReleased(MouseEvent me) { }
public void mouseEntered(MouseEvent me) { }
}Q17. Write the names of five event listener interfaces. Which interfaces are needed to handle ActionEvent, KeyEvent, MouseEvent and WindowEvent? (3 marks)
- ActionEvent → ActionListener
- KeyEvent → KeyListener
- MouseEvent → MouseListener (and MouseMotionListener for moved/dragged)
- WindowEvent → WindowListener
- Others: ItemListener, TextListener, FocusListener, ComponentListener.
Q18. Write a method (program) that gets the coordinates of the mouse when it moves and displays them on a JLabel. (5 marks)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseCoordinates extends JFrame implements MouseMotionListener {
JLabel coordinates = new JLabel("Move the mouse"); // shows x, y
public MouseCoordinates() {
setLayout(new BorderLayout());
add(coordinates, BorderLayout.NORTH);
addMouseMotionListener(this); // register handler
setSize(350, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void mouseMoved(MouseEvent me) { // called while moving
coordinates.setText("X = " + me.getX() + ", Y = " + me.getY());
}
public void mouseDragged(MouseEvent me) { } // required, left empty
public static void main(String[] args) {
new MouseCoordinates();
}
}Q19. What is the difference between mouseDragged and mouseMoved? (2 marks)
- mouseMoved(): called when the mouse moves over the component with no button pressed.
- mouseDragged(): called when the mouse moves while a button is held down.
- Both are declared in the MouseMotionListener interface.
Q20. Write a GUI program that shows two buttons, "Button 1" and "Button 2". When we click any button, their texts are swapped with each other. (5 marks)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwapButtons implements ActionListener {
JFrame frame;
JButton b1, b2;
public void initGUI() {
frame = new JFrame("Swap");
Container cont = frame.getContentPane();
cont.setLayout(new FlowLayout());
b1 = new JButton("Button 1");
b2 = new JButton("Button 2");
b1.addActionListener(this); // register handler
b2.addActionListener(this);
cont.add(b1);
cont.add(b2);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) { // either button clicked
String temp = b1.getText();
b1.setText(b2.getText());
b2.setText(temp);
}
public static void main(String[] args) {
new SwapButtons().initGUI();
}
}Q21. Write a simple Java program to show event handling. (5 marks)
Event handling is a three-step process: (1) create the event generator (the button), (2) write the event handler (a class implementing ActionListener), (3) register the handler with the generator.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo implements ActionListener {
JFrame frame;
JButton button;
public void initGUI() {
frame = new JFrame("Events"); // container
button = new JButton("Click me"); // 1. event generator
button.addActionListener(this); // 3. register the handler
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(button);
frame.setSize(250, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) { // 2. event handler
JOptionPane.showMessageDialog(null, "Button clicked");
}
public static void main(String[] args) {
new ButtonDemo().initGUI();
}
}Q22. A button can generate events and we have built an object that can handle them. Have we completed all the steps needed to handle the button's events? (3 marks)
No. There are three steps: the event generator, the event handler, and registering the handler with the generator using addActionListener(). Creating the button and the handler object is not enough; without registration the button does not know whom to notify and nothing happens when it is clicked.
Q23. How can a GUI component handle its own events? (3 marks)
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener, for example a frame class implements MouseMotionListener and calls addMouseMotionListener(this).
Q24. Why do we use serialization? What is the difference between serialization and deserialization? (3 marks)
- Serialization turns an object into a stream of bytes so it can be sent to a stream (a file or a network), for example to pass objects between systems. The class must implement the Serializable interface.
- Deserialization turns the stream of bytes back into a copy of the original object. The object is read back as type Object, so down-casting is required to convert it to its real type.
import java.io.*;
class PersonInfo implements Serializable {
String name;
transient String phoneNum; // skipped during serialization
}
public class SerialDemo {
public static void main(String[] args) throws Exception {
PersonInfo p = new PersonInfo();
p.name = "Ali";
p.phoneNum = "0300";
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("p.ser"));
out.writeObject(p); // serialization
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("p.ser"));
PersonInfo q = (PersonInfo) in.readObject(); // deserialization + cast
in.close();
System.out.println(q.name + " " + q.phoneNum); // Ali null
}
}Q25. We cannot pass objects from one system to another directly, but we want to send objects. What modification do we need in our class? (3 marks)
Make the class implements Serializable, so that its objects can be written to an ObjectOutputStream (or a socket's stream) and read back with an ObjectInputStream on the other side. Serializable is a marker interface with no methods to implement.
Q26. How can we prevent serialization of a field? (5 marks)
Often there is no need to serialize sockets, streams and database connections because they do not represent the state of the object, only connections to external resources. Mark such a field with the transient keyword. Transient fields are returned as null (or the default value) when the object is read back.
import java.io.*;
class Address implements Serializable {
String street;
String city;
transient String houseNo; // not serialized, comes back as null
}Q27. Differentiate between an array and an ArrayList. What is the advantage of a collection over an array? (2 marks)
- Array: fixed size, set when it is created; can hold primitives or objects.
- ArrayList: a resizable array. It replaces the old Vector, grows or shrinks as elements are added or removed, and stores objects.
- Advantage of a collection: you do not need to know the eventual size of the collection in order to add objects to it.
Q28. Write the syntax to load the Oracle driver. (2 marks)
Class.forName("oracle.jdbc.driver.OracleDriver");(For MS Access the JDBC-ODBC driver that comes with J2SE is loaded with Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");.)
Q29. What will happen if an image is drawn outside the window coordinates? (2 marks)
Nothing is shown for the part that lies outside the visible area: it is clipped. No error or exception occurs; the image simply is not visible unless the coordinates are brought back inside the window.
Q30. How do we process the results of an SQL query? How can you retrieve data from a ResultSet? (5 marks)
- The ResultSet keeps the data in the form of a table (rows and columns) and provides getXXX() methods that take a column index or name.
- The first row has index 1, not 0.
- next() returns true or false depending on whether another row exists, and moves the cursor to it. Always call next() at least once before reading.
ResultSet rs = stmt.executeQuery("SELECT * FROM Person");
while (rs.next()) {
String name = rs.getString("name"); // by column name
String add = rs.getString(2); // or by column index
}Q31. Write a while loop to retrieve the values of a given table (columns) using a ResultSet. (5 marks)
Example for a table Person(name, address, phone):
ResultSet rs = stmt.executeQuery("SELECT * FROM Person");
while (rs.next()) {
String name = rs.getString(1);
String address = rs.getString(2);
String phone = rs.getString(3);
System.out.println(name + " " + address + " " + phone);
}Note: The exact table was shown only in the paper; use the column count and types of the given table.
Q32. A column has index 5 in the ResultSet. Which statement retrieves its value? How can you get the name of a specific column of the ResultSet? (3 marks)
String name = rs.getString(5);
The column name comes from the ResultSetMetaData:
ResultSetMetaData rsmd = rs.getMetaData(); String colName = rsmd.getColumnName(5);
Q33. Which method of ResultSetMetaData returns the suggested label of a column for printouts? (2 marks)
getColumnLabel() returns the suggested column label for printouts.
Q34. Discuss any three methods of ResultSetMetaData. (3 marks)
getColumnCount()returns the number of columns in the result set.getColumnDisplaySize(int)returns the maximum width of the specified column in characters.getColumnType(int)returns the SQL type of the column, to compare against the types in java.sql.Types.- Others: getColumnName(int), getColumnLabel(int), getColumnTypeName(int).
Q35. Write code using a ResultSetMetaData object to display the name, the database type name and the width of the second column. (5 marks)
import java.sql.*;
public class Meta2 {
static void show(Statement stmt) throws SQLException {
ResultSet rs = stmt.executeQuery("SELECT * FROM Table2");
ResultSetMetaData rsmd = rs.getMetaData();
String colName = rsmd.getColumnName(2); // name of 2nd column
String typeName = rsmd.getColumnTypeName(2); // database type name
int width = rsmd.getColumnDisplaySize(2); // width of 2nd column
System.out.println(colName + " " + typeName + " " + width);
}
}Note: The shared answer used getColumnType(), which returns the numeric SQL type; the database type name is returned by getColumnTypeName().
Q36. How do we create a DatabaseMetaData object? What is the process of getting metadata in Java? (2 marks)
A DatabaseMetaData object is obtained from the Connection object, and a ResultSetMetaData object from the ResultSet:
Connection con = DriverManager.getConnection(url, usr, pwd);
DatabaseMetaData dbMetaData = con.getMetaData(); // about the database
ResultSet rs = stmt.executeQuery("SELECT * FROM Person");
ResultSetMetaData rsmd = rs.getMetaData(); // about the result setQ37. Write a program that prints the database version, the driver name, whether the database is read only, and then the ids of the students in the table "Students". (5 marks)
import java.sql.*;
public class DbInfo {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:personDSN");
DatabaseMetaData md = con.getMetaData();
System.out.println("Database version: " + md.getDatabaseProductVersion());
System.out.println("Database Driver: " + md.getDriverName());
System.out.println("Read only: " + md.isReadOnly());
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Students");
while (rs.next()) {
System.out.println(rs.getInt(1)); // student id
}
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}Note: The JDBC-ODBC bridge (sun.jdbc.odbc) was used in the VU handouts; it was removed from Java 8 onwards.
Q38. What is the difference between executeQuery(sql) and executeUpdate(sql)? Why is executeUpdate() used? Which methods are used to execute SQL queries? (3 marks)
- executeQuery(sql): used for SQL SELECT queries; returns a ResultSet object with the results.
- executeUpdate(sql): used for INSERT, UPDATE and DELETE statements (and DDL); returns an int, the number of rows affected.
- There is also execute(sql), which can run any SQL statement.
ResultSet rs = stmt.executeQuery("SELECT * FROM sometable");
int count = stmt.executeUpdate("INSERT INTO tablename (columnNames) VALUES (values)");Q39. Write the syntax of an SQL UPDATE query in JDBC. Write the code that changes the name of the student to "Naeem Khan" where the id is 10. (3 marks)
import java.sql.*;
public class UpdSql {
static void change(Connection con) throws SQLException {
Statement stmt = con.createStatement();
String sql = "UPDATE student SET name = 'Naeem Khan' WHERE id = 10";
int count = stmt.executeUpdate(sql); // rows affected
}
}Note: The shared answer under this question showed an INSERT statement; an update uses UPDATE ... SET ... WHERE ..., sent with executeUpdate().
Q40. Write java code that updates the name Ali to Ahmed in the 5th row (column name sname). Write only the necessary code. (3 marks)
Using an updatable, scrollable ResultSet:
import java.sql.*;
public class UpdRow {
static void change(Connection con) throws SQLException {
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
rs.absolute(5); // go to the 5th row
rs.updateString("sname", "Ahmed"); // Ali -> Ahmed
rs.updateRow(); // write it to the database
}
}Note: An equally valid answer is an SQL UPDATE sent with executeUpdate().
Q41. Write the code of a PreparedStatement that inserts values into the student table (columns student id and student name). (5 marks)
import java.sql.*;
public class PrepIns {
static void add(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student (studentId, studentName) VALUES (?, ?)");
ps.setInt(1, 10); // first ?
ps.setString(2, "Naeem Khan"); // second ?
int count = ps.executeUpdate();
}
}Q42. Why do we use a PreparedStatement object? (3 marks)
- It is used for executing precompiled SQL statements and passing different parameters to them.
- The statement is sent to the database in a standard form for compilation before it is used, so repeated execution is faster.
- The marked parameters (?) are replaced each time with setter methods such as setString() and setInt().
- It is created with the prepareStatement() method of the Connection class.
PreparedStatement pStmt = con.prepareStatement("UPDATE tableName SET columnName = ? WHERE columnName = ?");
pStmt.setString(1, stringValue);
pStmt.setInt(2, intValue);Q43. Describe the types of statements used in JDBC. (3 marks)
- Statement: executes simple SQL statements with no parameters.
- PreparedStatement: executes precompiled SQL statements, with ? parameters.
- CallableStatement: executes stored procedures in the database.
Q44. Write the four types of JDBC drivers. (3 marks)
| Type | Name |
|---|---|
| Type 1 | JDBC-ODBC bridge |
| Type 2 | Native-API / partly Java driver |
| Type 3 | Net-protocol / all-Java driver |
| Type 4 | Native-protocol / all-Java driver (best performance) |
Q45. What is the JDBC-ODBC bridge (a Type 1 driver)? Why is it called so? Why is a Type 2 driver more efficient than the bridge? (3 marks)
- The JDBC-ODBC bridge is a Type 1 driver that lets Java programs reach any database that has an ODBC driver (such as MS Access). It is called a bridge because it translates JDBC calls into ODBC calls, so the call goes JDBC → ODBC → database.
- A Type 2 driver converts JDBC calls directly into the database's own native API calls, skipping the extra ODBC layer, so there is less translation and it is faster.
Note: Model answer from the driver-type descriptions.
Q46. How do we load a driver and define a connection URL for JDBC? Write the code to connect to an MS Access database using the connection URL string conURL. (5 marks)
- Load a driver suitable for the database. For MS Access the JDBC-ODBC driver comes with J2SE; for Oracle the driver must be downloaded.
- Define the connection URL: with the JDBC-ODBC driver it needs a DSN (Data Source Name) created earlier, e.g. personDSN.
- Get the connection from DriverManager.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // MS Access
// Class.forName("oracle.jdbc.driver.OracleDriver"); // Oracle
String conURL = "jdbc:odbc:personDSN";
Connection con = DriverManager.getConnection(conURL);Q47. Why is the connection string called a connection URL? Explain by relating it to a browser URL. (3 marks)
A browser URL (like http://www.vu.edu.pk) contains the protocol and the address of a web server. In the same way the connection URL jdbc:odbc:personDSN contains the protocol (jdbc), the sub-protocol (odbc) and the address of the database (the DSN). It tells the DriverManager where the database is, just as a URL tells the browser where the page is.
Q48. For a company named ABC, what are the basic steps to communicate with their database using JDBC in Java? (Write the complete steps for making a connection and getting data from a table.) (5 marks)
- Import the java.sql package.
- Load the driver.
- Define the connection URL.
- Establish the connection.
- Create a Statement.
- Execute the query.
- Process the results.
- Close the connection.
import java.sql.*;
public class JdbcEx {
public static void main(String[] args) {
try {
// 1. import java.sql.* (done above)
// 2. load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 3. define the connection URL
String conURL = "jdbc:odbc:personDSN";
// 4. establish the connection
Connection con = DriverManager.getConnection(conURL);
// 5. create a statement
Statement stmt = con.createStatement();
// 6. execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM Person");
// 7. process the results
while (rs.next()) {
String name = rs.getString("name"); // by column name
String add = rs.getString(2); // by column index
System.out.println(name + " " + add);
}
// 8. close the connection
con.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}Q49. What does the code ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE do when passed to prepareStatement()? (3 marks)
It creates a scrollable and updatable ResultSet: the cursor can move forward and backward and jump to a row (absolute(), previous()), TYPE_SCROLL_INSENSITIVE means it does not see changes made by others after it was opened, and CONCUR_UPDATABLE allows rows to be updated, inserted or deleted through the ResultSet.
import java.sql.*;
public class ScrollEx {
static ResultSet open(Connection con) throws SQLException {
PreparedStatement pStmt = con.prepareStatement(
"SELECT * FROM Person",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pStmt.executeQuery();
rs.absolute(5); // jump to 5th row
rs.previous(); // allowed: scrollable
return rs;
}
}Q50. Write three limitations of the default ResultSet. If we use previous() with it, why is an exception thrown? (3 marks)
- It is forward-only: the cursor moves only from the first row towards the last.
- It is read-only: its rows cannot be updated.
- It is not scrollable, so we cannot jump to a particular row.
previous() needs a scrollable ResultSet. With the default (TYPE_FORWARD_ONLY) ResultSet it throws an SQLException; create the statement with TYPE_SCROLL_INSENSITIVE (and CONCUR_UPDATABLE for updates) to use it.
Q51. Which command or method is used to move to a specific row in a ResultSet? (2 marks)
rs.absolute(n) moves the cursor to row number n (it needs a scrollable ResultSet). Others are relative(int), first(), last(), next() and previous().
Q52. Why do we have the getMaxRows() and setMaxRows() methods? (2 marks)
setMaxRows(int) limits the maximum number of rows that a ResultSet can contain for a Statement, and getMaxRows() returns that current limit (0 means no limit). They are useful to avoid fetching a very large result.
Q53. State one advantage and one disadvantage of a RowSet compared with a normal ResultSet. Which object allows us to work with a closed connection? (3 marks)
- Advantage: a (cached) RowSet is a disconnected, scrollable and updatable JavaBean, so we can keep working with its data after the connection is closed.
- Disadvantage: the data is held in memory, so large results use a lot of memory and the data can go stale; changes must be synchronized with the database.
Note: Model answer; the original paper options were not shown.
Q54. Write the steps of making a simple client in a Java client-server application. (5 marks)
- Import the required packages (java.net.* and java.io.*).
- Connect/open a socket with the server: Socket s = new Socket("serverName", serverPort); (use "localhost" when client and server run on the same machine).
- Get the I/O streams of the socket (an InputStream wrapped in InputStreamReader and BufferedReader for reading, and an OutputStream wrapped in a PrintWriter, with true for auto-flush, for writing).
- Send/receive messages: pw.println("hello world"); String recMsg = br.readLine();
- Close the socket: s.close();
import java.net.*;
import java.io.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 2222); // 2. connect to server
BufferedReader br = new BufferedReader(
new InputStreamReader(s.getInputStream())); // 3. input stream
PrintWriter pw = new PrintWriter(s.getOutputStream(), true); // output stream
pw.println("hello world"); // 4. send
String recMsg = br.readLine(); // 4. receive
System.out.println(recMsg);
s.close(); // 5. close
}
}Q55. Complete the code for establishing the connection and sending/receiving messages on the server side. The client sends two numbers in a single string to the server and the server sends back their sum in a single string. (5 marks)
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
public class SumServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(2222); // listen on port 2222
Socket s = ss.accept(); // wait for a client
BufferedReader br = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
String line = br.readLine(); // e.g. "10 20"
StringTokenizer st = new StringTokenizer(line);
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
pw.println(String.valueOf(a + b)); // send the sum back
s.close();
ss.close();
}
}Steps: create a ServerSocket on a port, accept() a client, get the streams, read the string, split and add the numbers, send the result, close.
Q56. What is a port? How is it useful in a network? What is the difference between a client socket and a server socket? (5 marks)
- A port is a transport address to which processes can listen for connection requests. It lets one machine run many network services at the same time, because each service uses its own port number.
- TCP and UDP are the protocols available; sockets in this course use TCP.
- Socket (client): created with new Socket(host, port); it actively connects to a server and gives input/output streams for communication.
- ServerSocket (server): created with new ServerSocket(port); it waits on a port and accept() returns a Socket for each client that connects.
Q57. What is the difference between an applet and an application? (5 marks)
- Applets are small programs, applications are larger programs.
- An applet has no main() method; an application starts execution from main().
- Applets run in a browser window or in the appletviewer; applications run on their own.
- Applets are designed for client-side programming and run under security restrictions; applications are designed to work with the client as well as the server.
- Both are platform independent and byte-code based.
Q58. Write the names of four applet life cycle methods. What does start() do and when is it used? What is the role of paint()? (4 marks)
init(): called once when the applet is loaded; initializes the applet.start(): called after init() and every time the applet becomes visible again (for example after the browser page is revisited or the applet is restored); it starts the applet running.stop(): called when the applet is no longer visible (minimized or the page is left); stops running.destroy(): called once before the applet is unloaded; final cleanup.paint(Graphics g): called whenever the applet's display needs to be drawn (also after repaint()).
Q59. Write the code (and the HTML) for an applet that displays a message. (5 marks)
import java.awt.*;
import javax.swing.*;
public class HelloApplet extends JApplet {
public void paint(Graphics g) {
super.paint(g);
g.drawString("Hello Applet", 50, 50);
}
}HTML page that runs it:
<html> <body> <applet code="HelloApplet.class" width="300" height="200"> </applet> </body> </html>
Run it with appletviewer HelloApplet.html or in a browser that supports applets.
Q60. What happens if we do not write the code attribute in the applet tag? (2 marks)
The applet will not run. The code attribute (together with width and height) tells the browser which applet class to load; without it there is no class to start.
Q61. Can applets communicate with each other? (3 marks)
Applets running in the same virtual machine can communicate. If they are of the same class they can share static variables; if they are of different classes, each needs a reference to the same class holding the static variables. An applet can also get references to all other applets on the same page using getApplets() of java.applet.AppletContext and then use their public members.
Q62. As a GUI developer, what should you know about top-level containers and general purpose containers? Write any five GUI components. (5 marks)
- A container is a collection of related components that allows other components to be nested inside it. In a JFrame application we attach components to the content pane.
- Top-level containers (JFrame, Dialog, Applet) can contain other containers as well as basic components; our application uses one of them.
- General purpose containers (JPanel, ToolBar, ScrollPane) are used to collect basic components and must be added to a top-level container; they cannot exist alone.
- Five GUI components: JButton, JLabel, JTextField, JCheckBox, JRadioButton (also JComboBox, JList, JTextArea).
Q63. Name the Component subclasses that support painting. (2 marks)
The Canvas, Frame, Panel and Applet classes support painting (in Swing mostly JPanel is used). Canvas is the subclass that is specially meant for drawing and painting.
Q64. Write three differences between an abstract class and an interface. What does it mean for a class or method to be abstract? (5 marks)
- Meaning of abstract: an abstract class defines only part of an implementation, so it cannot be instantiated; a class with an abstract method (no body) must be declared abstract, but a class can be declared abstract even without any abstract method. A subclass that overrides all abstract methods becomes concrete; otherwise it must also be abstract. A reference of an abstract class can point to an object of a concrete subclass.
- Interface vs abstract class: an interface has only method prototypes (no definitions) while an abstract class may also contain method definitions and instance variables.
- Use an interface when the behaviour of the sub-types is totally different; use an abstract class when it is partly common and partly different.
- A class can implement many interfaces (a form of multiple inheritance) but extend only one class.
Q65. What is the difference between a static and a non-static inner class? Can an anonymous class both extend a class and implement an interface? (3 marks)
- A non-static inner class has object instances associated with an instance of its outer class. A static inner class does not need an instance of the outer class.
- An anonymous class can either extend a class or implement an interface, but it cannot do both.
Q66. If a method is declared protected, where can it be accessed? (2 marks)
It can be accessed by the class itself, by its subclasses, and by other classes in the same package.
Q67. Is Iterator a class or an interface? What is its use? (2 marks)
Iterator is an interface used to step through the elements of a collection one by one (hasNext(), next(), remove()).
Q68. Which two Java collections would you use for indexed search? (2 marks)
ArrayList (and Vector), which are sequence-based collections that give access to an element by its index with get(index).
Q69. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? What is the difference between character-oriented and byte-oriented streams? (3 marks)
- Reader/Writer is character-oriented; InputStream/OutputStream is byte-oriented. InputStream and OutputStream are the abstract classes at the top of the byte streams, Reader and Writer at the top of the character streams.
- A byte stream accesses a file byte by byte and is suitable for any kind of file, but not quite for text: if a character takes two bytes (Unicode) the byte stream treats them separately and you must do the conversion yourself.
- A character stream reads a file character by character and needs the file's encoding to work properly.
Q70. Differentiate between PrintWriter and BufferedReader with respect to their data conversion abilities. Name an easier-to-use alternative to byte streams and say how it helps. (5 marks)
- PrintWriter converts primitive values and objects into text (print/println), so we can write an int or double directly.
- BufferedReader only reads text and returns Strings (readLine()); any conversion to int or double must be done by us, e.g. with Integer.parseInt().
- Alternative to byte streams: character streams (FileReader, FileWriter, BufferedReader, PrintWriter). They deal with characters and text directly, so reading and writing text is easier, and buffering makes it efficient.
import java.io.*;
public class PwBr {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
pw.println(25); // int converted to text automatically
pw.println(3.5); // double converted to text
pw.close();
BufferedReader br = new BufferedReader(new FileReader("out.txt"));
String line = br.readLine(); // always a String
int n = Integer.parseInt(line); // conversion done by us
br.close();
}
}Q71. Write a method (program) that displays the string "I am student" at a random location on a screen of size 1200 x 1000. (5 marks)
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class RandomStringPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random r = new Random();
int x = r.nextInt(1200); // 0 .. 1199
int y = r.nextInt(1000); // 0 .. 999
g.drawString("I am student", x, y);
}
}Q72. Write a method that draws a triangle using lines. Each time the triangle is displayed it should be at a different location. (5 marks)
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class TrianglePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random r = new Random();
int x = r.nextInt(300); // new location each time
int y = r.nextInt(300);
g.drawLine(x, y + 60, x + 60, y + 60); // base
g.drawLine(x, y + 60, x + 30, y); // left side
g.drawLine(x + 60, y + 60, x + 30, y); // right side
}
}Q73. Write code that draws a pink rectangle and the string "i am a student". (5 marks)
import java.awt.*;
import javax.swing.*;
public class PinkRect extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); // clear old painting
g.setColor(Color.PINK);
g.fillRect(50, 50, 150, 80); // pink rectangle
g.setColor(Color.BLACK);
g.drawString("i am a student", 60, 100); // text
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics");
frame.getContentPane().add(new PinkRect());
frame.setSize(300, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}Q74. Write the code to draw an unfilled circle. (3 marks)
import java.awt.*;
import javax.swing.*;
public class CirclePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawOval(50, 50, 100, 100); // unfilled circle: width = height
}
}drawOval() draws only the outline; use fillOval() for a filled one. The circle has equal width and height.
Q75. Write the code that draws the word "java" at 100 different locations. (5 marks)
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class JavaWordPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Random r = new Random();
for (int i = 0; i < 100; i++) { // 100 different locations
g.drawString("java", r.nextInt(400), r.nextInt(400));
}
}
}Q76. Write the code of a transparent triangle and enclose it with an orange circle, using paintComponent(). (5 marks)
import java.awt.*;
import javax.swing.*;
public class TransparentTriangle extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xs = {100, 200, 150};
int[] ys = {200, 200, 100};
g.setColor(new Color(0, 0, 255, 80)); // blue, alpha 80 = transparent
g.fillPolygon(xs, ys, 3); // triangle
g.setColor(Color.ORANGE);
g.drawOval(80, 70, 140, 140); // orange circle around it
}
}Note: The wording of the original question was unclear; this draws a transparent (alpha) blue triangle and an orange circle outline around it.
Q77. To develop and execute a Java program, it goes through how many phases? Which is the 2nd phase?
Five phases: edit, compile, load, verify and execute. The 2nd phase is compiling (the compiler turns the source code into bytecode).
Q78. To compare the values of two strings, which must be used?
The equals() method (the == operator compares addresses, not values).
Q79. Which object is used for sharing resources among different servlets of the same application?
ServletContext (ServletConfig is specific to one servlet).
Q80. Moving a session from one server to another in case of server failure is known as?
Session migration.
Q81. HTTP is a ________ protocol.
Both connectionless and stateless.
Q82. FTP (File Transfer Protocol) works on which port?
Port 21.
Q83. HTTP works on which port?
Port 80.
Q84. Which block always executes whether an exception occurs or not?
The finally block.
Q85. Event handling is a ________ step process.
A three-step process: create the event generator, write the event handler, and register the handler with the generator.
Q86. Which is NOT an event handling step: create the event handler, register it with the generator, or publish the event?
"Publish event" is not a step. The steps are creating the event source, creating the handler, and registering the handler.
Q87. Which of the following is NOT true for Java inner classes?
That inner classes are "generally used as public utility classes" is not true; inner classes are normally used to help their outer class (for example as event handlers) and are not general public utilities.
Q88. Which statement is true about a Java anonymous inner class?
All of these: it is difficult to understand, it has no name, and it is much shorter. (Answer: all of the given options.)
Q89. Running ExceptionExample without command-line arguments, where main prints args[0], gives which exception?
ArrayIndexOutOfBoundsException (array index out of bound exception), because args is empty.
Q90. Which statement is true regarding the paintComponent() method?
It first paints the background and then performs the custom painting.
Q91. Which statement is NOT true about paintComponent()?
"Tells the component's border (if any) to paint" is not true: that is the job of paintBorder().
Q92. Interface imposes structure ________ on any class that uses the interface.
Design (the interface forces a design/structure on the implementing classes).
Q93. An object of the Student class is created in Test.java with s2->setName("Aslam"). What is the error?
Java has no arrow operator for members. The dot operator is used: s2.setName("Aslam");
Q94. Which driver type has better performance than the others?
Type 4 (native-protocol / all-Java driver).
Q95. Bytecodes are put in memory by ________.
The class loader.
Q96. Bytecodes are created and stored on disk by ________.
The compiler.
Q97. Write the correct syntax to make the PersonInfo class serializable.
public class PersonInfo implements Serializable { /* class body */ }
Q98. Timer t = new Timer(1000, this); t.start(); The code fires an action event once per ________.
Second (the Timer constructor takes the delay in milliseconds, and 1000 ms = 1 second).
Q99. The Timer class constructor requires time in ________.
Milliseconds.
Q100. CmdArgs is compiled and "java CmdArgs CS506" is run, where main prints "First argument" + args[0]. What is the output?
First argumentCS506 (no space is added between the text and the argument).
Note: The shared answer only said CS506; the program prints the text and the argument joined. Checked by running it.
Q101. Which classes provide definitions (empty bodies) for all methods of their listener interface? (Java defines these for listener interfaces having more than one method.)
Adapter classes.
Q102. To make sure array accesses touch only the memory allocated to them, the JVM does checking at ________.
Run time (dynamic checking).
Q103. A HashMap is to store Teacher objects as values with their CNIC strings as keys. Which syntax is correct?
HashMap<String, Teacher> h = new HashMap<String, Teacher>();
Q104. Which of the following classes can be instantiated?
A concrete class (an abstract class or interface cannot).
Q105. Which object is passed as an argument to the paintComponent() method?
A Graphics object.
Q106. double a = 9.5; int b = (int) a; Which conversion is applied?
Down-casting (narrowing) of a to b's type; the fraction is lost.
Q107. int a = 20; double b = a; Which conversion is applied?
Up-casting (widening) of a to b's type; done automatically.
Q108. Employee is a super class and Teacher a child class. Employee e = new Teacher(); Which conversion is applied?
Up-casting: the child object is treated as its parent type.
Note: The shared answer said "downcasting teacher to employee type", which is wrong: assigning a child object to a parent reference is up-casting.
Q109. Which of the given will clear all the previous painting?
super.paintComponent(g)
Q110. FileReader fr = new FileReader("input.txt"); is an example of a ________.
Node stream.
Q111. Choose the correct syntax to define an interface named Speaker.
public interface Speaker { }
Q112. For each class contained in a Java source file, the compiler generates how many class files?
One class file for each class.
Q113. Which of the following methods is called only once during the life cycle of an applet?
destroy() (called once when the applet is unloaded).
Note: init() is also called only once, at loading; the shared answer was destroy().
Q114. Which statement object is used to execute a simple SQL statement?
Statement.
Q115. Which of the following features is available in Java?
Primitive data types (also single inheritance and function overriding).
Q116. A port is a ________ to which processes can listen for connection requests.
A transport address.
Q117. How many simultaneous connections can be opened using TCP and UDP ports?
128K in total in the course's answer: 64K (65,536) ports for TCP and 64K for UDP.
Note: The source answer "128K" was kept; each protocol has 65,536 port numbers.
Q118. Which statement is the correct one for the "mouse release" event in the MouseListener interface?
public void mouseReleased(MouseEvent me)
Q119. In a collection class, a ________ creates a collection with no elements.
Constructor (the default constructor).
Q120. In the context of Java graphics, which method should we override while painting (for example, to display a triangle drawn on a JPanel)?
paintComponent()
Q121. Which Java statement is used to establish the connection?
Connection con = DriverManager.getConnection(conURL);
Q122. ResultSet provides various getters to retrieve ________.
The data of the columns of the current row.
Q123. In an editor, Java programs are created and stored on/in ________.
Disk.
Q124. Which of the following is NOT a method of the ResultSet object?
executeQuery(sql) (it belongs to Statement).
Q125. DDL stands for?
Data Definition Language.
Q126. In Java, how many types of statement objects are available for sending SQL queries to the database?
Three: Statement, PreparedStatement and CallableStatement.
Q127. An applet can be defined as ________.
A small program written in Java and included in an HTML page.
Q128. setColor is a method of which class?
Graphics.
Q129. In order to include graphics in your Java program, from which class do we extend (as taught in the course)?
JPanel (subclass JPanel and override paintComponent()).
Note: Not strictly mandatory in Java (JComponent or JFrame can also be used), but this is the course's approach.
Q130. Suppose strings are stored in an ArrayList named arraylist. Write the line that gets one string element into the variable element.
String element = (String) arraylist.get(i); (a cast is needed because a raw ArrayList returns Object).
Part 3: Short Notes & Key Terms
- Bytecode
- The form into which Java source code is compiled. It is platform independent and is understood by the Java Virtual Machine (JVM).
- Phases of a Java program
- Edit, compile, load, verify, execute. The compiler creates bytecode and stores it on disk, the class loader puts it in memory, the bytecode verifier checks it does not violate security restrictions, and the JVM runs it.
- main method
- Entry point: public static void main(String[] args). Without static, without the String array or if private, the program compiles but does not run. Modifier order (static public) does not matter.
- Compile and run
- javac Test.java compiles; java Test runs (class name, no extension). One class file is generated for each class in the source file.
- Garbage collection
- Done automatically by the JVM, not by the programmer.
- Primitive vs reference types
- Primitive types are created on the stack, objects (reference types) on the heap. Strings are objects. == compares addresses of strings, equals() compares their values.
- Access modifiers
- public: everywhere. protected: same class, subclasses and same package. default (no modifier): same package. private: same class only. An overriding method may keep or widen (never narrow) the access of the overridden method.
- static
- Static members belong to the class (class variables). Static methods can only access static variables and methods.
- Casting
- Up-casting: child to parent type (Employee e = new Teacher();), done automatically. Down-casting: bigger to smaller type or parent to child type, needs an explicit cast, e.g. int b = (int) 9.5;
- Overloading vs overriding
- Overloading is resolved at compile time (compile time binding); overriding at run time (run time binding). super.toString() calls the parent's version.
- Abstract class
- Cannot be instantiated. May have fully implemented methods and instance variables. A class with an abstract method must be abstract, but an abstract class may have no abstract method. A reference of an abstract class can point to a concrete subclass object.
- Interface
- Called a pure abstract class: only method prototypes. A class implements it (an 'is a' relationship). It provides the facility of multiple inheritance in Java and imposes a design on implementing classes.
- Inner and anonymous classes
- A class defined inside another class is an inner class. An anonymous inner class has no name and either extends a class or implements an interface (not both). Non-static inner class objects are tied to an outer-class instance.
- Exceptions
- All exceptions and errors inherit from Throwable. Checked exceptions (e.g. IOException) must be handled or declared; unchecked exceptions (e.g. NullPointerException, ArrayIndexOutOfBoundsException) need not be. Any Throwable can be thrown with throw.
- try, catch, finally, throws
- Risky code goes in try, handler code in catch; finally always executes whether an exception occurs or not. A method declares exceptions it does not catch with a throws-clause.
- Collections
- Defined in java.util. ArrayList is a resizable, sequence-based replacement for Vector. A collection does not need its size in advance. Iterator is an interface used to step through a collection. HashMap/Hashtable store key-value pairs; keys and values are objects.
- Streams
- Byte-oriented streams have 'Stream' in their name (FileInputStream); character-oriented ones use Reader/Writer. By functionality they are node streams (directly connected to a source such as a file or keyboard, e.g. FileReader) and filter streams (wrap other streams, e.g. BufferedReader). Files need the java.io package.
- Serialization
- Converting an object to a stream of bytes (class implements the marker interface Serializable); deserialization re-creates the object and needs a down-cast from Object. Fields marked transient are not serialized and come back as null. Needed to move objects across tiers.
- Layout managers
- Defaults: JFrame, window and dialog (content pane) use BorderLayout (5 regions); JPanel and Applet use FlowLayout.
- AWT vs Swing
- AWT components are heavyweight; Swing components are lightweight. Top-level containers: JFrame, Dialog, Applet. General purpose container: JPanel.
- Event handling
- A three-step process: (1) event generator/source such as a button, (2) event handler implementing the listener interface, (3) registering the handler with the generator, e.g. addActionListener(this). An event is represented as an object, and the JVM keeps events in a queue.
- Listener interfaces
- ActionListener (actionPerformed), MouseListener (5 methods), MouseMotionListener (mouseMoved, mouseDragged), KeyListener, WindowListener (7 methods, e.g. windowClosing).
- Adapter classes
- Classes that give empty bodies to every method of a listener interface that has more than one method, so we override only what we need. There is none for ActionListener (it has one method).
- Painting in Swing
- Subclass JPanel and override paintComponent(Graphics g). paint() calls paintComponent(), paintBorder() and paintChildren(). Never call paint() directly; call repaint(). super.paintComponent(g) clears the previous painting. Graphics methods: setColor, drawRect, drawOval, drawLine, drawString, fillRect.
- Timer
- javax.swing.Timer(delay, listener): the delay is in milliseconds; new Timer(1000, this) fires an action event once per second.
- Applet life cycle
- init() (once, at loading) → start() (when it becomes visible) → stop() (when no longer visible) → destroy() (once, at unloading). paint() draws it. Applets have no main(), are embedded in an HTML page with the applet tag (code, width, height) and run in a browser or the appletviewer.
- JDBC steps
- Import java.sql, load the driver (Class.forName), define the connection URL, get the Connection from DriverManager, create a Statement, execute the query, process the results, close the connection.
- DSN and connection URL
- DSN = Data Source Name. With the JDBC-ODBC driver the connection URL is like jdbc:odbc:personDSN.
- JDBC driver types
- Type 1: JDBC-ODBC bridge. Type 2: native-API / partly Java. Type 3: net-protocol / all-Java (network driver). Type 4: native-protocol / all-Java (best performance).
- JDBC statements
- Statement: simple SQL. PreparedStatement: precompiled SQL with ? parameters. CallableStatement: stored procedures. executeQuery() for SELECT (returns a ResultSet); executeUpdate() for INSERT/UPDATE/DELETE (returns rows affected).
- SQL categories
- DDL (Data Definition Language): CREATE, ALTER, DROP. DML: INSERT, UPDATE, DELETE, SELECT.
- ResultSet
- Data as rows and columns; the first row and column have index 1. next() moves the cursor. The default ResultSet is forward-only and not updatable. A scrollable updatable one uses TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE and allows previous(), absolute(), updateRow(), insert and delete rows (not columns).
- Metadata
- DatabaseMetaData comes from the Connection (con.getMetaData(); isReadOnly()). ResultSetMetaData comes from the ResultSet (rs.getMetaData(); getColumnCount(), getColumnName(), getColumnLabel(), getColumnType(), getColumnTypeName(), getColumnDisplaySize()).
- Sockets and ports
- A socket is a bi-directional communication channel between hosts; a port is a transport address to which processes listen for connection requests. Client: new Socket(host, port). Server: ServerSocket + accept(). Streams are read/written and the socket is closed at the end. Java client-server uses TCP and the java.net and java.io packages.
- Well-known ports
- HTTP 80, FTP 21, TELNET 23.
- Protocol
- Defines the way and method of communication between two parties. HTTP is an application-layer, connectionless and stateless, request-response protocol.
- HTTP request and response
- A request has a request method, URI and header fields; the status code belongs to the response. Status codes: 200-299 success, 300-399 redirection, 400-499 client error, 500-599 server error.
- Session tracking
- Collecting data while a user moves between pages, since HTTP is stateless. Techniques: cookies, hidden fields, URL rewriting. A session ID is exchanged between client and server. Moving a session to another server after a failure is session migration.
- Servlets and JSP
- A JSP is translated and compiled into a servlet. JSP implicit objects include session, application, config (and request, response, out). jspInit() and jspDestroy() can be overridden but _jspService() cannot. Expression tags hold an expression that is evaluated. The error page is set with the error-page tag.
- JavaBean
- A reusable Java class: private properties accessed through getters/setters, a public zero-argument constructor, no public variables, serializable.
- Web application setup
- web.xml is the configuration file and sits in the WEB-INF folder. CATALINA_HOME is the environment variable for the root directory of Tomcat. Servlet, JSP and JSF are Java web technologies (ASP is not).
- ServletContext vs ServletConfig
- ServletContext is shared by all servlets of the application and lets them communicate with the container and share resources; ServletConfig holds one servlet's own initialization parameters.
- Threads
- Create with the Thread class (inheritance) or the Runnable interface; the work goes in run(). yield() lets other threads of the same priority execute and returns the running thread to the ready state. setPriority(Thread.MAX_PRIORITY) sets the maximum priority. Low-priority threads can suffer starvation.
- Packages
- Organize files into directories according to functionality, usability and category.
No comments:
Post a Comment
Please give us your feedback & help us to improve this site.