Important java questions
Blackkspydo
0 views 0 reactions 2025-08-31
Unit 1: Programming in Java
-
Explain the Java architecture and its key components, such as JVM, JRE, and JDK.
Java architecture is platform-independent and consists of: JVM (Java Virtual Machine) which executes bytecode; JRE (Java Runtime Environment) which provides libraries and JVM for running Java programs; JDK (Java Development Kit) which includes JRE plus tools like compiler (javac) for developing Java applications. -
What are Java buzzwords? Describe any five with examples.
Java buzzwords include Platform Independent (write once, run anywhere via bytecode), Simple (no pointers, automatic garbage collection), Secure (sandbox environment, no direct memory access), Portable (bytecode runs on any JVM), Object-Oriented (encapsulation, inheritance, polymorphism). For example, Platform Independent: A Java program compiled on Windows runs on Linux without changes. -
How do you set Path and ClassPath variables in Java? Why are they important?
Path is set for system executables like javac/java (e.g., in Windows: set PATH=%PATH%;C:\Program Files\Java\jdk\bin). ClassPath is for locating .class files (e.g., set CLASSPATH=.;C:\myclasses). They are important for the system to find Java tools and classes during compilation/execution. -
Walk through the process of compiling and running a simple Java program.
Write code in a .java file (e.g., Hello.java with public class Hello { public static void main(String[] args) { System.out.println(“Hello”); } }). Compile with javac Hello.java to produce Hello.class. Run with java Hello. -
Differentiate between arrays and enhanced for-each loops in Java with syntax examples.
Arrays are fixed-size collections (e.g., int[] arr = {1,2,3};). For-each loop iterates over arrays/collections without index (e.g., for(int num : arr) { System.out.println(num); }). Arrays store data; for-each simplifies traversal but can’t modify indices. -
What is the difference between a class and an object? Provide an example of object creation.
Class is a blueprint (e.g., class Dog { String name; }). Object is an instance (e.g., Dog myDog = new Dog();). Objects have state/behavior from the class. -
Explain method overloading in Java with an example, including how the compiler resolves overloaded methods.
Overloading: Multiple methods with same name but different parameters (e.g., void add(int a, int b); void add(int a, double b);). Compiler resolves by matching argument types/number/order at compile time. -
Describe access privileges (modifiers) in Java, such as public, private, protected, and default.
Public: Accessible everywhere. Private: Only within class. Protected: Within package and subclasses. Default (no modifier): Within package only. -
What is an interface in Java? How does it differ from an abstract class?
Interface: Abstract type with abstract methods/constants (e.g., interface Animal { void eat(); }). Supports multiple inheritance. Abstract class: Can have concrete/abstract methods, single inheritance only. -
Explain inner classes in Java and provide scenarios where they are useful.
Inner classes: Class within class (e.g., class Outer { class Inner { } }). Useful for encapsulation, like event handlers or private helpers. -
What do the final and static modifiers mean in Java? Give examples of their usage.
Final: Can’t be modified (e.g., final int x=5; can’t reassign). Static: Belongs to class, not instance (e.g., static int count; shared across objects). -
How do packages work in Java? Explain how to create and import a package.
Packages organize classes (e.g., package com.example;). Create: Use package statement at top. Import: import com.example.MyClass; or import com.example.*;. -
Describe inheritance in Java, including types like single, multilevel, and hierarchical.
Inheritance: Subclass inherits from superclass (extends keyword). Single: One superclass. Multilevel: Chain (A extends B extends C). Hierarchical: Multiple subclasses from one superclass. -
What is method overriding? How does it relate to polymorphism?
Overriding: Subclass redefines superclass method with same signature. Enables runtime polymorphism (method called based on object type). -
Explain exception handling keywords: try, catch, finally, throws, and throw.
Try: Encloses code that may throw exception. Catch: Handles specific exception. Finally: Always executes (cleanup). Throws: Declares method may throw exception. Throw: Manually throws exception. -
How do you create a custom exception class in Java? Provide an example.
Extend Exception (e.g., class MyException extends Exception { MyException(String msg) { super(msg); } }). Throw with throw new MyException(“Error”); -
Introduce concurrency in Java and describe the different thread states.
Concurrency: Multiple threads executing. States: New (created), Runnable (ready), Running (executing), Blocked (waiting), Terminated (done). -
How do you create multithreaded programs in Java? Explain with code snippets.
Extend Thread or implement Runnable (e.g., class MyThread extends Thread { public void run() { System.out.println(“Running”); } }; MyThread t = new MyThread(); t.start();). -
What are thread properties, and how can you set thread priorities?
Properties: Name, priority, daemon status. Set priority: t.setPriority(Thread.MAX_PRIORITY); (1-10 range). -
Explain thread synchronization in Java, including the use of synchronized keyword.
Synchronization: Prevents concurrent access issues (e.g., synchronized void method() { } or synchronized(block) { }). -
Differentiate between byte stream and character stream classes for file handling.
Byte: Handles binary (InputStream/OutputStream). Character: Handles text (Reader/Writer), Unicode-aware. -
How do you work with Random Access Files in Java?
Use RandomAccessFile (e.g., RandomAccessFile raf = new RandomAccessFile(“file.txt”, “rw”); raf.seek(10); raf.write(“data”);). -
Explain how to read and write objects to files using serialization.
Implement Serializable. Write: ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(“file”)); oos.writeObject(obj);. Read: ObjectInputStream ois = …; Obj o = (Obj) ois.readObject();.
Unit 2: User Interface Components with Swing
-
What is the difference between AWT and Swing in Java?
AWT: Native components, heavyweight. Swing: Lightweight, pure Java, more features/customizable. -
Explain the concept of Java Applets and their life cycle methods.
Applets: Embed in web pages. Life cycle: init(), start(), paint(), stop(), destroy(). -
Describe the Swing class hierarchy, focusing on components and containers.
Root: JComponent. Components: JLabel, JButton. Containers: JFrame, JPanel (hold components). -
What are layout managers in Swing? Explain why they are used.
Layout managers: Arrange components (e.g., FlowLayout). Used for automatic resizing/positioning across platforms. -
Compare FlowLayout, BorderLayout, and GridLayout with examples.
FlowLayout: Left-to-right flow. BorderLayout: North/South/East/West/Center. GridLayout: Grid rows/columns. -
How does GridBagLayout work? Provide a scenario where it is preferred.
Flexible grid with constraints (GridBagConstraints). Preferred for complex, resizable forms. -
What is GroupLayout, and how is it different from other layouts?
GroupLayout: Groups components horizontally/vertically. Differs by precise alignment, often used in GUI builders. -
Explain GUI controls like TextField, PasswordField, and TextArea in Swing.
JTextField: Single-line text. JPasswordField: Echoes hidden. JTextArea: Multi-line text. -
How do you use ScrollPane and Labels in Swing applications?
JScrollPane: Adds scrollbars (e.g., new JScrollPane(textArea);). JLabel: Displays text/image (new JLabel(“Text”);). -
Describe CheckBoxes and RadioButtons, including how to group them.
JCheckBox: Toggle on/off. JRadioButton: Mutually exclusive, group with ButtonGroup (e.g., ButtonGroup bg = new ButtonGroup(); bg.add(rb1); bg.add(rb2);). -
What are Borders in Swing? How can you apply them to components?
Borders: Visual edges (e.g., BorderFactory.createLineBorder(Color.BLACK);). Apply: component.setBorder(border);. -
Explain ComboBoxes and Sliders with their properties and usage.
JComboBox: Dropdown list (new JComboBox(items);). JSlider: Range selector (new JSlider(0,100);). -
How do you create Menus and MenuItems in Swing?
JMenuBar bar = new JMenuBar(); JMenu menu = new JMenu(“File”); JMenuItem item = new JMenuItem(“Open”); menu.add(item); bar.add(menu); frame.setJMenuBar(bar);. -
What are Icons in Menu Items? How do you add them?
Icons: Images (e.g., item.setIcon(new ImageIcon(“icon.png”));). -
Explain CheckBox and RadioButton in Menu Items.
JCheckBoxMenuItem: Toggleable menu item. JRadioButtonMenuItem: Grouped radio in menu. -
What are Pop-up Menus, and how do they differ from regular menus?
JPopupMenu: Context menu on right-click. Differs: Not in menu bar, shown on demand. -
How do you add Keyboard Mnemonics and Accelerators to menu items?
Mnemonics: item.setMnemonic(‘O’); (Alt+O). Accelerators: item.setAccelerator(KeyStroke.getKeyStroke(‘O’, CTRL_DOWN_MASK));. -
Explain enabling/disabling Menu Items dynamically.
item.setEnabled(false); based on conditions. -
What are Toolbars and Tooltips in Swing? Provide examples.
JToolBar: Button strip (new JToolBar(); bar.add(button);). Tooltip: component.setToolTipText(“Hint”);. -
Describe Option Dialogs and how to create custom dialogs.
JOptionPane: showMessageDialog(), showInputDialog(), etc. Custom: Extend JDialog. -
Explain FileChoosers and ColorChoosers in Swing.
JFileChooser: File selection dialog. JColorChooser: Color picker. -
What are Internal Frames? How do they work within a desktop application?
JInternalFrame: Windows inside JDesktopPane (MDI). Add to desktop: desktop.add(internalFrame);. -
Describe Frames, Tables, Trees, and their basic implementations in Swing.
JFrame: Top-level window. JTable: Data grid (new JTable(data, columns);). JTree: Hierarchical (new JTree(rootNode);). JTable: Wait, this seems duplicate; assuming it’s JTable and JTree as listed.
Unit 3: Event Handling
-
Explain the event handling concept in Java, including event sources and listeners.
Events: User actions (e.g., click). Source: Component generating event. Listener: Object handling it (implements interface, registered via addListener). -
What are Listener Interfaces? Name a few and their purposes.
ActionListener: For buttons. KeyListener: Keyboard. MouseListener: Mouse actions. -
How do you use Action Commands in event handling?
Set: button.setActionCommand(“cmd”); Get: e.getActionCommand() in actionPerformed. -
What are Adapter Classes, and why are they useful in event handling?
Adapters: Empty implementations of interfaces (e.g., MouseAdapter). Useful: Override only needed methods. -
Explain how to handle Action Events with an example.
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code } });. -
Describe Key Events and how to capture keyboard inputs.
KeyEvent: Press/release/type. Add KeyListener to component. -
What are Focus Events? Provide a use case.
FocusEvent: Gain/lose focus. Use: Validate input on focus lost. -
Explain Mouse Events, including mouse clicks and movements.
MouseEvent: Click, enter/exit, drag. Methods: mouseClicked, mouseMoved. -
How do you handle Window Events like opening or closing?
Add WindowListener: windowOpened, windowClosing, etc. -
Describe Item Events and their association with components like CheckBoxes.
ItemEvent: State change (selected/deselected). For JCheckBox, JComboBox.
Unit 4: Database Connectivity
-
Explain the JDBC architecture and its layers.
Layers: Application (Java code), JDBC API (java.sql), Driver Manager, Drivers (connect to DB). -
What are the different types of JDBC drivers? When would you use each?
Type 1: JDBC-ODBC bridge (legacy). Type 2: Native API (fast, platform-specific). Type 3: Network protocol (middleware). Type 4: Thin driver (direct to DB, portable). -
How do you configure JDBC connections in Java?
Load driver (Class.forName(“driver”);), Connect: Connection con = DriverManager.getConnection(“url”, “user”, “pass”);. -
Explain managing Connections, Statements, and ResultSets in JDBC.
Connection: DB link. Statement: Execute SQL. ResultSet: Query results (rs.next() to iterate). -
How do you handle SQL Exceptions in JDBC code?
Catch SQLException in try-catch, check getMessage() or getErrorCode(). -
Describe DDL and DML operations using Java JDBC.
DDL: CREATE/ALTER (stmt.execute(“CREATE TABLE …”);). DML: INSERT/UPDATE (stmt.executeUpdate(“INSERT …”);). -
What are Prepared Statements? Why are they preferred over regular Statements?
PreparedStatement: Precompiled SQL with placeholders (ps.setString(1, value);). Preferred: Prevents SQL injection, efficient for repeated use. -
Explain handling Multiple Results from queries.
Use stmt.getMoreResults() to check/process next ResultSet. -
What are Scrollable Result Sets? How do you navigate them?
Create with TYPE_SCROLL_INSENSITIVE. Navigate: rs.first(), rs.last(), rs.absolute(pos). -
Describe Updateable Result Sets with an example.
Create with CONCUR_UPDATABLE. Update: rs.updateString(“col”, “val”); rs.updateRow();. -
What are RowSets and Cached RowSets? How do they differ from ResultSets?
RowSet: Disconnected ResultSet. CachedRowSet: In-memory cache. Differ: Can work offline, unlike connected ResultSet. -
Explain transactions in JDBC, including commit and rollback.
con.setAutoCommit(false); Execute ops; con.commit(); or con.rollback() on error. -
What are SQL Escapes in JDBC?
Standardize syntax (e.g., {d ‘2025-08-31’} for date).
Unit 5: Network Programming
-
Differentiate between TCP and UDP protocols in network programming.
TCP: Connection-oriented, reliable, ordered. UDP: Connectionless, faster, no guarantees. -
What are ports and IP addresses? How are they used in Java networking?
IP: Device address. Port: Application endpoint. Used: Socket(address, port). -
Name some network classes in JDK and their purposes.
Socket: TCP client. ServerSocket: TCP server. DatagramSocket: UDP. URL: Web resources. -
Explain socket programming using TCP in Java with client-server examples.
Server: ServerSocket ss = new ServerSocket(8080); Socket s = ss.accept();. Client: Socket s = new Socket(“localhost”, 8080); Use streams for I/O. -
How does socket programming with UDP differ from TCP? Provide code snippets.
UDP: No connection. DatagramSocket ds = new DatagramSocket(); ds.send(new DatagramPacket(data, len, addr, port)); ds.receive(packet);. -
What is a URL in Java? How do you work with URLs?
URL u = new URL(”http://example.com”); Read: u.openStream();. -
Explain the URLConnection class and its methods.
URLConnection conn = u.openConnection(); conn.connect(); Get headers, input/output streams. -
Introduce Java Mail API and its components.
For email: Session, Message, Transport, Store. -
How do you send an email using Java Mail API?
Session session = Session.getInstance(props); MimeMessage msg = new MimeMessage(session); msg.setFrom(…); Transport.send(msg);. -
Explain receiving emails with Java Mail API.
Store store = session.getStore(“pop3”); store.connect(); Folder folder = store.getFolder(“INBOX”); folder.open(READ_ONLY); Message[] msgs = folder.getMessages();.
Unit 6: GUI with JavaFX
-
What is JavaFX? How does it compare to Swing?
JavaFX: Modern UI toolkit with CSS, animations. Vs Swing: Richer media support, hardware-accelerated, but requires separate module post-Java 8. -
Explain JavaFX layouts like FlowPane and BorderPane.
FlowPane: Wraps nodes in flow. BorderPane: Top/Bottom/Left/Right/Center regions. -
Describe HBox, VBox, and GridPane in JavaFX.
HBox: Horizontal box. VBox: Vertical. GridPane: Grid with rows/columns. -
What are JavaFX UI controls like Label, TextField, and Button?
Label: Text display. TextField: Input. Button: Clickable. -
Explain RadioButton and CheckBox in JavaFX.
RadioButton: Group with ToggleGroup. CheckBox: Toggle. -
How do you use Hyperlink, Menu, and Tooltip in JavaFX?
Hyperlink: Clickable link. Menu: In MenuBar. Tooltip: Tooltip.install(node, new Tooltip(“text”));. -
Describe FileChooser in JavaFX and its usage.
FileChooser fc = new FileChooser(); File file = fc.showOpenDialog(stage);.
Unit 7: Servlets and Java Server Pages
-
What is a Web Container? Name some examples.
Runs web apps (Servlets/JSP). Examples: Tomcat, Jetty. -
Introduce Servlets and explain their life cycle.
Server-side Java. Life cycle: init(), service() (doGet/doPost), destroy(). -
Describe the Servlet APIs and key interfaces like HttpServlet.
javax.servlet: Servlet, HttpServlet (extends GenericServlet for HTTP). -
How do you write a basic Servlet program?
Extend HttpServlet, override doGet/doPost. Map in web.xml or @WebServlet. -
Explain reading form parameters in Servlets.
request.getParameter(“name”); for single, getParameterValues for multiple. -
How do Servlets process forms?
In doPost: Read params, process, respond via response.getWriter().println(“result”);. -
Differentiate between HTTP GET and POST requests in Servlets.
GET: URL params, idempotent. POST: Body data, for modifications. -
Explain database access using Servlets.
Use JDBC inside doGet/doPost: Get connection, execute queries. -
How do you handle Cookies in Servlets?
Add: Cookie c = new Cookie(“key”, “val”); response.addCookie(c);. Get: request.getCookies();. -
Describe Session management in Servlets.
HttpSession session = request.getSession(); session.setAttribute(“key”, obj); getAttribute. -
What is the difference between Servlets and JSP?
Servlet: Java code with HTML. JSP: HTML with Java (compiles to Servlet). -
Explain the JSP Access Model.
JSP translated to Servlet, executed on server, output sent to client. -
Describe JSP syntax elements: Directives, Declarations, Expressions, Scriptlets, and Comments.
Directive: <%@ page … %>. Declaration: <%! int x; %>. Expression: <%= x %>. Scriptlet: <% code; %>. Comment: <%— —%>. -
What are JSP Implicit Objects? Name a few.
request, response, out, session, application. -
How does object scope work in JSP (e.g., page, request, session)?
pageContext.setAttribute(“key”, obj, PageContext.PAGE_SCOPE); Similarly for REQUEST_SCOPE, etc. -
Explain processing forms in JSP.
Use ${param.name} or request.getParameter in scriptlets. -
How do you access databases with JSP?
Use scriptlets with JDBC code. -
Introduce Java Web Frameworks and name a few popular ones like Spring or Struts.
Frameworks: Simplify web dev. Spring (MVC, dependency injection), Struts (MVC pattern), JSF (component-based).
Unit 8: RMI and CORBA
-
What is RMI? Explain its architecture.
Remote Method Invocation: Call methods on remote objects. Architecture: Stub (client proxy), Skeleton (server), RMI registry. -
How do you create and execute RMI applications?
Interface extends Remote. Impl extends UnicastRemoteObject. Server: Naming.bind(“name”, obj);. Client: Naming.lookup(“rmi://host/name”);. -
Differentiate between RMI and CORBA.
RMI: Java-only, simple. CORBA: Language-independent, more complex. -
Explain the architecture of CORBA.
Common Object Request Broker Architecture: ORB (broker), IDL (interface), stubs/skeletons. -
What is IDL in CORBA? Why is it used?
Interface Definition Language: Defines interfaces neutrally. Used for cross-language compatibility. -
Provide a simple example of a CORBA program.
Define IDL interface. Compile to stubs. Implement server, register with ORB. Client resolves and calls.
General/Laboratory Works Questions
-
Describe how to implement basic Java concepts like arrays and loops in a lab program.
e.g., int[] arr = new int[5]; for(int i=0; i -
Explain designing a GUI application using Swing or JavaFX in the lab.
Create JFrame/Stage, add components/layouts, handle events. -
How would you handle events in a lab project involving buttons or menus?
Add ActionListener to button, implement actionPerformed. -
Provide an example of JDBC integration in a lab program for database operations.
Connect to DB, execute SELECT/INSERT via Statement or PreparedStatement. -
Describe a network programming lab exercise, such as a client-server chat application.
Server: ServerSocket, accept connections, read/write via sockets. Client: Connect, send/receive messages. -
How do you develop a web application using Servlets or JSP in the lab?
Use Tomcat, create Servlet/JSP, handle requests, deploy war. -
Explain creating distributed applications with RMI in a lab setting.
Define remote interface, implement, start rmiregistry, bind server, lookup in client. -
What Java Web Framework have you used in lab work, and how did you apply it?
e.g., Spring: Configure MVC, create controllers, services, views for web app.