Which of the following is used for inheritance in java?
- Aimplements
- Bextends
- C: (colon)
- Dinherit
A class inherits from another class with the extends keyword.
Syllabus: lectures 1–18. Past-paper MCQs are shown first.Syllabus: lecture 1–18. Past paper ki MCQs pehle dikhai gayi hain.
86 MCQs · 46 short · 21 long questions · 86 MCQs from past papers86 MCQs · 46 short · 21 long sawal · 86 MCQs past papers se
Which of the following is used for inheritance in java?
A class inherits from another class with the extends keyword.
Which of the following statements is true regarding Vectors with no specified base type?
A raw Vector stores elements as Object references.
Map interface is derived from the Collection interface.
Map is a separate interface hierarchy and does not extend Collection.
A collection can store..........
Collections hold Object references, so objects of different types can be stored together.
HahMap takes key as a/an _________
HashMap keys are objects.
The collections API are defined in ______ package?
The collection classes such as ArrayList and HashMap are in java.util.
If no base type is specified in a Vector, Java will use:
A raw Vector stores elements as Object.
There are _________ types of exceptions in Java
Exceptions are divided into checked and unchecked exceptions.
Which of the following belongs to a category of checked exception?
IOException must be caught or declared, so it is checked.
Which of the following exception belongs to a category of un-checked exception?
NullPointerException is a RuntimeException, so it is unchecked.
All the exceptions and errors in java are inherited from _____ class.
Throwable is the superclass of both Exception and Error.
When defining a method, which clause is used to declare exceptions that may be thrown?
A method declares the checked exceptions it may throw with a throws clause.
Aside from the Scanner class, which of the following classes can be used for text-file file input?
BufferedReader wrapped around a FileReader reads text files line by line.
Which of the following package needs to be import while handling files?
File and stream classes are in java.io.
Which of the following stream is a filter stream?
BufferedReader wraps another stream and adds buffering, so it is a filter stream.
Based on functionality, the streams can be categorized as________
By function, streams are node streams (connected to a source/sink) or filter streams (wrapping another stream).
Which of the following stream is a Node stream?
FileWriter connects directly to a file (data source), so it is a node stream; the others are filters.
Which class can be used for text file input besides Scanner?
BufferedReader (wrapping a FileReader) reads text files line by line.
An abstract class --------------- instantiated.
Objects cannot be created from an abstract class.
In Java an abstract class cannot be sub-classed
Abstract classes are meant to be subclassed.
An instance of abstract class cannot be created.
Abstract classes cannot be instantiated.
Which of the following is called ' pure abstract class ' ?
All methods of an interface are abstract, so it acts as a pure abstract class.
Which of the following is true about abstract class?
A class may be declared abstract even if it has no abstract methods.
Which of the following feature provide facility for multiple inheritances:-
A class can implement many interfaces, which gives the effect of multiple inheritance.
An abstract class:
Objects of an abstract class cannot be created with new.
In Java, which of these classes implement the LayoutManager interface?
GridBagLayout is a real layout manager; the others do not exist in the JDK.
BorderLayout is the default layout manager for a JFrame's content pane
A JFrame's content pane uses BorderLayout by default.
Window frame and dialog use ________ as their default layout.
Window, Frame and Dialog use BorderLayout by default.
JPanel and Applet use ________ as their default layout.
JPanel and Applet use FlowLayout by default.
BorderLayout is the default layout manager for a JFrame content pane
A JFrame's content pane uses BorderLayout by default.
Which of the following is a general purpose container?
JPanel is a general-purpose container; the others are top-level containers.
Border layout divides the area into _______ regions
BorderLayout has five regions: north, south, east, west and center.
Adapter classes have been defined for listener interfaces except ______ interface.
ActionListener has only one method, so it has no adapter class.
To create DataBaseMetaData object we write following line of code
DatabaseMetaData is obtained from the Connection with getMetaData().
Which of the following methods are invoked by the AWT to support paint and repaint operations?
The AWT system itself calls paint() when a component must be drawn; programs call repaint() to request it.
Which of the following are passed as an argument to the paint ( ) method?
paint(Graphics g) receives a Graphics object used for drawing.
The code below draws a line. What color is the line? g.setColor(Color.red.green.yellow.red); g.drawLine(0, 0, 100,100);
Each static field access through an instance just reads the named constant, so the last one, Color.red, is used.
Java developed in __________
Sun released Java publicly in 1995, as the handout states.
A serializable class must implement the method(s) _________.
Serializable is a marker interface with no methods; implementing it is enough.
You can ---------to a network using sockets.
A socket gives both an input stream and an output stream, so you can read and write.
Socket is a --------------communication channel between hosts.
A socket is a two-way (bi-directional) channel between two hosts.
Event source can have --------- listeners registered on it.
Any number of listeners can be registered on one event source.
A ___________ defines the way and method of communication between two parties.
A protocol is the set of rules for how two parties communicate.
What if the main method is declared as private?
A private main compiles, but the launcher cannot use it as the entry point.
A member variable or method prefixed by the protected access modifier can be accessed:
Protected members are visible in the class, its package and its subclasses.
In Java a final class must be sub-classed before it.
A final class cannot be subclassed at all.
A top level class without any modifier is accessible to
With no modifier a class has default (package) access.
A top level class may have only the following access modifier.
A top-level class can only be public or have default access; there is no "package" keyword.
Given a one dimensional array arr, what is the correct way of getting the number of elements in arr
Arrays have a length field (not a method) giving the number of elements.
When recursive method is called to solve a problem, the method actually is capable of solving only the simpler case(s), or base case(s).
A recursive method directly solves only the base case and reduces other cases toward it.
Which of these are valid declarations for the main method?
The standard entry point is public static void main(String args[]).
In Java garbage collection is done by_______________
The JVM garbage collector frees unused objects automatically.
____________is/are the JSP Implicit Object(s).
session, application and config are all JSP implicit objects.
JavaBeans are?
A JavaBean is an ordinary Java class written to bean conventions.
An expression tag contains a scripting language expression that is evaluated.
A JSP expression is evaluated, converted to a String and inserted in the output.
A final class can't be extended.
Declaring a class final prevents subclassing.
ServletConfig defines a set of methods that a servlet uses to communicate with its servlet container.
That is the definition of ServletContext; ServletConfig carries one servlet's configuration.
A method can not be made final until whole class is made final.
Individual methods can be declared final in a non-final class.
Servlet session and JSP session have different abilities.
A JSP becomes a servlet, so session handling is the same.
Java program code is compiled into form called
javac compiles source into platform-independent bytecode for the JVM.
Overloading is _______ whereas overriding is _____
Overloaded calls are resolved by the compiler; overridden methods are chosen at run time.
Static methods only access ___
Static methods have no this reference, so they directly access only static members.
Which of the following is modifier is provided by default if no access is written explicitly?
With no access modifier, default (package) access applies.
Which of the following function will be used to register event handler with events generator (button)?
A button registers an ActionListener with addActionListener().
Which of the following function is declared in MouseMotionListener interface?
MouseMotionListener declares mouseDragged and mouseMoved; the others are in MouseListener.
Window Listener interface contains _______ methods.
WindowListener has seven methods, such as windowOpened and windowClosing.
Mouse events can be trapped for ________ GUI component.
Mouse events can be trapped for any component that inherits from Component.
Which of the following package needs to import while interacting with relational database?
JDBC classes and interfaces are in java.sql.
Which of the following method is used to execute SELECT SQL statements?
executeQuery() runs a SELECT and returns a ResultSet.
CREATE, ALTER, DROP are _________ SQL statements.
Statements that define or change table structure are Data Definition Language.
Which of the following statement object is used to execute stored procedures?
CallableStatement is used to call stored procedures.
If a super class method is protected then overriding method _________
An overriding method cannot reduce visibility, so it may be protected or public.
ODBC stands for ______________
ODBC means Open Database Connectivity.
Which of the following command is used to compile Java code?
javac compiles a source file and needs the .java extension.
Java was developed in which year?
Java was publicly released by Sun Microsystems in 1995.
Which method is invoked by AWT to support painting operations?
The AWT painting system calls paint(Graphics g) to draw a component.
A serializable class:
Serializable is a marker interface with no methods to implement.
Using sockets, you can perform which operation on a network?
A socket provides input and output streams, so both reading and writing are possible.
Which object is passed as an argument to the paint() method
paint() receives a Graphics object used for drawing.
If the main method is declared as private:
A private main compiles, but the launcher cannot use it as the entry point.
Protected access modifier allows access:
Protected members are accessible in the class, its package and its subclasses.
A final class can be extended.
A final class cannot have subclasses.
Which is the correct way to get the number of elements in an array?
Arrays have a length field, not a method.
Garbage collection in Java is performed by:
The JVM garbage collector reclaims unreferenced objects automatically.
Java program code is compiled into:
javac compiles source into bytecode stored in .class files.
Static methods can access:
Without an object, a static method can directly use only static members.
No MCQs match this filter.Is filter mein koi MCQ nahi.
What is the typical use of Hashtable?
A Hashtable stores data as key-value pairs so that a value can be stored and quickly looked up by its key (for example roll number -> student). It does not allow null keys or values and its methods are synchronized.
Why we use paintChildern( ) method?
paintChildren(Graphics g) is called by paint() to tell all components contained in this component to paint themselves. It is part of Swing’s painting process and normally should not be overridden or called directly.
Write any two steps of painting strategy.
1. Subclass JPanel (or another JComponent). 2. Override paintComponent(Graphics g), call super.paintComponent(g) and draw with the Graphics object. (To show changes later, call repaint() instead of calling paint methods directly.)
Name three paint () methods which are used to paint Swing Component.
protected void paintComponent(Graphics g) protected void paintBorder(Graphics g) protected void paintChildren(Graphics g)
Write down the code for a method of ResultMetaData object (rs) to return the database type name of second column.
ResultSetMetaData rsmd = rs.getMetaData(); String typeName = rsmd.getColumnTypeName(2); // database-specific type name of 2nd column System.out.println(typeName);
Describe types of statements used in JDBC.
1. Statement: executes simple SQL statements without parameters (created by con.createStatement()). 2. PreparedStatement: a precompiled SQL statement with ? parameters that are set by setter methods; efficient when run many times (con.prepareStatement(sql)). 3. CallableStatement: used to call stored procedures of the database (con.prepareCall("{call proc(?)}")).
You need to state the names of any four applet life cycle methods.
init(), start(), stop() and destroy() (paint() is also called to draw the applet).
Suppose we created a button in a program which can generate events and then we built an object that can handle these events. You need to state that are we completed all the necessary steps in our program for handling the events of that button.
No. The handler object (which implements ActionListener and defines actionPerformed) must also be registered with the button, e.g. button.addActionListener(handler); Without registration the button’s events never reach the handler.
Why we use serialization
Serialization converts an object (its state) into a stream of bytes so that it can be saved to a file or sent over a network (e.g. through a socket) and later re-created exactly in memory (deserialization).
Differentiate between array and ArrayList.
An array has a fixed size given at creation, can hold primitives or objects, and its size is read with length. An ArrayList is a collection class that grows or shrinks automatically, holds only objects, and provides methods such as add(), get(), remove() and size().
Write the syntax to load the oracle driver.
Class.forName("oracle.jdbc.driver.OracleDriver");
How a window handle its own events.
The window (e.g. a class that extends JFrame) implements the required listener interface itself, e.g. WindowListener or ActionListener, defines its methods, and registers itself as the listener: addWindowListener(this); Alternatively it can call enableEvents() for that event type and override the matching processXxxEvent() method.
Diff b/w array n arraylist?
An array has a fixed size and can hold primitives; an ArrayList is resizable, holds only objects and gives methods like add(), get(), remove(), size().
automatic reading in serialization?
When readObject() of ObjectInputStream is called, the system itself reads the bytes from the stream and re-creates the object (with all its serializable fields) in memory; the programmer does not read fields one by one. The returned object is of type Object, so it must be down-cast to its actual type, e.g. PersonInfo p = (PersonInfo) ois.readObject();
What is advantage of collection over array?
You do not need to know the final size of a collection before adding objects to it; it grows and shrinks automatically, and it provides ready-made methods for adding, removing, searching and iterating.
Which method of ResultSetMetaData objective is used to return the suggested value to column label for printout?
getColumnLabel(int column) returns the suggested column title for printouts and displays.
If a method is declared in protected where it can be accessible?
In the same class, in its subclasses (even in other packages) and in all classes of the same package.
What will happen if class implemented WindowListner interface and provided its definition of only one method?
WindowListener has 7 methods. If only one (e.g. windowClosing) is defined, the class does not implement the whole interface, so it does not compile unless it is declared abstract, and then no object of it can be created. All 7 methods must be defined (others may be empty), or the class should extend the WindowAdapter class and override only the needed method.
State the name of the class with which Window like container can be declared for GUI and animation based Web application. And explain it.
The applet class: JApplet (javax.swing.JApplet, a subclass of java.applet.Applet). It is a top-level, window-like container that is embedded in a web page and runs inside the browser (or appletviewer). We extend it and override its life-cycle methods init(), start(), stop(), destroy() and paint() to build GUI or animation programs.
Why is directly paintComponent () method not recommended?
Painting is managed by the system. If paintComponent() (or paint()) is called directly, it may run at a wrong time, e.g. before the component is visible or when no valid Graphics object is available. Instead repaint() should be called, which asks the system to repaint the component at a suitable time.
Write a difference between execute query sql and update query sql method?
executeQuery(sql) is used for SELECT statements and returns a ResultSet containing the result rows. executeUpdate(sql) is used for INSERT, UPDATE, DELETE (and DDL) statements and returns an int: the number of rows affected.
Is iterator class or interface? What is its use?
Iterator is an interface (java.util.Iterator). It is used to step through the elements of a collection one by one using hasNext(), next() and remove().
Discuss three method of ResultSet metadata?
getColumnCount(): returns the number of columns in the result set. getColumnName(int): returns the name of the given column. getColumnType(int): returns the SQL type of the column (from java.sql.Types). (Others: getColumnDisplaySize(int), getColumnLabel(int), getColumnTypeName(int).)
How GUI component handles its own events?
The component class implements the needed listener interface (e.g. ActionListener), defines its method, and registers itself as its own listener, e.g. addActionListener(this); (Another way is enableEvents() and overriding processXxxEvent().)
Can an anonymous class be declared as implementing an inheritance and extending a class
No. An anonymous class can either extend one class or implement one interface, but it cannot do both (and cannot implement more than one interface).
Difference between serialization and deserialization
Serialization writes an object’s state into a stream of bytes (ObjectOutputStream.writeObject()) so it can be saved or sent. Deserialization reads those bytes back and re-creates a copy of the original object in memory (ObjectInputStream.readObject()).
Difference between character oriented and byte oriented streams
Byte-oriented streams (InputStream/OutputStream and their subclasses, names end with "Stream") read and write data 8-bit byte by byte and suit any binary data. Character-oriented streams (Reader/Writer subclasses) read and write 16-bit Unicode characters and handle character encoding, so they suit text.
Why is executeUpdate() used
It is used to execute INSERT, UPDATE or DELETE (and DDL) SQL statements; it returns the number of rows affected.
Name component subclasses that support painting
In AWT: Canvas, Panel, Frame and Applet (overriding paint()). In Swing, any JComponent such as JPanel (overriding paintComponent()).
Write Different between abstract class and interface class?
An abstract class can have abstract as well as implemented methods, constructors and instance variables, and a class can extend only one class. An interface contains only method declarations (and constants), and a class can implement many interfaces. Use an abstract class when subclasses share common behaviour; use an interface when only a common set of methods is required.
Write 4 types of JDBC Driver.
Type 1: JDBC-ODBC Bridge driver Type 2: Native-API / partly Java driver Type 3: Net-protocol / all-Java driver Type 4: Native-protocol / all-Java driver
If a method is declared as protected where can be the method accessed?
In the same class, in its subclasses and in other classes of the same package.
What Difference between serialization and de-serialization?
Serialization turns an object into a stream of bytes; deserialization turns that stream of bytes back into a copy of the original object.
4 stages of applet cycles
1. init(): the applet initializes itself. 2. start(): it starts running. 3. stop(): it stops running (e.g. page left). 4. destroy(): final cleanup before it is unloaded.
What will happen if a class implements Windowlistener Interface and it does not provide definitions of all methods.
The class does not compile unless it is declared abstract, and then its object cannot be created; all 7 methods must be defined, or WindowAdapter should be extended instead.
Methods to execute SQL query?
Statement provides executeQuery(sql) for SELECT (returns a ResultSet), executeUpdate(sql) for INSERT, UPDATE, DELETE (returns number of rows affected) and execute(sql) for any statement (returns true if a ResultSet is produced).
Diff b/w Input/output streams class hierarchy and Read/Write class hierarchy?
The InputStream/OutputStream hierarchy is byte-oriented: InputStream and OutputStream are the abstract classes at its top and its classes read/write bytes. The Reader/Writer hierarchy is character-oriented: Reader and Writer are the abstract top classes and its classes read/write Unicode characters (text).
As a developer of GUI, what should u know about top level containers and general purpose containers?
A container is a component that holds other components. Top-level containers (JFrame, JDialog, JApplet) are the root of a GUI, can exist alone and contain other containers and basic components (through their content pane). General-purpose containers (JPanel, JScrollPane, JToolBar) are used to group basic components; they cannot exist alone and must be added to a top-level container.
What is the difference between a static and a non-static inner class?
An object of a non-static inner class is always linked to an object of the outer class, so it can access the outer object’s instance members, and it is created through an outer object (outer.new Inner()). A static nested class is not linked to any outer object; it can be created without an outer object (new Outer.Nested()) and can directly access only static members of the outer class.
Discuss any three methods of ResultSetMetaData?
getColumnCount() returns number of columns; getColumnName(int) returns a column name; getColumnType(int) returns the SQL type of a column.
Two java collections. Which Should use for Your indexed Search?
ArrayList, because its elements are stored by position and can be read directly by index with get(index). A HashMap is used instead when values are searched by a key rather than by an index.
Which Component subclasses are used for paint
Canvas, Panel, Frame and Applet in AWT; in Swing, JComponent subclasses such as JPanel.
How do we create DataBaseMetaData object?
It is obtained from a Connection object: Connection con = DriverManager.getConnection(url, usr, pwd); DatabaseMetaData dbMetaData = con.getMetaData();
Write the syntax of update SQL Query.
String sql = "UPDATE Person SET address = 'Lahore' WHERE name = 'ali'"; int count = stmt.executeUpdate(sql); // number of rows updated General form: UPDATE tableName SET columnName = value WHERE condition
What is the difference between the paint() and repaint() methods?
paint() (paintComponent() in Swing) contains the actual drawing code; it is overridden to change how a component looks and is called by the system. repaint() is called by the program to request that the component be redrawn; the system then calls update()/paint() as soon as it can. Programs should call repaint(), not paint() directly.
What interfaces needs to implement while handling ActionEvent, KeaEvent and WindowEvent?
ActionEvent: ActionListener (actionPerformed) KeyEvent: KeyListener (keyPressed, keyReleased, keyTyped) WindowEvent: WindowListener (windowClosing etc., 7 methods)
What restrictions are placed on method overriding?
An overriding method in a subclass must: - have the same name, the same parameter list and the same (or, from Java 5, a covariant subtype) return type as the superclass method; - not reduce visibility (a public method must stay public; a protected one may be protected or public); - not throw new or broader checked exceptions than the overridden method; - not override a final method (final methods cannot be overridden) and a static method cannot be overridden by an instance method (static methods are hidden, not overridden); - private methods are not inherited, so they cannot be overridden.
What is a Container in a GUI?
A container is a GUI component that can hold other components (and other containers) and arranges them with a layout manager. Top-level containers such as JFrame, JDialog and JApplet form the window; their content pane is where components are added. General-purpose containers such as JPanel, JScrollPane and JToolBar group components inside a window. Components are added with add(), and the container's layout manager (FlowLayout, BorderLayout, GridLayout etc.) decides their size and position.
What are the problems faced by Java programmers who don't use layout managers?
Without a layout manager (null layout) the programmer must give the exact position and size of every component with setBounds(). Problems: a lot of extra work; the GUI does not adjust when the window is resized; it may look wrong on other platforms, screen resolutions, fonts or look-and-feels, so components can overlap or be cut off; adding or changing a component means recalculating many coordinates, so the code is hard to maintain; and it breaks Java's platform-independent GUI design.
You will write the program whose interface is show above. The panel consists of Two Buttons and one Text box and a string "Hello World". Toggle Button: The functionality of the Toggle button is that when it is pressed the color of the text shown on the panel will be changed. Initially you will use two colors for text (here in the figure 1 and 2 blue and red colors are used) but if you want to use more color it will be appreciated. Green Button Green button will simply change the color of the text to Green. Text Box Whatever string you will write in the text box will appear on the panel and on this text "Toggle" and "Green" operations can be performed as shown in Fig-4. 1- "Toggle" button will be pressed the color of text will be changed and By press the Toggle button again the color will be changed again you have to use two colors at least for toggling (Here in this case blue and red color are shown). 2- When you press the "Green" button the text will become green 3- There is a text box, when you write some string in the text box the Text on the Panel will change as shown in Fig-3.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorText implements ActionListener { JFrame frame; JLabel label; JButton toggle, green; JTextField text; Color[] colors = {Color.BLUE, Color.RED}; int index = 0; public ColorText() { frame = new JFrame("Color Text"); Container c = frame.getContentPane(); c.setLayout(new FlowLayout()); label = new JLabel("Hello World"); label.setForeground(colors[index]); toggle = new JButton("Toggle"); green = new JButton("Green"); text = new JTextField(15); toggle.addActionListener(this); green.addActionListener(this); text.addActionListener(this); // Enter in the text box c.add(label); c.add(toggle); c.add(green); c.add(text); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 150); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == toggle) { index = (index + 1) % colors.length; // next color in the cycle label.setForeground(colors[index]); } else if (e.getSource() == green) { label.setForeground(Color.GREEN); } else if (e.getSource() == text) { label.setText(text.getText()); // show typed string } } public static void main(String[] args) { new ColorText(); } } The label shows the text; Toggle cycles through the colors array (more colors can be added to it), Green sets green, and pressing Enter in the text box puts the typed string on the panel, after which Toggle and Green work on the new text.
Differentiate between Named and Anonymous Objects.
A named object is created and assigned to a reference variable, so it can be used again and again through that name, e.g. String s = "hello"; System.out.println(s); or Handler h = new Handler(); b.addActionListener(h); An anonymous object is created without storing its reference in a variable; it is used once at the place where it is created, e.g. System.out.println("hello"); or b.addActionListener(new Handler()); Use anonymous objects for one-time use (less code); use named objects when the object must be referred to again.
Following are the contents of file1.txt My name is ali. My roll no is bc020400001. I am studying java. Java is very easy. You are required to write a code which will read this file and create a new file in which lines would be swapped in such a way that first line would be swapped with 2nd and 3rd with 4th and so on. New file should look like: My roll no is bc020400001. My name is ali. Java is very easy. I am studying java. (5 Marks file handling, 5 Marks swapping)
import java.io.*; import java.util.*; public class SwapLines { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("file1.txt")); ArrayList<String> lines = new ArrayList<String>(); String line; while ((line = br.readLine()) != null) { lines.add(line); } br.close(); PrintWriter pw = new PrintWriter(new FileWriter("file2.txt")); for (int i = 0; i < lines.size(); i += 2) { if (i + 1 < lines.size()) { pw.println(lines.get(i + 1)); // write the 2nd line of the pair first } pw.println(lines.get(i)); } pw.close(); } catch (IOException e) { System.out.println(e); } } }
For a company named ABC what are the basic steps to communicate their database with JDBC through Java languages.
1. Import the java.sql package. 2. Load a suitable driver, e.g. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 3. Define the connection URL of the database, e.g. String url = "jdbc:odbc:abcDSN"; 4. Establish the connection: Connection con = DriverManager.getConnection(url, user, password); 5. Create a statement: Statement st = con.createStatement(); 6. Execute the query: ResultSet rs = st.executeQuery(sql); (or executeUpdate for INSERT/UPDATE/DELETE) 7. Process the results with rs.next() and getXXX() methods. 8. Close the result set, statement and connection.
Write the names of steps to make a simple client in Java client Server application.
1. Import the required packages (java.net.* and java.io.*). 2. Connect / open a socket with the server: Socket s = new Socket(serverName, serverPort); 3. Get the I/O streams of the socket (getInputStream(), getOutputStream(), wrapped in BufferedReader and PrintWriter). 4. Send / receive messages (pw.println(...), br.readLine()). 5. Close the socket: s.close();
What will happen if an image drawn out of the window coordinates?
Nothing fails: drawing is clipped to the component’s visible area. The part of the image that lies outside the window coordinates is simply not shown (and is not drawn at all if it is completely outside); no error or exception occurs. It becomes visible only if the window is enlarged or the image is moved inside the drawable area.
How we process the results of sql query.
executeQuery() returns a ResultSet that holds the rows of the result in table form. A cursor is initially before the first row; next() moves it to the next row and returns false when no rows remain, so it is called in a loop (at least once). Column values of the current row are read with getXXX() methods (getString, getInt, ...) using the column name or the column index (starting from 1). while (rs.next()) { String name = rs.getString("name"); // or rs.getString(1) System.out.println(name); }
Write down the steps of make Client on Java Client Server application.
1. Import java.net.* and java.io.*. 2. Open a socket with the server: Socket s = new Socket("localhost", 2222); 3. Get the I/O streams: BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw = new PrintWriter(s.getOutputStream(), true); 4. Send / receive messages: pw.println("hello"); String msg = br.readLine(); 5. Close the socket: s.close();
What does it mean that a method or class is abstract?
An abstract method is declared with the abstract keyword and has no body; its subclasses must provide the implementation. An abstract class is declared abstract and defines only part of an implementation, so it cannot be instantiated. It may contain instance variables and fully implemented methods as well. Any class having an abstract method must be declared abstract, but a class may be declared abstract without abstract methods. A subclass that overrides all abstract methods becomes concrete; otherwise it must also be declared abstract. A reference of an abstract class can point to objects of its concrete subclasses.
What is port? How can it useful in network?
A port is a 16-bit number (0 to 65535) that works as a transport address of a process on a machine. The IP address identifies the computer, while the port identifies which program/service on it should receive the data. A server process listens for connection requests on a port (e.g. new ServerSocket(2222)), and a client connects by giving the host and the port. So many network programs can run on one machine at the same time. Ports below 1024 are reserved for well-known services (e.g. HTTP 80).
how do we load a driver and how do we define a connection for URL and JDBC
Load the driver with Class.forName(), e.g. for MS Access through ODBC: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); for Oracle: Class.forName("oracle.jdbc.driver.OracleDriver"); Then define the connection URL that addresses the database, e.g. with a DSN named personDSN: String url = "jdbc:odbc:personDSN"; and open the connection: Connection con = DriverManager.getConnection(url, "", "");
What is the difference between Applet and Application
An application is a stand-alone program that starts from main() and runs on the JVM from the command line, with full access to the local system. An applet has no main(); it is embedded in an HTML page and runs inside a browser or appletviewer, controlled by the life-cycle methods init(), start(), stop(), destroy() and paint(). Applets are downloaded from a server and run in a security sandbox (e.g. no local file access, connect only to their own server), while applications have no such restrictions.
How can we prevent serialization?
To stop a field from being serialized, mark it with the transient keyword. This is used for fields that do not represent object state but connections to external resources, e.g. transient Socket s; transient OutputStream os; transient Connection con; Transient fields are not written and come back as default values (null for objects) when the object is read. To prevent a whole class from being serialized, do not implement Serializable (or throw NotSerializableException from writeObject()).
Why do we use prepared Statement object?
A PreparedStatement holds a precompiled SQL statement. The SQL is sent to the database once for compilation, and then it can be executed many times with different parameter values, which is faster than a plain Statement. Parameters are marked with ? and filled with setter methods, which also avoids building SQL strings by hand (safer against SQL injection). PreparedStatement ps = con.prepareStatement("UPDATE Person SET phone = ? WHERE id = ?"); ps.setString(1, phone); ps.setInt(2, id); int n = ps.executeUpdate();
What does mean by it if a class or method is abstract?
An abstract method has no body and must be implemented by subclasses; an abstract class defines a partial implementation and cannot be instantiated; a class with any abstract method must be abstract.
Can applets communicate with each other?
Yes. Applets on the same page (same JVM) can get references to each other through the AppletContext: getAppletContext().getApplet(name) or getApplets(), and then call each other’s public methods. Applets of the same class can also share data through static variables. Applets on different pages can communicate only indirectly, e.g. through the server they came from.
What is the difference between Anonymous object and Named object? Give example with code.
A named object is stored in a reference variable and can be used again: String s = "hello"; System.out.println(s); An anonymous object is used once where it is created, without a variable: System.out.println("hello"); or button.addActionListener(new Handler()); Anonymous objects suit one-time use; named objects suit repeated use.
How can you retrieve data from the ResultSet?
Call next() in a loop to move the cursor row by row (it returns false after the last row) and read each column with getXXX() methods by column name or index (starting at 1): ResultSet rs = stmt.executeQuery("SELECT * FROM Person"); while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt(2); }