• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

GKPAD.COM

ONLINE HINDI EDUCATION PORTAL

  • Home
  • Blog
  • Sarkari Result
  • University Books
  • University Papers
  • University Syllabus
  • About Us

IGNOU MCS-206 Solved Question Paper PDF Download

The IGNOU MCS-206 Solved Question Paper PDF Download page is designed to help students access high-quality exam resources in one place. Here, you can find ignou solved question paper IGNOU Previous Year Question paper solved PDF that covers all important questions with detailed answers. This page provides IGNOU all Previous year Question Papers in one PDF format, making it easier for students to prepare effectively.

  • IGNOU MCS-206 Solved Question Paper in Hindi
  • IGNOU MCS-206 Solved Question Paper in English
  • IGNOU Previous Year Solved Question Papers (All Courses)

Whether you are looking for IGNOU Previous Year Question paper solved in English or ignou previous year question paper solved in hindi, this page offers both options to suit your learning needs. These solved papers help you understand exam patterns, improve answer writing skills, and boost confidence for upcoming exams.

IGNOU MCS-206 Solved Question Paper PDF

IGNOU Previous Year Solved Question Papers

This section provides IGNOU MCS-206 Solved Question Paper PDF in both Hindi and English. These ignou solved question paper IGNOU Previous Year Question paper solved PDF include detailed answers to help you understand exam patterns and improve your preparation. You can also access IGNOU all Previous year Question Papers in one PDF for quick and effective revision before exams.


IGNOU MCS-206 Previous Year Solved Question Paper in Hindi

Q1. (a) इनकैप्सुलेशन (encapsulation) क्या है? जावा में इनकैप्सुलेशन को कैसे लागू किया जाता है? एक प्रोग्राम के माध्यम से समझाएं। 5 (b) जावा में एब्स्ट्रैक्ट क्लास (abstract class) और इंटरफ़ेस (interface) के बीच अंतर करें। प्रत्येक का उदाहरण दें। 5 (c) जावा में मैप इंटरफ़ेस (map interface) की उपयोगिता की चर्चा एक प्रोग्राम की सहायता से करें। 5 (d) जावा में ऑब्जेक्ट सीरियलाइजेशन (object serialization) क्या है? ऑब्जेक्ट सीरियलाइजेशन की कार्यप्रणाली और उपयोगिता की व्याख्या करें। 5 (e) जावा में ‘final’ और ‘super’ कीवर्ड्स की उपयोगिता को उपयुक्त कोड के साथ वर्णित करें। 5 (f) 3 x 3 आयाम के दो मैट्रिक्स (matrices) का योग ज्ञात करने के लिए एक जावा प्रोग्राम लिखें। अपने कोड को उपयुक्त टिप्पणियों (comments) के साथ समर्थित करें। 5 (g) JDBC में ResultSet इंटरफ़ेस के उपयोग को एक प्रोग्राम की सहायता से समझाएं। 5 (h) जावा में फंक्शन ओवरलोडिंग (function overloading) के लाभ को एक उपयुक्त प्रोग्राम की सहायता से समझाएं। 5

Ans.

(a) इनकैप्सुलेशन (Encapsulation)

इनकैप्सुलेशन ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग (OOP) के चार मूलभूत सिद्धांतों में से एक है। इसका अर्थ है डेटा (वेरिएबल्स) और कोड (मेथड्स) जो उस डेटा पर काम करते हैं, को एक ही इकाई (unit) में बांधना या लपेटना। यह “डेटा हाइडिंग” (data hiding) का सिद्धांत लागू करता है, जिसका अर्थ है कि किसी ऑब्जेक्ट का आंतरिक डेटा अन्य ऑब्जेक्ट्स से छिपा होता है और केवल उस ऑब्जेक्ट के अपने मेथड्स के माध्यम से ही एक्सेस किया जा सकता है।

जावा में कार्यान्वयन: जावा में, इनकैप्सुलेशन को निम्नलिखित तरीकों से लागू किया जाता है:

  • क्लास के वेरिएबल्स (फील्ड्स) को private घोषित करके, ताकि उन्हें क्लास के बाहर से सीधे एक्सेस न किया जा सके।
  • प्रत्येक वेरिएबल के लिए public “getter” और “setter” मेथड्स प्रदान करके। Getter मेथड वेरिएबल की वैल्यू को पढ़ता है, और Setter मेथड वेरिएबल की वैल्यू को अपडेट करता है।

उदाहरण प्रोग्राम:

// एक इनकैप्सुलेटेड Employee क्लास class Employee { // प्राइवेट डेटा मेम्बर private String name; private int employeeId; // नाम के लिए Public Getter मेथड public String getName() { return name; } // नाम के लिए Public Setter मेथड public void setName(String name) { this.name = name; } // employeeId के लिए Public Getter मेथड public int getEmployeeId() { return employeeId; } // employeeId के लिए Public Setter मेथड public void setEmployeeId(int employeeId) { // हम यहां वैलिडेशन भी जोड़ सकते हैं if (employeeId > 0) { this.employeeId = employeeId; } } } public class EncapsulationDemo { public static void main(String[] args) { // Employee ऑब्जेक्ट बनाना Employee emp = new Employee(); // Setter मेथड्स का उपयोग करके डेटा सेट करना emp.setName(“Ravi Kumar”); emp.setEmployeeId(101); // Getter मेथड्स का उपयोग करके डेटा प्राप्त करना System.out.println(“Employee Name: ” + emp.getName()); System.out.println(“Employee ID: ” + emp.getEmployeeId()); } } (b) एब्स्ट्रैक्ट क्लास और इंटरफ़ेस में अंतर

एब्स्ट्रैक्ट क्लास और इंटरफ़ेस दोनों का उपयोग जावा में एब्स्ट्रैक्शन (abstraction) प्राप्त करने के लिए किया जाता है, लेकिन उनके बीच महत्वपूर्ण अंतर हैं:

  • मेथड इम्प्लीमेंटेशन: एब्स्ट्रैक्ट क्लास में एब्स्ट्रैक्ट (बिना बॉडी के) और नॉन-एब्स्ट्रैक्ट (बॉडी के साथ) दोनों मेथड्स हो सकते हैं। जबकि इंटरफ़ेस में (जावा 8 से पहले) केवल एब्स्ट्रैक्ट मेथड्स हो सकते थे। जावा 8 और उसके बाद, इंटरफ़ेस में डिफ़ॉल्ट और स्टैटिक मेथड्स भी हो सकते हैं जिनकी बॉडी होती है।
  • वेरिएबल्स: एब्स्ट्रैक्ट क्लास में final, non-final, static, और non-static वेरिएबल्स हो सकते हैं। इंटरफ़ेस में केवल public static final वेरिएबल्स (कांस्टेंट्स) हो सकते हैं।
  • कंस्ट्रक्टर: एब्स्ट्रैक्ट क्लास का अपना कंस्ट्रक्टर हो सकता है (जिसे सबक्लास द्वारा कॉल किया जाता है)। इंटरफ़ेस का कोई कंस्ट्रक्टर नहीं हो सकता।
  • कीवर्ड: एक क्लास एब्स्ट्रैक्ट क्लास को इनहेरिट करने के लिए extends कीवर्ड का उपयोग करती है। एक क्लास इंटरफ़ेस को लागू करने के लिए implements कीवर्ड का उपयोग करती है।
  • मल्टीपल इनहेरिटेंस: एक क्लास केवल एक एब्स्ट्रैक्ट क्लास को एक्सटेंड कर सकती है, लेकिन कई इंटरफेस को इम्प्लीमेंट कर सकती है।

एब्स्ट्रैक्ट क्लास का उदाहरण:

abstract class Animal { Animal() { System.out.println(“Animal is created”); } abstract void makeSound(); // एब्स्ट्रैक्ट मेथड void eat() { System.out.println(“Animal is eating”); // नॉन-एब्स्ट्रैक्ट मेथड } } class Dog extends Animal { void makeSound() { System.out.println(“Dog barks”); } }

इंटरफ़ेस का उदाहरण:

interface Vehicle { void start(); // एब्स्ट्रैक्ट मेथड void stop(); } class Car implements Vehicle { public void start() { System.out.println(“Car starts”); } public void stop() { System.out.println(“Car stops”); } } (c) मैप इंटरफ़ेस (Map Interface) की उपयोगिता

जावा में Map इंटरफ़ेस कलेक्शन फ्रेमवर्क का एक हिस्सा है, लेकिन यह Collection इंटरफ़ेस को एक्सटेंड नहीं करता है। यह ऑब्जेक्ट्स को की-वैल्यू (key-value) पेयर्स के रूप में संग्रहीत करने के लिए उपयोगी है। प्रत्येक की (key) यूनिक होनी चाहिए, और यह एक वैल्यू (value) से मैप होती है।

उपयोगिता:

  • तेज डेटा रिट्रीवल: मैप्स को की (key) के आधार पर वैल्यूज को बहुत तेजी से खोजने, अपडेट करने और हटाने के लिए डिज़ाइन किया गया है।
  • डेटा एसोसिएशन: यह उन परिदृश्यों के लिए आदर्श है जहां आपको संबंधित डेटा को एक साथ जोड़ना होता है, जैसे यूजर आईडी को यूजर ऑब्जेक्ट से, या एक शब्द को उसकी परिभाषा से।
  • यूनिक कीज: यह डुप्लिकेट कीज की अनुमति नहीं देता है, जो यूनिक आइडेंटिफायर्स के साथ डेटा संग्रहीत करने के लिए उपयोगी है।

जावा में कई मैप इम्प्लीमेंटेशन हैं, जैसे HashMap, TreeMap, और LinkedHashMap । HashMap सबसे अधिक उपयोग किया जाने वाला है क्योंकि यह फास्ट एक्सेस प्रदान करता है और कीज का कोई क्रम बनाए नहीं रखता है।

उदाहरण प्रोग्राम:

import java.util.HashMap; import java.util.Map; public class MapDemo { public static void main(String[] args) { // एक HashMap बनाना जो String कीज को Integer वैल्यूज से मैप करता है Map

ऑब्जेक्ट सीरियलाइजेशन एक प्रक्रिया है जिसमें एक जावा ऑब्जेक्ट की स्थिति (state) को एक बाइट स्ट्रीम (byte stream) में परिवर्तित किया जाता है। इस बाइट स्ट्रीम को फिर एक फ़ाइल में संग्रहीत किया जा सकता है, नेटवर्क पर भेजा जा सकता है, या डेटाबेस में सहेजा जा सकता है। इस प्रक्रिया के विपरीत, बाइट स्ट्रीम को वापस जावा ऑब्जेक्ट में परिवर्तित करने को डी-सीरियलाइजेशन (deserialization) कहा जाता है।

कार्यप्रणाली और उपयोगिता:

  • कार्यप्रणाली: किसी क्लास के ऑब्जेक्ट को सीरियलाइज करने योग्य बनाने के लिए, उस क्लास को java.io.Serializable इंटरफ़ेस को इम्प्लीमेंट करना होगा। यह एक मार्कर इंटरफ़ेस है, जिसका अर्थ है कि इसमें कोई मेथड नहीं है; यह केवल JVM को संकेत देता है कि क्लास सीरियलाइज की जा सकती है।
    • सीरियलाइजेशन: ObjectOutputStream क्लास का उपयोग करके, हम writeObject() मेथड से ऑब्जेक्ट को एक आउटपुट स्ट्रीम (जैसे FileOutputStream) में लिखते हैं।
    • डी-सीरियलाइजेशन: ObjectInputStream क्लास का उपयोग करके, हम readObject() मेथड से इनपुट स्ट्रीम से ऑब्जेक्ट को पढ़ते हैं।
  • उपयोगिता:
    • परसिस्टेंस (Persistence): ऑब्जेक्ट की स्थिति को डिस्क पर सहेजा जा सकता है ताकि एप्लिकेशन के पुनरारंभ होने पर इसे पुनर्प्राप्त किया जा सके।
    • संचार (Communication): ऑब्जेक्ट्स को नेटवर्क पर एक जावा एप्लिकेशन से दूसरे में भेजा जा सकता है, जैसे कि रिमोट मेथड इनवोकेशन (RMI) में।
    • कैशिंग (Caching): बार-बार उपयोग किए जाने वाले ऑब्जेक्ट्स को मेमोरी या डिस्क पर सीरियलाइज करके रखा जा सकता है ताकि उन्हें तेजी से एक्सेस किया जा सके।

(e) ‘final’ और ‘super’ कीवर्ड्स की उपयोगिता

‘final’ कीवर्ड:

‘final’ कीवर्ड का उपयोग किसी एंटिटी (वेरिएबल, मेथड, या क्लास) को अंतिम रूप देने के लिए किया जाता है, जिसका अर्थ है कि इसे बाद में संशोधित या बदला नहीं जा सकता है।

  • final वेरिएबल: यदि कोई वेरिएबल final घोषित किया जाता है, तो वह एक कांस्टेंट बन जाता है। उसे केवल एक बार इनिशियलाइज़ किया जा सकता है (या तो घोषणा के समय या कंस्ट्रक्टर के अंदर)। final int MAX_SPEED = 120;
  • final मेथड: यदि कोई मेथड final घोषित किया जाता है, तो उसे सबक्लास में ओवरराइड (override) नहीं किया जा सकता है। इसका उपयोग यह सुनिश्चित करने के लिए किया जाता है कि मेथड का व्यवहार इनहेरिटेंस के दौरान न बदले। class Parent { final void display() { ... } }
  • final क्लास: यदि कोई क्लास final घोषित की जाती है, तो उसे इनहेरिट (extend) नहीं किया जा सकता है। उदाहरण के लिए, जावा में String क्लास final है। final class ImmutableClass { ... }

‘super’ कीवर्ड:

‘super’ कीवर्ड एक रिफरेंस वेरिएबल है जिसका उपयोग तत्काल पैरेंट क्लास (superclass) के ऑब्जेक्ट को रिफर करने के लिए किया जाता है।

  • सुपरक्लास के कंस्ट्रक्टर को कॉल करना: super() का उपयोग सबक्लास के कंस्ट्रक्टर से सुपरक्लास के कंस्ट्रक्टर को कॉल करने के लिए किया जाता है। यह कंस्ट्रक्टर में पहला स्टेटमेंट होना चाहिए।
    class Animal { Animal() { System.out.println("Animal is created"); }}class Dog extends Animal { Dog() { super(); // Animal कंस्ट्रक्टर को कॉल करता है System.out.println("Dog is created"); }} 
  • सुपरक्लास के मेथड्स को एक्सेस करना: यदि सबक्लास में एक मेथड है जो सुपरक्लास के मेथड को ओवरराइड करता है, तो super कीवर्ड का उपयोग सुपरक्लास के ओरिजिनल मेथड को कॉल करने के लिए किया जा सकता है।
    class Vehicle { void move() { System.out.println("Vehicle is moving"); }}class Car extends Vehicle { void move() { super.move(); // Vehicle के move() मेथड को कॉल करता है System.out.println("Car is moving"); }} 

(f) दो 3×3 मैट्रिक्स का योग करने के लिए जावा प्रोग्राम

public class MatrixAddition { public static void main(String[] args) { // पहला 3×3 मैट्रिक्स int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // दूसरा 3×3 मैट्रिक्स int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; // परिणाम को संग्रहीत करने के लिए एक 3×3 मैट्रिक्स बनाना int[][] sumMatrix = new int[3][3]; // मैट्रिक्स को जोड़ने के लिए लूप // बाहरी लूप पंक्तियों (rows) के लिए for (int i = 0; i < 3; i++) { // भीतरी लूप कॉलम (columns) के लिए for (int j = 0; j < 3; j++) { // संबंधित एलिमेंट्स को जोड़ना और परिणाम मैट्रिक्स में संग्रहीत करना sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // परिणामी मैट्रिक्स को प्रिंट करना System.out.println(“Sum of the two matrices is:”); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(sumMatrix[i][j] + ” “); } System.out.println(); // अगली पंक्ति के लिए नई लाइन } } } (g) JDBC में ResultSet इंटरफ़ेस का उपयोग

ResultSet इंटरफ़ेस (java.sql.ResultSet) JDBC API का एक महत्वपूर्ण हिस्सा है। यह एक डेटाबेस क्वेरी के परिणामों का प्रतिनिधित्व करता है। जब हम Statement या PreparedStatement ऑब्जेक्ट पर executeQuery() मेथड को कॉल करते हैं, तो यह एक ResultSet ऑब्जेक्ट लौटाता है।

यह एक कर्सर बनाए रखता है जो डेटा की वर्तमान पंक्ति (row) को इंगित करता है। प्रारंभ में, कर्सर पहली पंक्ति से पहले स्थित होता है।

उपयोग:

  • नेविगेशन: next() मेथड कर्सर को अगली पंक्ति पर ले जाता है। यदि अगली पंक्ति मौजूद है तो यह `true` लौटाता है, अन्यथा `false` लौटाता है। इसका उपयोग आमतौर पर `while` लूप में परिणामों के माध्यम से आइटरेट करने के लिए किया जाता है।
  • डेटा रिट्रीवल: ResultSet विभिन्न getter मेथड्स प्रदान करता है (जैसे `getInt()`, `getString()`, `getDouble()`, `getDate()`) ताकि वर्तमान पंक्ति से कॉलम डेटा को उनके डेटा प्रकार के अनुसार पुनर्प्राप्त किया जा सके। हम या तो कॉलम इंडेक्स (1 से शुरू) या कॉलम नाम का उपयोग कर सकते हैं।

उदाहरण प्रोग्राम:

import java.sql.*; public class ResultSetExample { public static void main(String[] args) { String url = “jdbc:mysql://localhost:3306/yourdatabase”; String user = “username”; String password = “password”; String query = “SELECT id, name, salary FROM employees”; try (Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query)) { // ResultSet में आइटरेट करना System.out.println(“Employee Details:”); while (rs.next()) { // कॉलम इंडेक्स या नाम द्वारा डेटा पुनर्प्राप्त करना int id = rs.getInt(“id”); String name = rs.getString(“name”); double salary = rs.getDouble(“salary”); // परिणाम प्रिंट करना System.out.println(“ID: ” + id + “, Name: ” + name + “, Salary: ” + salary); } } catch (SQLException e) { e.printStackTrace(); } } }

नोट: इस कोड को चलाने के लिए एक डेटाबेस और संबंधित JDBC ड्राइवर की आवश्यकता होगी। (h) जावा में फंक्शन ओवरलोडिंग का लाभ

फंक्शन ओवरलोडिंग (या मेथड ओवरलोडिंग) एक ही क्लास में एक ही नाम के कई मेथड्स को परिभाषित करने की क्षमता है, जब तक कि उनके पैरामीटर लिस्ट (पैरामीटर्स की संख्या या प्रकार) अलग-अलग हों। यह कंपाइल-टाइम पॉलीमॉर्फिज्म का एक उदाहरण है।

लाभ:

  • पठनीयता (Readability): ओवरलोडिंग प्रोग्राम की पठनीयता को बढ़ाता है। प्रोग्रामर्स को एक ही ऑपरेशन के लिए अलग-अलग मेथड नाम याद रखने की आवश्यकता नहीं होती है। उदाहरण के लिए, `add` नाम का एक मेथड पूर्णांकों, डबल्स या अन्य प्रकारों को जोड़ने के लिए उपयोग किया जा सकता है।
  • कोड पुन: प्रयोज्यता (Code Reusability): यह आपको एक ही नाम के तहत समान कार्यक्षमता वाले मेथड्स को समूहित करने की अनुमति देता है, जिससे कोड अधिक संगठित होता है।
  • लचीलापन (Flexibility): यह विभिन्न प्रकार के इनपुट के साथ काम करने के लिए लचीलापन प्रदान करता है। उदाहरण के लिए, `System.out.println()` मेथड को किसी भी डेटा प्रकार (int, String, double, आदि) को प्रिंट करने के लिए ओवरलोड किया गया है।

उदाहरण प्रोग्राम:

class Calculator { // दो पूर्णांकों को जोड़ने के लिए मेथड public int add(int a, int b) { System.out.println(“Adding two integers:”); return a + b; } // दो डबल्स को जोड़ने के लिए ओवरलोडेड मेथड public double add(double a, double b) { System.out.println(“Adding two doubles:”); return a + b; } // तीन पूर्णांकों को जोड़ने के लिए ओवरलोडेड मेथड public int add(int a, int b, int c) { System.out.println(“Adding three integers:”); return a + b + c; } } public class OverloadingDemo { public static void main(String[] args) { Calculator calc = new Calculator(); // कंपाइलर पैरामीटर के आधार पर सही मेथड को कॉल करता है System.out.println(“Sum: ” + calc.add(10, 20)); System.out.println(“Sum: ” + calc.add(10.5, 20.5)); System.out.println(“Sum: ” + calc.add(10, 20, 30)); } }

Q2. (a) मल्टीथ्रेडिंग (multithreading) क्या है? जावा में थ्रेड के निर्माण को दर्शाने के लिए उपयुक्त कोड लिखें। साथ ही, मल्टीथ्रेडेड प्रोग्रामिंग में isAlive( ) मेथड के उपयोग को एक प्रोग्राम की सहायता से समझाएं। अपने कोड को उपयुक्त टिप्पणियों के साथ समर्थित करें। 10 (b) नंबर क्लास (Number Class) क्या है? parseInt (String s) मेथड के उपयोग को एक उदाहरण की सहायता से समझाएं। 5 (c) जावा एफएक्स (Java FX) में इवेंट हैंडलिंग (event handling) को एक उदाहरण की सहायता से समझाएं। 5

Ans.

(a) मल्टीथ्रेडिंग (Multithreading)

मल्टीथ्रेडिंग एक प्रक्रिया (process) के भीतर कई थ्रेड्स (हल्के उप-प्रक्रियाओं) को एक साथ निष्पादित (execute) करने की एक अवधारणा है। प्रत्येक थ्रेड का अपना निष्पादन पथ (execution path) होता है, लेकिन वे प्रक्रिया के मेमोरी स्पेस को साझा करते हैं। यह एक सीपीयू (CPU) को एक ही समय में कई कार्यों के बीच स्विच करने की अनुमति देता है, जिससे प्रदर्शन और जवाबदेही (responsiveness) में सुधार होता है।

जावा में थ्रेड बनाना:

जावा में थ्रेड बनाने के दो मुख्य तरीके हैं:

  1. `Thread` क्लास को एक्सटेंड करके: एक क्लास बनाएं जो `java.lang.Thread` क्लास को एक्सटेंड करती है और उसके `run()` मेथड को ओवरराइड करती है।
  2. `Runnable` इंटरफ़ेस को इम्प्लीमेंट करके: एक क्लास बनाएं जो `java.lang.Runnable` इंटरफ़ेस को इम्प्लीमेंट करती है और उसके `run()` मेथड को इम्प्लीमेंट करती है। फिर इस क्लास का एक ऑब्जेक्ट बनाएं और इसे `Thread` क्लास के कंस्ट्रक्टर में पास करें। यह तरीका पसंदीदा है क्योंकि यह मल्टीपल इनहेरिटेंस की अनुमति देता है।

थ्रेड बनाने का कोड (`Runnable` इंटरफ़ेस का उपयोग करके):

// Runnable इंटरफ़ेस को इम्प्लीमेंट करके एक थ्रेड बनाना class MyThread implements Runnable { private String threadName; MyThread(String name) { this.threadName = name; } // run() मेथड में थ्रेड का निष्पादन कोड होता है public void run() { System.out.println(threadName + ” is running.”); try { for (int i = 0; i < 3; i++) { System.out.println(threadName + “: ” + i); Thread.sleep(500); // थ्रेड को 500 मिलीसेकंड के लिए रोकता है } } catch (InterruptedException e) { System.out.println(threadName + ” was interrupted.”); } System.out.println(threadName + ” has finished.”); } } public class ThreadCreationDemo { public static void main(String[] args) { // Runnable का ऑब्जेक्ट बनाना MyThread myRunnable = new MyThread(“Thread-1”);

// Thread क्लास के कंस्ट्रक्टर में Runnable ऑब्जेक्ट पास करना Thread t1 = new Thread(myRunnable);

// थ्रेड शुरू करना, जो run() मेथड को कॉल करेगा t1.start(); } } `isAlive()` मेथड का उपयोग:

`isAlive()` मेथड यह जांचने के लिए उपयोग किया जाता है कि कोई थ्रेड अभी भी चल रहा है या नहीं। यदि थ्रेड शुरू हो चुका है और अभी तक समाप्त नहीं हुआ है, तो यह `true` लौटाता है; अन्यथा, यह `false` लौटाता है। यह मुख्य थ्रेड को अन्य थ्रेड्स के पूरा होने तक प्रतीक्षा करने के लिए उपयोगी है। `isAlive()` का उदाहरण प्रोग्राम:

public class IsAliveExample { public static void main(String[] args) { // एक Runnable ऑब्जेक्ट और एक थ्रेड बनाना MyThread runnable = new MyThread(“WorkerThread”); Thread workerThread = new Thread(runnable);

// यह जांचना कि थ्रेड शुरू होने से पहले जीवित है या नहीं System.out.println(“Before starting, is workerThread alive? ” + workerThread.isAlive()); // false लौटाएगा // थ्रेड शुरू करना workerThread.start();

// यह जांचना कि थ्रेड शुरू होने के बाद जीवित है या नहीं System.out.println(“After starting, is workerThread alive? ” + workerThread.isAlive()); // true लौटाएगा

try { // मुख्य थ्रेड को वर्कर थ्रेड के पूरा होने का इंतजार करना // हम isAlive() का उपयोग करके लूप कर सकते हैं while(workerThread.isAlive()) { System.out.println(“Main thread is waiting for WorkerThread to finish…”); Thread.sleep(1000); // थोड़ी देर प्रतीक्षा करें } } catch (InterruptedException e) { e.printStackTrace(); } // यह जांचना कि थ्रेड समाप्त होने के बाद जीवित है या नहीं System.out.println(“After finishing, is workerThread alive? ” + workerThread.isAlive()); // false लौटाएगा

System.out.println(“Main thread is finishing.”); } } // पिछले उदाहरण से MyThread क्लास का पुन: उपयोग करें /* class MyThread implements Runnable { // … (ऊपर जैसा ही कोड) … } */ (b) नंबर क्लास (Number Class)

`java.lang.Number` क्लास जावा में एक एब्स्ट्रैक्ट क्लास है। यह उन सभी रैपर क्लास (wrapper classes) की सुपरक्लास है जो न्यूमेरिक वैल्यूज का प्रतिनिधित्व करती हैं, जैसे `Integer`, `Long`, `Double`, `Float`, `Byte`, और `Short`।

चूंकि `Number` एक एब्स्ट्रैक्ट क्लास है, इसलिए आप इसका सीधे ऑब्जेक्ट नहीं बना सकते। इसका मुख्य उद्देश्य एक सामान्य सुपरटाइप प्रदान करना है ताकि सभी न्यूमेरिक रैपर क्लास को एक समान तरीके से ट्रीट किया जा सके।

यह छह मेथड्स को परिभाषित करता है जिन्हें सभी सबक्लास को इम्प्लीमेंट करना होता है: `intValue()`, `longValue()`, `floatValue()`, `doubleValue()`, `byteValue()`, और `shortValue()`। ये मेथड्स एक न्यूमेरिक प्रकार को दूसरे में बदलने की अनुमति देते हैं। `parseInt(String s)` मेथड:

`parseInt(String s)` `Integer` क्लास का एक स्टैटिक मेथड है (न कि `Number` क्लास का)। इसका उपयोग एक स्ट्रिंग आर्ग्यूमेंट को पार्स करके एक साइन्ड डेसीमल इंटीजर (signed decimal integer) में बदलने के लिए किया जाता है।

  • यह एक `String` को इनपुट के रूप में लेता है।
  • यह एक प्रिमिटिव `int` प्रकार की वैल्यू लौटाता है।
  • यदि स्ट्रिंग में एक पार्स करने योग्य इंटीजर नहीं है, तो यह `NumberFormatException` फेंकता है।

उदाहरण:

public class ParseIntExample { public static void main(String[] args) { String strNumber = “123”;

try { // स्ट्रिंग “123” को इंटीजर 123 में बदलना int number = Integer.parseInt(strNumber);

// परिणाम का उपयोग करना System.out.println(“The parsed integer is: ” + number);

// अब हम इस पर गणितीय ऑपरेशन कर सकते हैं int result = number + 7; System.out.println(“Result after adding 7: ” + result); } catch (NumberFormatException e) { // यदि स्ट्रिंग एक वैध संख्या नहीं है तो इसे हैंडल करें System.err.println(“Invalid number format: ” + strNumber); }

String invalidStr = “123a”; try { int invalidNumber = Integer.parseInt(invalidStr); } catch (NumberFormatException e) { System.err.println(“Caught exception for invalid string: ” + e.getMessage()); } } } (c) जावा एफएक्स (JavaFX) में इवेंट हैंडलिंग

जावा एफएक्स (JavaFX) में, इवेंट हैंडलिंग एक मैकेनिज्म है जो यूजर के कार्यों (जैसे बटन क्लिक, की प्रेस, माउस मूवमेंट) या सिस्टम द्वारा उत्पन्न घटनाओं पर प्रतिक्रिया करता है। यह GUI एप्लिकेशन को इंटरैक्टिव बनाता है।

इवेंट हैंडलिंग मॉडल में तीन मुख्य घटक होते हैं:

  1. इवेंट सोर्स (Event Source): वह UI कंपोनेंट जो इवेंट उत्पन्न करता है (जैसे, एक `Button`, `TextField`)।
  2. इवेंट ऑब्जेक्ट (Event Object): यह इवेंट के बारे में जानकारी को इनकैप्सुलेट करता है (जैसे, `ActionEvent`, `MouseEvent`)।
  3. इवेंट हैंडलर (Event Handler): यह एक मेथड या ऑब्जेक्ट है जो इवेंट का जवाब देता है। यह `EventHandler` इंटरफ़ेस को इम्प्लीमेंट करता है।

प्रक्रिया:

  1. एक यूजर UI कंपोनेंट (सोर्स) के साथ इंटरैक्ट करता है।
  2. सोर्स एक इवेंट ऑब्जेक्ट बनाता है और उसे उन सभी रजिस्टर्ड हैंडलर्स को भेजता है।
  3. हैंडलर का कोड निष्पादित होता है, जिससे एप्लिकेशन की स्थिति में बदलाव होता है।

उदाहरण: यह उदाहरण एक JavaFX एप्लिकेशन बनाता है जिसमें एक बटन और एक लेबल होता है। जब बटन पर क्लिक किया जाता है, तो इवेंट हैंडलर लेबल के टेक्स्ट को अपडेट करता है। import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class JavaFXEventHandling extends Application { @Override public void start(Stage primaryStage) { primaryStage.setTitle(“Event Handling Example”); // 1. इवेंट सोर्स: एक बटन Button btn = new Button(“Click Me”); // एक लेबल जो परिणाम दिखाएगा Label label = new Label(“Waiting for event…”); // 2. इवेंट हैंडलर: बटन क्लिक पर क्या करना है // हम एक लैम्ब्डा एक्सप्रेशन का उपयोग कर रहे हैं जो एक EventHandler बनाता है btn.setOnAction(event -> { label.setText(“Button was clicked!”); System.out.println(“Button click event handled.”); }); /* // लैम्ब्डा के बिना वैकल्पिक तरीका (एनोनिमस इनर क्लास) btn.setOnAction(new EventHandler

// सीन और स्टेज सेट करना Scene scene = new Scene(vbox, 300, 200); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } } इस उदाहरण में, `btn.setOnAction(…)` मेथड बटन के लिए एक इवेंट हैंडलर को रजिस्टर करता है। जब बटन पर क्लिक किया जाता है, तो एक `ActionEvent` उत्पन्न होता है, और लैम्ब्डा एक्सप्रेशन के अंदर का कोड निष्पादित होता है, जो लेबल के टेक्स्ट को बदल देता है।

Q3. (a) जावा में ‘एक्सेप्शन हैंडलिंग (Exception Handling)’ शब्द का वर्णन करें। एक्सेप्शन हैंडलिंग में ‘throws’ क्लॉज की भूमिका पर, जावा में एक उपयुक्त कोड की सहायता से चर्चा करें। अपने कोड को उपयुक्त टिप्पणियों के साथ समर्थित करें। साथ ही, एक्सेप्शन हैंडलिंग के फायदे भी बताएं। 10 (b) जावा में JDBC का उपयोग करके एक प्रोग्राम लिखें जो कर्मचारियों की जानकारी, जिसमें ID, Name, Date of Birth, Department, position शामिल है, को Employee नामक डेटाबेस तालिका में संग्रहीत करे। अपने कोड को उपयुक्त टिप्पणियों के साथ समर्थित करें। 10

Ans.

(a) एक्सेप्शन हैंडलिंग (Exception Handling)

एक्सेप्शन हैंडलिंग जावा में एक शक्तिशाली मैकेनिज्म है जो रन-टाइम त्रुटियों (जिन्हें एक्सेप्शन कहा जाता है) को संभालने के लिए उपयोग किया जाता है ताकि प्रोग्राम का सामान्य प्रवाह बाधित न हो। एक एक्सेप्शन एक ऐसी घटना है जो प्रोग्राम के निष्पादन के दौरान होती है और प्रोग्राम के सामान्य निर्देशों के प्रवाह को बाधित करती है, जैसे कि शून्य से भाग देना, एक ऐसी फ़ाइल को एक्सेस करना जो मौजूद नहीं है, या नेटवर्क कनेक्शन में समस्या।

जावा में एक्सेप्शन हैंडलिंग को पांच कीवर्ड्स का उपयोग करके प्रबंधित किया जाता है: try, catch, finally, throw, और throws ।

  • try: उस कोड ब्लॉक को घेरता है जिसमें एक्सेप्शन हो सकता है।
  • catch: try ब्लॉक में फेंके गए एक्सेप्शन को पकड़ता है और उसे हैंडल करता है।
  • finally: यह ब्लॉक हमेशा निष्पादित होता है, चाहे एक्सेप्शन हुआ हो या नहीं। इसका उपयोग संसाधनों को साफ करने के लिए किया जाता है।

‘throws’ क्लॉज की भूमिका:

‘throws’ कीवर्ड का उपयोग मेथड सिग्नेचर में यह घोषित करने के लिए किया जाता है कि यह मेथड एक या अधिक प्रकार के चेक्ड एक्सेप्शन (checked exceptions) फेंक सकता है। यह मेथड के अंदर एक्सेप्शन को हैंडल नहीं करता है; इसके बजाय, यह जिम्मेदारी उस मेथड पर डाल देता है जो इसे कॉल करता है। कॉलर मेथड को या तो `try-catch` ब्लॉक का उपयोग करके उस एक्सेप्शन को हैंडल करना होगा या फिर से `throws` क्लॉज का उपयोग करके उसे आगे अपने कॉलर को पास करना होगा। `throws` क्लॉज का उपयोग केवल चेक्ड एक्सेप्शन के लिए आवश्यक है (वे जो `Exception` के सबक्लास हैं लेकिन `RuntimeException` के नहीं)। ‘throws’ क्लॉज के साथ कोड उदाहरण:

import java.io.IOException; class FileProcessor { // यह मेथड घोषित करता है कि यह IOException फेंक सकता है। // यह इसे खुद हैंडल नहीं करता है। public void readFile(String fileName) throws IOException { System.out.println(“Attempting to read file: ” + fileName); if (fileName.equals(“nonexistent.txt”)) { // एक चेक्ड एक्सेप्शन फेंकना throw new IOException(“File not found error!”); } System.out.println(“File read successfully (hypothetical).”); } } public class ThrowsExample { public static void main(String[] args) { FileProcessor processor = new FileProcessor(); // कॉलिंग मेथड को throws द्वारा घोषित एक्सेप्शन को हैंडल करना होगा। try { // एक वैध फ़ाइल नाम के साथ कॉल करना (कोई एक्सेप्शन नहीं) processor.readFile(“data.txt”);

// एक अमान्य फ़ाइल नाम के साथ कॉल करना जो एक्सेप्शन फेंकेगा processor.readFile(“nonexistent.txt”);

} catch (IOException e) { // यहाँ एक्सेप्शन को पकड़ा और हैंडल किया जाता है System.err.println(“Caught an exception in main method: ” + e.getMessage()); }

System.out.println(“Program continues after handling the exception.”); } } इस उदाहरण में, `readFile` मेथड `IOException` को हैंडल नहीं करता है, बल्कि `throws IOException` का उपयोग करके यह घोषित करता है कि यह इसे फेंक सकता है। `main` मेथड, जो `readFile` को कॉल करता है, इस एक्सेप्शन को `try-catch` ब्लॉक का उपयोग करके हैंडल करने के लिए जिम्मेदार है। एक्सेप्शन हैंडलिंग के फायदे:

  1. त्रुटि-हैंडलिंग कोड को सामान्य कोड से अलग करना: यह कोड को अधिक स्वच्छ और पठनीय बनाता है।
  2. प्रोग्राम के सामान्य प्रवाह को बनाए रखना: एक त्रुटि होने पर प्रोग्राम अचानक समाप्त नहीं होता है; यह त्रुटि को शालीनता से संभाल सकता है और जारी रह सकता है।
  3. त्रुटियों का प्रसार (Error Propagation): `throws` क्लॉज का उपयोग करके, एक मेथड त्रुटि को कॉल स्टैक में ऊपर की ओर propagatee कर सकता है, जहां इसे अधिक उपयुक्त रूप से हैंडल किया जा सकता है।
  4. सार्थक त्रुटि रिपोर्टिंग: आप विशिष्ट प्रकार के एक्सेप्शन को पकड़ सकते हैं और उपयोगकर्ता को सार्थक त्रुटि संदेश प्रदान कर सकते हैं।

(b) JDBC का उपयोग करके कर्मचारी जानकारी संग्रहीत करने के लिए जावा प्रोग्राम

यह प्रोग्राम JDBC का उपयोग करके एक MySQL डेटाबेस में `Employee` नामक तालिका में कर्मचारी रिकॉर्ड सम्मिलित करता है। पूर्व-आवश्यकताएँ: 1. एक MySQL डेटाबेस सर्वर चल रहा हो। 2. डेटाबेस में, `Employee` नामक एक तालिका निम्नलिखित संरचना के साथ बनी हो: CREATE TABLE Employee ( ID INT PRIMARY KEY, Name VARCHAR(100), DateOfBirth DATE, Department VARCHAR(50), Position VARCHAR(50) ); 3. MySQL JDBC ड्राइवर (.jar फ़ाइल) प्रोजेक्ट के क्लासपाथ में जोड़ा गया हो। जावा कोड:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Date; public class StoreEmployeeInfo { // डेटाबेस कनेक्शन विवरण private static final String DB_URL = “jdbc:mysql://localhost:3306/your_database_name”; private static final String USER = “your_username”; private static final String PASS = “your_password”; public static void main(String[] args) {

Connection conn = null; PreparedStatement pstmt = null; try { // चरण 1: JDBC ड्राइवर को लोड करना (आधुनिक JDBC में वैकल्पिक) // Class.forName(“com.mysql.cj.jdbc.Driver”); // चरण 2: डेटाबेस से कनेक्शन स्थापित करना System.out.println(“Connecting to database…”); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println(“Connection successful!”); // चरण 3: PreparedStatement के लिए SQL क्वेरी बनाना // PreparedStatement SQL इंजेक्शन हमलों से बचाता है और प्रदर्शन में सुधार करता है String sql = “INSERT INTO Employee (ID, Name, DateOfBirth, Department, Position) VALUES (?, ?, ?, ?, ?)”;

pstmt = conn.prepareStatement(sql); // कर्मचारी डेटा int id = 101; String name = “Suresh Sharma”; // java.sql.Date के लिए, हम java.time.LocalDate का उपयोग कर सकते हैं java.time.LocalDate dob = java.time.LocalDate.of(1990, 5, 15); String department = “IT”; String position = “Software Engineer”; // चरण 4: स्टेटमेंट में पैरामीटर सेट करना pstmt.setInt(1, id); // पहला ‘?’ pstmt.setString(2, name); // दूसरा ‘?’ pstmt.setDate(3, Date.valueOf(dob)); // तीसरा ‘?’ pstmt.setString(4, department); // चौथा ‘?’ pstmt.setString(5, position); // पाँचवाँ ‘?’ // चरण 5: क्वेरी को निष्पादित करना int rowsAffected = pstmt.executeUpdate();

if (rowsAffected > 0) { System.out.println(“A new employee was inserted successfully!”); } } catch (SQLException se) { // JDBC त्रुटियों को हैंडल करना se.printStackTrace(); } catch (Exception e) { // Class.forName() त्रुटियों को हैंडल करना e.printStackTrace(); } finally { // चरण 6: संसाधनों को बंद करना // finally ब्लॉक का उपयोग यह सुनिश्चित करता है कि संसाधन हमेशा बंद हों try { if (pstmt != null) pstmt.close(); } catch (SQLException se2) { } // कुछ नहीं करना try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } System.out.println(“Goodbye!”); } }

टिप्पणी: आपको `your_database_name`, `your_username`, और `your_password` को अपने वास्तविक डेटाबेस क्रेडेंशियल्स से बदलना होगा।

Q4. (a) पॉलीमॉर्फिज्म (Polymorphism) क्या है? जावा द्वारा समर्थित विभिन्न प्रकार के पॉलीमॉर्फिज्म को प्रत्येक के लिए उदाहरण कोड के साथ समझाएं। 10 (b) जावा में स्ट्रीम क्लास (stream classes) का उद्देश्य क्या है? बाइट स्ट्रीम (byte streams) कैरेक्टर स्ट्रीम (character streams) से कैसे भिन्न हैं? प्रत्येक के लिए उपयुक्त उदाहरण दें। 10

Ans.

(a) पॉलीमॉर्फिज्म (Polymorphism)

पॉलीमॉर्फिज्म एक ग्रीक शब्द है जिसका अर्थ है “कई रूप”। ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग में, यह एक वेरिएबल, फंक्शन या ऑब्जेक्ट की कई रूपों में प्रकट होने की क्षमता को संदर्भित करता है। सरल शब्दों में, यह एक ही क्रिया को अलग-अलग तरीकों से करने की अनुमति देता है। उदाहरण के लिए, एक `+` ऑपरेटर संख्याओं को जोड़ता है और स्ट्रिंग्स को जोड़ता है।

जावा में पॉलीमॉर्फिज्म दो प्रकार का होता है:

  1. कंपाइल-टाइम पॉलीमॉर्फिज्म (Compile-time Polymorphism) / स्टैटिक बाइंडिंग: इसे मेथड ओवरलोडिंग के माध्यम से प्राप्त किया जाता है। कंपाइलर कंपाइलेशन के समय यह निर्धारित करता है कि कौन सा मेथड कॉल किया जाएगा, जो मेथड के सिग्नेचर (पैरामीटर की संख्या और प्रकार) पर आधारित होता है।
  2. रन-टाइम पॉलीमॉर्फिज्म (Run-time Polymorphism) / डायनेमिक बाइंडिंग: इसे मेथड ओवरराइडिंग के माध्यम से प्राप्त किया जाता है। रनटाइम पर यह निर्धारित किया जाता है कि कौन सा मेथड निष्पादित होगा, जो ऑब्जेक्ट के प्रकार पर आधारित होता है।

1. कंपाइल-टाइम पॉलीमॉर्फिज्म (मेथड ओवरलोडिंग) एक ही क्लास में एक ही नाम के कई मेथड्स को परिभाषित करना, बशर्ते उनके पैरामीटर लिस्ट अलग-अलग हों (या तो पैरामीटर्स की संख्या में या उनके प्रकार में)।

उदाहरण कोड:

class Display { // एक पूर्णांक प्रदर्शित करने के लिए मेथड public void show(int num) { System.out.println(“Displaying integer: ” + num); }

// एक स्ट्रिंग प्रदर्शित करने के लिए ओवरलोडेड मेथड public void show(String text) { System.out.println(“Displaying string: ” + text); } } public class OverloadingExample { public static void main(String[] args) { Display d = new Display(); // कंपाइलर जानता है कि आर्ग्यूमेंट के प्रकार के आधार पर कौन सा show() कॉल करना है d.show(100); d.show(“Hello Polymorphism”); } }

2. रन-टाइम पॉलीमॉर्फिज्म (मेथड ओवरराइडिंग) जब एक सबक्लास (child class) एक मेथड के लिए एक विशिष्ट कार्यान्वयन प्रदान करती है जो पहले से ही उसकी सुपरक्लास (parent class) में परिभाषित है, तो इसे मेथड ओवरराइडिंग कहा जाता है। ओवरराइडिंग के लिए मेथड का नाम, पैरामीटर लिस्ट और रिटर्न टाइप (या कोवैरिएंट टाइप) समान होना चाहिए।

उदाहरण कोड:

// सुपरक्लास class Animal { public void makeSound() { System.out.println(“The animal makes a sound”); } } // सबक्लास 1 class Dog extends Animal { // makeSound() मेथड को ओवरराइड करना @Override public void makeSound() { System.out.println(“The dog barks”); } } // सबक्लास 2 class Cat extends Animal { // makeSound() मेथड को ओवरराइड करना @Override public void makeSound() { System.out.println(“The cat meows”); } } public class OverridingExample { public static void main(String[] args) { // सुपरक्लास का रिफरेंस, लेकिन सबक्लास का ऑब्जेक्ट Animal myAnimal = new Animal(); // Animal रिफरेंस, Animal ऑब्जेक्ट Animal myDog = new Dog(); // Animal रिफरेंस, Dog ऑब्जेक्ट Animal myCat = new Cat(); // Animal रिफरेंस, Cat ऑब्जेक्ट // रनटाइम पर JVM तय करता है कि किस ऑब्जेक्ट के मेथड को कॉल करना है myAnimal.makeSound(); // The animal makes a sound myDog.makeSound(); // The dog barks myCat.makeSound(); // The cat meows } } इस उदाहरण में, `myDog.makeSound()` हमेशा `Dog` क्लास के मेथड को कॉल करेगा, भले ही रिफरेंस प्रकार `Animal` हो। यह रन-टाइम पर तय होता है, इसलिए इसे रन-टाइम पॉलीमॉर्फिज्म कहा जाता है। (b) जावा में स्ट्रीम क्लासेस

जावा में, स्ट्रीम डेटा का एक अनुक्रम (sequence) है। `java.io` पैकेज में स्ट्रीम क्लासेस का मुख्य उद्देश्य इनपुट और आउटपुट (I/O) ऑपरेशनों को संभालना है। ये क्लासेस जावा एप्लिकेशन को विभिन्न स्रोतों (जैसे फ़ाइलें, नेटवर्क कनेक्शन, मेमोरी बफ़र्स) से डेटा पढ़ने और विभिन्न गंतव्यों (destinations) पर डेटा लिखने की अनुमति देती हैं।

जावा में दो मुख्य प्रकार की स्ट्रीम होती हैं:

1. बाइट स्ट्रीम (Byte Streams):

  • ये 8-बिट बाइट्स के रूप में डेटा को पढ़ते और लिखते हैं।
  • ये सभी प्रकार के डेटा, जैसे कि टेक्स्ट, इमेज, वीडियो, और बाइनरी फ़ाइलों को संभालने के लिए उपयुक्त हैं।
  • इनकी मुख्य एब्स्ट्रैक्ट सुपरक्लास `InputStream` (पढ़ने के लिए) और `OutputStream` (लिखने के लिए) हैं।
  • उदाहरण: `FileInputStream`, `FileOutputStream`, `ByteArrayInputStream`।

2. कैरेक्टर स्ट्रीम (Character Streams):

  • ये 16-बिट यूनिकोड कैरेक्टर्स के रूप में डेटा को पढ़ते और लिखते हैं।
  • ये विशेष रूप से टेक्स्ट फ़ाइलों को संभालने के लिए डिज़ाइन किए गए हैं क्योंकि वे आंतरिक रूप से बाइट्स और कैरेक्टर्स के बीच रूपांतरण को संभालते हैं, जो विभिन्न कैरेक्टर एन्कोडिंग के साथ काम करते समय सहायक होता है।
  • इनकी मुख्य एब्स्ट्रैक्ट सुपरक्लास `Reader` (पढ़ने के लिए) और `Writer` (लिखने के लिए) हैं।
  • उदाहरण: `FileReader`, `FileWriter`, `BufferedReader`।

बाइट स्ट्रीम और कैरेक्टर स्ट्रीम के बीच अंतर:

विशेषता

बाइट स्ट्रीम

कैरेक्टर स्ट्रीम

डेटा इकाई

8-बिट बाइट्स में डेटा को संभालता है।

16-बिट यूनिकोड कैरेक्टर्स में डेटा को संभालता है।

उपयोग

रॉ बाइनरी डेटा, जैसे इमेज, ऑडियो, वीडियो और निष्पादन योग्य फ़ाइलों के लिए आदर्श।

टेक्स्ट डेटा और टेक्स्ट फ़ाइलों को संभालने के लिए आदर्श, क्योंकि यह कैरेक्टर एन्कोडिंग को संभालता है।

सुपरक्लास

`InputStream` और `OutputStream`।

`Reader` और `Writer`।

दक्षता

टेक्स्ट डेटा के लिए कम कुशल क्योंकि यह कैरेक्टर एन्कोडिंग को सीधे नहीं समझता है।

टेक्स्ट डेटा के लिए अधिक कुशल।

बाइट स्ट्रीम का उदाहरण (`FileInputStream`): यह कोड एक फ़ाइल से बाइट्स को पढ़ता है और उन्हें कंसोल पर प्रिंट करता है। import java.io.FileInputStream; import java.io.IOException; public class ByteStreamExample { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream(“source.txt”)) { int byteData; System.out.println(“Reading with Byte Stream:”); // फ़ाइल के अंत तक एक-एक बाइट पढ़ें while ((byteData = fis.read()) != -1) { // बाइट को कैरेक्टर में कास्ट करके प्रिंट करें System.out.print((char) byteData); } } catch (IOException e) { e.printStackTrace(); } } } कैरेक्टर स्ट्रीम का उदाहरण (`FileReader`): यह कोड एक फ़ाइल से कैरेक्टर्स को पढ़ता है और उन्हें कंसोल पर प्रिंट करता है। import java.io.FileReader; import java.io.IOException; public class CharacterStreamExample { public static void main(String[] args) { try (FileReader fr = new FileReader(“source.txt”)) { int charData; System.out.println(“\nReading with Character Stream:”); // फ़ाइल के अंत तक एक-एक कैरेक्टर पढ़ें while ((charData = fr.read()) != -1) { // कैरेक्टर को सीधे प्रिंट करें System.out.print((char) charData); } } catch (IOException e) { e.printStackTrace(); } } } दोनों उदाहरणों के लिए `source.txt` नामक एक टेक्स्ट फ़ाइल की आवश्यकता होगी।

Q5. निम्नलिखित पर संक्षिप्त नोट्स लिखें: 4×5=20 (a) CallableStatement इंटरफ़ेस (b) गार्बेज कलेक्शन और गार्बेज कलेक्शन में finalize( ) मेथड की भूमिका (c) JavaFX और इसकी विशेषताएँ (d) TreeSet और HashSet की उपयोगिता

Ans.

(a) CallableStatement इंटरफ़ेस

`java.sql.CallableStatement` इंटरफ़ेस JDBC API का एक हिस्सा है और इसका उपयोग डेटाबेस में संग्रहीत प्रक्रियाओं (stored procedures) को निष्पादित करने के लिए किया जाता है। संग्रहीत प्रक्रियाएँ SQL स्टेटमेंट्स का एक पूर्व-संकलित समूह होती हैं जिन्हें डेटाबेस सर्वर पर संग्रहीत किया जाता है और एक नाम से कॉल किया जा सकता है।

`CallableStatement` `PreparedStatement` इंटरफ़ेस को एक्सटेंड करता है, इसलिए इसमें `PreparedStatement` की सभी कार्यक्षमताएँ होती हैं, जैसे पैरामीटराइज्ड क्वेरी चलाना। इसकी मुख्य विशेषताएँ हैं:

  • आउटपुट पैरामीटर्स (OUT) को संभालना: संग्रहीत प्रक्रियाएँ मान लौटा सकती हैं। `CallableStatement` आपको `registerOutParameter()` मेथड का उपयोग करके इन OUT पैरामीटर्स को रजिस्टर करने और फिर `getInt()`, `getString()` आदि जैसे गेटर मेथड्स का उपयोग करके मान प्राप्त करने की अनुमति देता है।
  • इनपुट/आउटपुट पैरामीटर्स (INOUT) को संभालना: यह उन पैरामीटर्स को भी संभाल सकता है जो इनपुट और आउटपुट दोनों के रूप में कार्य करते हैं।
  • निष्पादन: संग्रहीत प्रक्रिया को `execute()` या `executeUpdate()` मेथड का उपयोग करके निष्पादित किया जाता है।
  • सिंटेक्स: कॉल करने का सिंटेक्स `{call procedure_name(?, ?)}` जैसा होता है, जहाँ `?` प्लेसहोल्डर पैरामीटर्स के लिए होते हैं।

`CallableStatement` का उपयोग प्रदर्शन में सुधार कर सकता है क्योंकि संग्रहीत प्रक्रियाएँ पूर्व-संकलित होती हैं और यह नेटवर्क ट्रैफ़िक को कम करता है। (b) गार्बेज कलेक्शन और finalize() मेथड की भूमिका

गार्बेज कलेक्शन (GC) जावा वर्चुअल मशीन (JVM) की एक स्वचालित मेमोरी प्रबंधन प्रक्रिया है। जावा में, प्रोग्रामर्स को मैन्युअल रूप से ऑब्जेक्ट्स द्वारा उपयोग की गई मेमोरी को डी-एलोकेट करने की आवश्यकता नहीं होती है, जैसा कि C++ जैसी भाषाओं में होता है। गार्बेज कलेक्टर पृष्ठभूमि में चलता है और उन ऑब्जेक्ट्स की पहचान करता है जो अब प्रोग्राम द्वारा उपयोग में नहीं हैं (यानी, उन तक कोई सक्रिय रिफरेंस नहीं है)। फिर यह इन “गार्बेज” ऑब्जेक्ट्स द्वारा घेरी गई मेमोरी को पुनः प्राप्त (reclaim) कर लेता है, जिससे यह मेमोरी भविष्य के ऑब्जेक्ट्स के लिए उपलब्ध हो जाती है। यह मेमोरी लीक को रोकने में मदद करता है।

`finalize()` मेथड की भूमिका:

`java.lang.Object` क्लास में `protected void finalize() throws Throwable` मेथड होता है। गार्बेज कलेक्टर द्वारा किसी ऑब्जेक्ट की मेमोरी को पुनः प्राप्त करने से ठीक पहले यह मेथड उस ऑब्जेक्ट पर कॉल किया जाता है। इसका उद्देश्य ऑब्जेक्ट को नष्ट करने से पहले किसी भी अंतिम सफाई (cleanup) गतिविधियों को करने का अवसर देना है, जैसे कि गैर-जावा संसाधनों (जैसे फ़ाइल हैंडल या नेटिव ग्राफिक्स संसाधन) को जारी करना।

हालांकि, `finalize()` पर निर्भर रहने की अनुशंसा नहीं की जाती है क्योंकि:

  • इसकी कोई गारंटी नहीं है कि इसे कब (या यदि) कॉल किया जाएगा।
  • यह प्रदर्शन को नकारात्मक रूप से प्रभावित कर सकता है।
  • Java 9 से इसे पदावनत (deprecated) कर दिया गया है।

संसाधनों की सफाई के लिए `try-with-resources` स्टेटमेंट या `finally` ब्लॉक का उपयोग करना एक बेहतर और अधिक विश्वसनीय तरीका है। (c) JavaFX और इसकी विशेषताएँ

JavaFX एक आधुनिक, ओपन-सोर्स प्लेटफॉर्म है जिसका उपयोग डेस्कटॉप एप्लिकेशन और रिच इंटरनेट एप्लिकेशन (RIA) बनाने के लिए किया जाता है। यह जावा के लिए स्विंग (Swing) और AWT का उत्तराधिकारी है, जो एक समृद्ध और अधिक आधुनिक GUI टूलकिट प्रदान करता है।

मुख्य विशेषताएँ:

  • FXML: यह एक XML-आधारित मार्कअप भाषा है जो आपको जावा कोड से UI के लेआउट को अलग करने की अनुमति देती है। यह UI डिजाइन को सरल बनाता है और डेवलपर्स और डिजाइनरों के बीच सहयोग की सुविधा प्रदान करता है।
  • CSS के साथ स्टाइलिंग: JavaFX एप्लिकेशन को कैस्केडिंग स्टाइल शीट्स (CSS) का उपयोग करके स्टाइल किया जा सकता है, जिससे UI को अनुकूलित करना और थीम बनाना आसान हो जाता है।
  • रिच UI कंट्रोल्स: यह चार्ट्स, टेबल्स, ट्रीज, मेनू और बहुत कुछ सहित बिल्ट-इन UI कंट्रोल्स का एक व्यापक सेट प्रदान करता है।
  • ग्राफिक्स और मल्टीमीडिया: JavaFX में 2D और 3D ग्राफिक्स के लिए शक्तिशाली API हैं। यह ऑडियो और वीडियो प्लेबैक सहित मल्टीमीडिया सामग्री का भी समर्थन करता है।
  • WebView: इसमें एक `WebView` कंपोनेंट शामिल है जो HTML5, CSS3, और जावास्क्रिप्ट का समर्थन करने वाले वेब पेजों को सीधे एप्लिकेशन के भीतर एम्बेड और प्रस्तुत कर सकता है।
  • हार्डवेयर-एक्सेलरेटेड ग्राफिक्स: यह ग्राफिक्स पाइपलाइन का उपयोग करता है जो प्रदर्शन को बेहतर बनाने के लिए GPU का लाभ उठाता है, जिससे स्मूथ एनिमेशन और रेंडरिंग होती है।

(d) TreeSet और HashSet की उपयोगिता

`HashSet` और `TreeSet` दोनों `java.util.Set` इंटरफ़ेस के कार्यान्वयन हैं, जिसका अर्थ है कि वे डुप्लिकेट एलिमेंट्स के संग्रह की अनुमति नहीं देते हैं। हालांकि, वे आंतरिक रूप से एलिमेंट्स को अलग-अलग तरीके से संग्रहीत और प्रबंधित करते हैं, जिससे उनकी उपयोगिता अलग-अलग होती है।

HashSet की उपयोगिता:

  • कार्यान्वयन: यह एक हैश टेबल (`HashMap` इंस्टेंस) पर आधारित है।
  • ऑर्डरिंग: `HashSet` एलिमेंट्स के किसी भी क्रम की गारंटी नहीं देता है। एलिमेंट्स का क्रम समय के साथ बदल सकता है।
  • प्रदर्शन: यह `add()`, `remove()`, और `contains()` ऑपरेशनों के लिए बहुत तेज, स्थिर-समय (O(1)) प्रदर्शन प्रदान करता है, बशर्ते हैश फंक्शन एलिमेंट्स को बकेट्स में ठीक से वितरित करे।
  • Null वैल्यू: यह एक `null` एलिमेंट की अनुमति देता है।
  • उपयोग: जब आपको केवल यह सुनिश्चित करने की आवश्यकता हो कि संग्रह में कोई डुप्लिकेट न हो और एलिमेंट्स के क्रम की परवाह न हो, तो `HashSet` सबसे अच्छा विकल्प है। यह सबसे तेज `Set` कार्यान्वयन है।

TreeSet की उपयोगिता:

  • कार्यान्वयन: यह एक रेड-ब्लैक ट्री (एक प्रकार का सेल्फ-बैलेंसिंग बाइनरी सर्च ट्री) पर आधारित है।
  • ऑर्डरिंग: `TreeSet` एलिमेंट्स को उनके प्राकृतिक क्रम (natural ordering) के अनुसार या निर्माण के समय प्रदान किए गए `Comparator` के अनुसार सॉर्टेड क्रम में संग्रहीत करता है।
  • प्रदर्शन: `add()`, `remove()`, और `contains()` ऑपरेशनों के लिए प्रदर्शन थोड़ा धीमा होता है, जो लॉग(n) समय (O(log n)) लेता है, जहाँ n एलिमेंट्स की संख्या है।
  • Null वैल्यू: यह `null` एलिमेंट्स की अनुमति नहीं देता है (क्योंकि यह उन्हें सॉर्ट नहीं कर सकता)।
  • उपयोग: जब आपको एक सॉर्टेड सेट की आवश्यकता हो तो `TreeSet` का उपयोग करें। यह उन परिदृश्यों के लिए आदर्श है जहाँ आपको एक यूनिक एलिमेंट्स के संग्रह की आवश्यकता होती है जिसे हमेशा एक विशिष्ट क्रम में आइटरेट किया जाना चाहिए।

IGNOU MCS-206 Previous Year Solved Question Paper in English

Q1. (a) What is encapsulation ? How is encapsulation implemented in Java ? Explain through a program. 5 (b) Differentiate between abstract class and interface in Java. Give example of each. 5 (c) Discuss the utility of map interface in Java, with the help of a program. 5 (d) What is object serialization in Java ? Explain the working and utility of object serialization. 5 (e) Describe the utility of ‘final’ and ‘super’ keywords in Java with suitable code. 5 (f) Write a Java program to find the sum of two matrices of dimension 3 x 3. Support your code with suitable comments. 5 (g) Explain the use of ResultSet interface in JDBC, with the help of a program. 5 (h) Explain the advantage of function overloading in Java with the help of a suitable program. 5

Ans. (a) Encapsulation Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP). It refers to the bundling of data (variables) and the code (methods) that operates on that data into a single unit, called a class. It implements the principle of data hiding , which means the internal state of an object is hidden from other objects and can only be accessed through the object’s own methods. Implementation in Java: In Java, encapsulation is achieved by:

  • Declaring the variables (fields) of a class as private , so they cannot be accessed directly from outside the class.
  • Providing public “getter” and “setter” methods for each variable. The getter method reads the variable’s value, and the setter method updates the variable’s value.


Example Program:

// An encapsulated Employee classclass Employee { // Private data members private String name; private int employeeId;

// Public Getter method for name public String getName() { return name; }

// Public Setter method for name public void setName(String name) { this.name = name; }

// Public Getter method for employeeId public int getEmployeeId() { return employeeId; }

// Public Setter method for employeeId public void setEmployeeId(int employeeId) { // We can also add validation here if (employeeId > 0) { this.employeeId = employeeId; } }}

public class EncapsulationDemo { public static void main(String[] args) { // Creating an Employee object Employee emp = new Employee();

// Setting data using setter methods emp.setName("Ravi Kumar"); emp.setEmployeeId(101);

// Getting data using getter methods System.out.println("Employee Name: " + emp.getName()); System.out.println("Employee ID: " + emp.getEmployeeId()); }}

(b) Difference between Abstract Class and Interface Both abstract classes and interfaces are used to achieve abstraction in Java, but they have key differences:

  • Method Implementation: An abstract class can have both abstract (without a body) and non-abstract (with a body) methods. An interface (before Java 8) could only have abstract methods. Since Java 8, interfaces can also have default and static methods with bodies.
  • Variables: An abstract class can have final, non-final, static, and non-static variables. An interface can only have public static final variables (constants).
  • Constructor: An abstract class can have its own constructor (which is called by its subclass). An interface cannot have a constructor.
  • Keyword: A class uses the extends keyword to inherit an abstract class. A class uses the implements keyword to implement an interface.
  • Multiple Inheritance: A class can extend only one abstract class, but it can implement multiple interfaces.


Example of Abstract Class:

abstract class Animal { Animal() { System.out.println("Animal is created"); } abstract void makeSound(); // abstract method void eat() { System.out.println("Animal is eating"); // non-abstract method }}class Dog extends Animal { void makeSound() { System.out.println("Dog barks"); }}

Example of Interface:

interface Vehicle { void start(); // abstract method void stop();}class Car implements Vehicle { public void start() { System.out.println("Car starts"); } public void stop() { System.out.println("Car stops"); }}

(c) Utility of Map Interface The Map interface in Java is part of the Collections Framework, but it does not extend the Collection interface. It is useful for storing objects as key-value pairs. Each key must be unique, and it maps to a single value. Utility:

  • Fast Data Retrieval: Maps are designed for very fast lookup, update, and deletion of values based on their key.
  • Data Association: It is ideal for scenarios where you need to associate related data, such as mapping a user ID to a user object, or a word to its definition.
  • Unique Keys: It does not allow duplicate keys, which is useful for storing data with unique identifiers.

Java provides several map implementations like

HashMap, TreeMap, and LinkedHashMap

. HashMap is the most commonly used as it provides fast access and does not maintain any order of keys.


Example Program:

import java.util.HashMap;import java.util.Map;

public class MapDemo { public static void main(String[] args) { // Create a HashMap that maps String keys to Integer values Map<String, Integer> studentScores = new HashMap<>();

// Add elements to the map (put method) studentScores.put("Amit", 85); studentScores.put("Priya", 92); studentScores.put("Rahul", 78);

// Get a value using a key (get method) int priyaScore = studentScores.get("Priya"); System.out.println("Priya's Score: " + priyaScore);

// Iterate over the map System.out.println("\nAll Student Scores:"); for (Map.Entry<String, Integer> entry : studentScores.entrySet()) { System.out.println("Student: " + entry.getKey() + ", Score: " + entry.getValue()); }

// Remove a key (remove method) studentScores.remove("Rahul"); System.out.println("\nMap after removing Rahul: " + studentScores); }}

(d) Object Serialization Object serialization is the process of converting the state of a Java object into a byte stream. This byte stream can then be stored in a file, sent over a network, or saved to a database. The reverse process, converting the byte stream back into a Java object, is called deserialization . Working and Utility:

  • Working: To make an object of a class serializable, the class must implement the java.io.Serializable interface. This is a marker interface, meaning it has no methods; it just signals to the JVM that the class can be serialized.
    • Serialization: Using the ObjectOutputStream class, we write the object to an output stream (like FileOutputStream) with the writeObject() method.
    • Deserialization: Using the ObjectInputStream class, we read the object from an input stream with the readObject() method.
  • Utility:
    • Persistence: The state of an object can be saved to disk so it can be retrieved when the application restarts.
    • Communication: Objects can be sent over the network from one Java application to another, such as in Remote Method Invocation (RMI).
    • Caching: Frequently used objects can be serialized and kept in memory or on disk for faster access.

(e) Utility of ‘final’ and ‘super’ Keywords ‘final’ Keyword: The ‘final’ keyword is used to make an entity (variable, method, or class) final, meaning it cannot be modified or changed later.

  • final variable: If a variable is declared final, it becomes a constant. It can be initialized only once (either at declaration or inside the constructor). final int MAX_SPEED = 120;
  • final method: If a method is declared final, it cannot be overridden in a subclass. This is used to ensure the behavior of the method does not change during inheritance. class Parent { final void display() { ... } }
  • final class: If a class is declared final, it cannot be inherited (extended). For example, the String class in Java is final. final class ImmutableClass { ... }

‘super’ Keyword: The ‘super’ keyword is a reference variable that is used to refer to the immediate parent class object.

  • To call superclass’s constructor: super() is used to call the superclass’s constructor from a subclass’s constructor. It must be the first statement in the constructor.
    class Animal { Animal() { System.out.println("Animal is created"); }}class Dog extends Animal { Dog() { super(); // calls the Animal constructor System.out.println("Dog is created"); }} 
  • To access superclass’s methods: If a subclass has a method that overrides a method in the superclass, the super keyword can be used to call the original method from the superclass.
    class Vehicle { void move() { System.out.println("Vehicle is moving"); }}class Car extends Vehicle { void move() { super.move(); // calls the move() method of Vehicle System.out.println("Car is moving"); }} 

(f) Java Program to Find the Sum of Two 3×3 Matrices

public class MatrixAddition { public static void main(String[] args) { // First 3x3 matrix int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

// Second 3x3 matrix int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };

// Create a 3x3 matrix to store the result int[][] sumMatrix = new int[3][3];

// Loop to add the matrices // Outer loop for rows for (int i = 0; i < 3; i++) { // Inner loop for columns for (int j = 0; j < 3; j++) { // Add corresponding elements and store in the result matrix sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } }

// Print the resultant matrix System.out.println("Sum of the two matrices is:"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(sumMatrix[i][j] + " "); } System.out.println(); // New line for the next row } }}

(g) Use of ResultSet Interface in JDBC The ResultSet interface (java.sql.ResultSet) is a crucial part of the JDBC API. It represents the results of a database query. When we call the executeQuery() method on a Statement or PreparedStatement object, it returns a ResultSet object. It maintains a cursor that points to the current row of data. Initially, the cursor is positioned before the first row. Use:

  • Navigation: The next() method moves the cursor to the next row. It returns `true` if the next row exists, and `false` otherwise. This is typically used in a `while` loop to iterate through the results.
  • Data Retrieval: ResultSet provides various getter methods (e.g., `getInt()`, `getString()`, `getDouble()`, `getDate()`) to retrieve column data from the current row according to their data type. We can use either the column index (starting from 1) or the column name.


Example Program:

import java.sql.*;

public class ResultSetExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/yourdatabase"; String user = "username"; String password = "password"; String query = "SELECT id, name, salary FROM employees";

try (Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query)) {

// Iterate through the ResultSet System.out.println("Employee Details:"); while (rs.next()) { // Retrieve data by column index or name int id = rs.getInt("id"); String name = rs.getString("name"); double salary = rs.getDouble("salary");

// Print the results System.out.println("ID: " + id + ", Name: " + name + ", Salary: " + salary); } } catch (SQLException e) { e.printStackTrace(); } }}


Note: This code requires a database and the corresponding JDBC driver to run.

(h) Advantage of Function Overloading in Java Function overloading (or method overloading) is the ability to define multiple methods with the same name in the same class, as long as their parameter lists (number or type of parameters) are different. It is an example of compile-time polymorphism. Advantages:

  • Readability: Overloading improves the readability of the program. Programmers don’t need to remember different method names for the same operation. For instance, a method named `add` can be used to add integers, doubles, or other types.
  • Code Reusability: It allows you to group methods with similar functionality under the same name, making the code more organized.
  • Flexibility: It provides flexibility to work with different types of input. For example, the `System.out.println()` method is overloaded to print any data type (int, String, double, etc.).


Example Program:

class Calculator { // Method to add two integers public int add(int a, int b) { System.out.println("Adding two integers:"); return a + b; }

// Overloaded method to add two doubles public double add(double a, double b) { System.out.println("Adding two doubles:"); return a + b; }

// Overloaded method to add three integers public int add(int a, int b, int c) { System.out.println("Adding three integers:"); return a + b + c; }}

public class OverloadingDemo { public static void main(String[] args) { Calculator calc = new Calculator();

// The compiler calls the correct method based on the parameters System.out.println("Sum: " + calc.add(10, 20)); System.out.println("Sum: " + calc.add(10.5, 20.5)); System.out.println("Sum: " + calc.add(10, 20, 30)); }}

Q2. (a) What is multithreading ? Write suitable code in Java to illustrate the creation of thread. Also, explain the use of isAlive( ) method in multithreaded programming with the help of a_ program. Support your code with suitable comments. 10 (b) What is Number Class ? Explain the use of parseInt (String s) method with the help of an example. 5 (c) Explain event handling in Java FX, with the help of an example. 5

Ans. (a) Multithreading Multithreading is a concept of concurrently executing multiple threads (lightweight sub-processes) within a single process. Each thread has its own execution path but shares the memory space of the process. This allows a CPU to switch between multiple tasks at the same time, leading to improved performance and responsiveness. Creating a Thread in Java: There are two main ways to create a thread in Java:

  1. By extending the `Thread` class: Create a class that extends `java.lang.Thread` and override its `run()` method.
  2. By implementing the `Runnable` interface: Create a class that implements the `java.lang.Runnable` interface and implement its `run()` method. Then create an object of this class and pass it to the constructor of the `Thread` class. This method is preferred as it allows for multiple inheritance.

Code for Thread Creation (using `Runnable` interface):

// Creating a thread by implementing the Runnable interfaceclass MyThread implements Runnable { private String threadName;

MyThread(String name) { this.threadName = name; }

// The run() method contains the execution code of the thread public void run() { System.out.println(threadName + " is running."); try { for (int i = 0; i < 3; i++) { System.out.println(threadName + ": " + i); Thread.sleep(500); // Pauses the thread for 500 milliseconds } } catch (InterruptedException e) { System.out.println(threadName + " was interrupted."); } System.out.println(threadName + " has finished."); }}

public class ThreadCreationDemo { public static void main(String[] args) { // Create an object of the Runnable MyThread myRunnable = new MyThread("Thread-1"); // Pass the Runnable object to the Thread class's constructor Thread t1 = new Thread(myRunnable); // Start the thread, which will call the run() method t1.start(); }}

Use of `isAlive()` method: The `isAlive()` method is used to check if a thread is still running. It returns `true` if the thread has been started and has not yet terminated; otherwise, it returns `false`. This is useful for making the main thread wait until other threads have completed.

Example Program for `isAlive()`:

public class IsAliveExample { public static void main(String[] args) { // Create a Runnable object and a thread MyThread runnable = new MyThread("WorkerThread"); Thread workerThread = new Thread(runnable); // Check if the thread is alive before starting System.out.println("Before starting, is workerThread alive? " + workerThread.isAlive()); // Will return false

// Start the thread workerThread.start(); // Check if the thread is alive after starting System.out.println("After starting, is workerThread alive? " + workerThread.isAlive()); // Will return true try { // Make the main thread wait for the worker thread to complete // We can loop using isAlive() while(workerThread.isAlive()) { System.out.println("Main thread is waiting for WorkerThread to finish..."); Thread.sleep(1000); // Wait for a moment } } catch (InterruptedException e) { e.printStackTrace(); }

// Check if the thread is alive after it has finished System.out.println("After finishing, is workerThread alive? " + workerThread.isAlive()); // Will return false System.out.println("Main thread is finishing."); }}

// Reuse the MyThread class from the previous example/*class MyThread implements Runnable { // ... (same code as above) ...}*/

(b) Number Class The `java.lang.Number` class is an abstract class in Java. It is the superclass of all wrapper classes that represent numeric values, such as `Integer`, `Long`, `Double`, `Float`, `Byte`, and `Short`. Since `Number` is an abstract class, you cannot create an object of it directly. Its main purpose is to provide a common supertype so that all numeric wrapper classes can be treated in a uniform way. It defines six methods that all subclasses must implement: `intValue()`, `longValue()`, `floatValue()`, `doubleValue()`, `byteValue()`, and `shortValue()`. These methods allow for the conversion from one numeric type to another.

`parseInt(String s)` Method: The `parseInt(String s)` is a static method of the `Integer` class (not the `Number` class). It is used to parse a string argument and convert it into a signed decimal integer.

  • It takes a `String` as input.
  • It returns a primitive `int` type value.
  • If the string does not contain a parsable integer, it throws a `NumberFormatException`.


Example:

public class ParseIntExample { public static void main(String[] args) { String strNumber = "123"; try { // Convert the string "123" to the integer 123 int number = Integer.parseInt(strNumber); // Use the result System.out.println("The parsed integer is: " + number); // Now we can perform mathematical operations on it int result = number + 7; System.out.println("Result after adding 7: " + result);

} catch (NumberFormatException e) { // Handle the case where the string is not a valid number System.err.println("Invalid number format: " + strNumber); } String invalidStr = "123a"; try { int invalidNumber = Integer.parseInt(invalidStr); } catch (NumberFormatException e) { System.err.println("Caught exception for invalid string: " + e.getMessage()); } }}

(c) Event Handling in JavaFX In JavaFX, event handling is the mechanism that responds to user actions (like button clicks, key presses, mouse movements) or system-generated events. It makes a GUI application interactive. The event handling model consists of three main components:

  1. Event Source: The UI component that generates the event (e.g., a `Button`, `TextField`).
  2. Event Object: This encapsulates information about the event (e.g., `ActionEvent`, `MouseEvent`).
  3. Event Handler: This is a method or object that responds to the event. It implements the `EventHandler` interface.


The Process:

  1. A user interacts with a UI component (the source).
  2. The source creates an event object and sends it to all registered handlers.
  3. The handler’s code is executed, causing a change in the application’s state.

Example: This example creates a JavaFX application with a button and a label. When the button is clicked, the event handler updates the text of the label.

import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.layout.VBox;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;

public class JavaFXEventHandling extends Application {

@Override public void start(Stage primaryStage) { primaryStage.setTitle("Event Handling Example");

// 1. The Event Source: a Button Button btn = new Button("Click Me");

// A Label to show the result Label label = new Label("Waiting for event...");

// 2. The Event Handler: what to do on button click // We are using a lambda expression which creates an EventHandler btn.setOnAction(event -> { label.setText("Button was clicked!"); System.out.println("Button click event handled."); });

/* // Alternative way without lambda (anonymous inner class) btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { label.setText("Button was clicked!"); } }); */

// Set up the layout VBox vbox = new VBox(10, btn, label); // 10px spacing vbox.setAlignment(javafx.geometry.Pos.CENTER); // Set up the scene and stage Scene scene = new Scene(vbox, 300, 200); primaryStage.setScene(scene); primaryStage.show(); }

public static void main(String[] args) { launch(args); }}

In this example, the `btn.setOnAction(…)` method registers an event handler for the button. When the button is clicked, an `ActionEvent` is generated, and the code inside the lambda expression is executed, which changes the label’s text.

Q3. (a) Describe the term ‘Exception Handling’ in Java. Discuss the role of ‘throws’ clause in exception handling, with the help of a suitable code in Java. Support your code with suitable comments. Also, explain the advantages of exception handling. 10 (b) Write a program in Java using JDBC to store the employees information which includes ID, Name, Date of Birth, Department, position in a database table named Employee. Support your code with suitable comments. 10

Ans. (a) Exception Handling Exception handling in Java is a powerful mechanism to handle run-time errors (called exceptions) so that the normal flow of the program is not disrupted. An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program’s instructions, such as dividing by zero, accessing a file that doesn’t exist, or a problem with a network connection. Exception handling in Java is managed using five keywords: try, catch, finally, throw, and throws .

  • try: Encloses the block of code that might throw an exception.
  • catch: Catches the exception thrown in the try block and handles it.
  • finally: This block is always executed, regardless of whether an exception occurred or not. It’s used for cleaning up resources.

Role of ‘throws’ clause: The ‘throws’ keyword is used in a method signature to declare that the method might throw one or more types of checked exceptions. It does not handle the exception within the method; instead, it passes the responsibility onto the method that calls it. The calling method must either handle that exception using a `try-catch` block or pass it further up to its caller using the `throws` clause again. The `throws` clause is required only for checked exceptions (those that are subclasses of `Exception` but not `RuntimeException`).

Code Example with ‘throws’ clause:

import java.io.IOException;

class FileProcessor { // This method declares that it can throw an IOException. // It does not handle it itself. public void readFile(String fileName) throws IOException { System.out.println("Attempting to read file: " + fileName); if (fileName.equals("nonexistent.txt")) { // Throwing a checked exception throw new IOException("File not found error!"); } System.out.println("File read successfully (hypothetical)."); }}

public class ThrowsExample { public static void main(String[] args) { FileProcessor processor = new FileProcessor();

// The calling method must handle the exception declared by throws. try { // Calling with a valid file name (no exception) processor.readFile("data.txt"); // Calling with an invalid file name that will throw an exception processor.readFile("nonexistent.txt"); } catch (IOException e) { // The exception is caught and handled here System.err.println("Caught an exception in main method: " + e.getMessage()); } System.out.println("Program continues after handling the exception."); }}

In this example, the `readFile` method doesn’t handle the `IOException` but declares it can throw one using `throws IOException`. The `main` method, which calls `readFile`, is responsible for handling this exception using a `try-catch` block.

Advantages of Exception Handling:

  1. Separation of Error-Handling Code from Normal Code: It makes the code cleaner and more readable.
  2. Maintaining Normal Program Flow: The program does not terminate abruptly when an error occurs; it can handle the error gracefully and continue.
  3. Error Propagation: Using the `throws` clause, a method can propagate an error up the call stack to where it can be handled more appropriately.
  4. Meaningful Error Reporting: You can catch specific types of exceptions and provide meaningful error messages to the user.

(b) Java Program to Store Employee Information using JDBC This program uses JDBC to insert an employee record into an `Employee` table in a MySQL database. Prerequisites: 1. A MySQL database server running. 2. In the database, a table named `Employee` created with the following structure:

 CREATE TABLE Employee ( ID INT PRIMARY KEY, Name VARCHAR(100), DateOfBirth DATE, Department VARCHAR(50), Position VARCHAR(50) ); 

3. The MySQL JDBC driver (.jar file) added to the project’s classpath.

Java Code:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.SQLException;import java.sql.Date;

public class StoreEmployeeInfo {

// Database connection details private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name"; private static final String USER = "your_username"; private static final String PASS = "your_password";

public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null;

try { // Step 1: Load the JDBC driver (optional in modern JDBC) // Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish a connection to the database System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connection successful!");

// Step 3: Create the SQL query for the PreparedStatement // PreparedStatement protects against SQL injection attacks and improves performance String sql = "INSERT INTO Employee (ID, Name, DateOfBirth, Department, Position) VALUES (?, ?, ?, ?, ?)"; pstmt = conn.prepareStatement(sql);

// Employee data int id = 101; String name = "Suresh Sharma"; // For java.sql.Date, we can use java.time.LocalDate java.time.LocalDate dob = java.time.LocalDate.of(1990, 5, 15); String department = "IT"; String position = "Software Engineer";

// Step 4: Set the parameters in the statement pstmt.setInt(1, id); // First '?' pstmt.setString(2, name); // Second '?' pstmt.setDate(3, Date.valueOf(dob)); // Third '?' pstmt.setString(4, department); // Fourth '?' pstmt.setString(5, position); // Fifth '?'

// Step 5: Execute the query int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { System.out.println("A new employee was inserted successfully!"); }

} catch (SQLException se) { // Handle JDBC errors se.printStackTrace(); } catch (Exception e) { // Handle Class.forName() errors e.printStackTrace(); } finally { // Step 6: Close resources // The finally block ensures that resources are always closed try { if (pstmt != null) pstmt.close(); } catch (SQLException se2) { } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); }}


Note:

You need to replace `your_database_name`, `your_username`, and `your_password` with your actual database credentials.

Q4. (a) What is Polymorphism ? Explain different types of polymorphism that are supported by Java, with the help of example codes for each. 10 (b) Discuss the purpose of stream classes in Java. How do byte streams differ from character streams ? Give suitable example for each. 10

Ans. (a) Polymorphism Polymorphism is a Greek word that means “many forms”. In Object-Oriented Programming, it refers to the ability of a variable, function, or object to take on multiple forms. In simple terms, it allows a single action to be performed in different ways. For example, the `+` operator adds numbers and concatenates strings. There are two types of polymorphism in Java:

  1. Compile-time Polymorphism (Static Binding): This is achieved through method overloading . The compiler determines which method will be called at compile time, based on the method’s signature (number and type of parameters).
  2. Run-time Polymorphism (Dynamic Binding): This is achieved through method overriding . The determination of which method will be executed happens at runtime, based on the type of the object.

1. Compile-time Polymorphism (Method Overloading) Defining multiple methods with the same name in the same class, provided their parameter lists are different (either in the number of parameters or in their type).

Example Code:

class Display { // Method to display an integer public void show(int num) { System.out.println("Displaying integer: " + num); } // Overloaded method to display a string public void show(String text) { System.out.println("Displaying string: " + text); }}

public class OverloadingExample { public static void main(String[] args) { Display d = new Display(); // The compiler knows which show() to call based on the argument type d.show(100); d.show("Hello Polymorphism"); }}

2. Run-time Polymorphism (Method Overriding) When a subclass (child class) provides a specific implementation for a method that is already defined in its superclass (parent class), it is called method overriding. For overriding, the method name, parameter list, and return type (or a covariant type) must be the same.

Example Code:

// Superclassclass Animal { public void makeSound() { System.out.println("The animal makes a sound"); }}

// Subclass 1class Dog extends Animal { // Overriding the makeSound() method @Override public void makeSound() { System.out.println("The dog barks"); }}

// Subclass 2class Cat extends Animal { // Overriding the makeSound() method @Override public void makeSound() { System.out.println("The cat meows"); }}

public class OverridingExample { public static void main(String[] args) { // Superclass reference, but subclass object Animal myAnimal = new Animal(); // Animal reference, Animal object Animal myDog = new Dog(); // Animal reference, Dog object Animal myCat = new Cat(); // Animal reference, Cat object

// At runtime, the JVM decides which object's method to call myAnimal.makeSound(); // The animal makes a sound myDog.makeSound(); // The dog barks myCat.makeSound(); // The cat meows }}

In this example, `myDog.makeSound()` will always call the method from the `Dog` class, even though the reference type is `Animal`. This is decided at runtime, hence the name run-time polymorphism.

(b) Stream Classes in Java In Java, a stream is a sequence of data. The main purpose of stream classes in the `java.io` package is to handle input and output (I/O) operations. These classes allow a Java application to read data from various sources (like files, network connections, memory buffers) and write data to various destinations. There are two main types of streams in Java:

1. Byte Streams:

  • They read and write data in the form of 8-bit bytes.
  • They are suitable for handling all types of data, such as text, images, videos, and binary files.
  • Their main abstract superclasses are `InputStream` (for reading) and `OutputStream` (for writing).
  • Examples: `FileInputStream`, `FileOutputStream`, `ByteArrayInputStream`.

2. Character Streams:

  • They read and write data in the form of 16-bit Unicode characters.
  • They are specifically designed to handle text files because they internally handle the conversion between bytes and characters, which is helpful when working with different character encodings.
  • Their main abstract superclasses are `Reader` (for reading) and `Writer` (for writing).
  • Examples: `FileReader`, `FileWriter`, `BufferedReader`.

Difference between Byte Streams and Character Streams:


Feature

Byte Stream

Character Stream

Unit of Data
Handles data in 8-bit bytes. Handles data in 16-bit Unicode characters.

Usage
Ideal for raw binary data, such as images, audio, video, and executable files. Ideal for handling text data and text files, as it handles character encoding.

Superclasses
`InputStream` and `OutputStream`. `Reader` and `Writer`.

Efficiency
Less efficient for text data as it does not understand character encoding directly. More efficient for text data.

Example of Byte Stream (`FileInputStream`): This code reads bytes from a file and prints them to the console.

import java.io.FileInputStream;import java.io.IOException;

public class ByteStreamExample { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream("source.txt")) { int byteData; System.out.println("Reading with Byte Stream:"); // Read one byte at a time until the end of the file while ((byteData = fis.read()) != -1) { // Print by casting the byte to a character System.out.print((char) byteData); } } catch (IOException e) { e.printStackTrace(); } }}

Example of Character Stream (`FileReader`): This code reads characters from a file and prints them to the console.

import java.io.FileReader;import java.io.IOException;

public class CharacterStreamExample { public static void main(String[] args) { try (FileReader fr = new FileReader("source.txt")) { int charData; System.out.println("\nReading with Character Stream:"); // Read one character at a time until the end of the file while ((charData = fr.read()) != -1) { // Print the character directly System.out.print((char) charData); } } catch (IOException e) { e.printStackTrace(); } }}

Both examples require a text file named `source.txt` to exist.

Q5. Write short notes on the following: 4×5=20 (a) CallableStatement Interface (b) Garbage collection and role of finalize( ) method in garbage collection (c) JavaFX and its features (d) Utility of TreeSet and HashSet

Ans. (a) CallableStatement Interface The `java.sql.CallableStatement` interface is part of the JDBC API and is used to execute stored procedures in a database. Stored procedures are pre-compiled groups of SQL statements stored on the database server that can be called by name. `CallableStatement` extends the `PreparedStatement` interface, so it has all the functionality of `PreparedStatement`, like executing parameterized queries. Its key features are:

  • Handling Output Parameters (OUT): Stored procedures can return values. `CallableStatement` allows you to register these OUT parameters using the `registerOutParameter()` method and then retrieve the values using getter methods like `getInt()`, `getString()`, etc.
  • Handling Input/Output Parameters (INOUT): It can also handle parameters that act as both input and output.
  • Execution: The stored procedure is executed using the `execute()` or `executeUpdate()` method.
  • Syntax: The syntax for calling is like `{call procedure_name(?, ?)}`, where `?` are placeholders for parameters.

Using `CallableStatement` can improve performance because stored procedures are pre-compiled and it reduces network traffic.

(b) Garbage Collection and role of finalize() method Garbage Collection (GC) is an automatic memory management process in the Java Virtual Machine (JVM). In Java, programmers do not need to manually de-allocate memory used by objects, as is done in languages like C++. The garbage collector runs in the background and identifies objects that are no longer in use by the program (i.e., there are no active references to them). It then reclaims the memory occupied by these “garbage” objects, making this memory available for future objects. This helps in preventing memory leaks. Role of `finalize()` method: The `java.lang.Object` class contains the `protected void finalize() throws Throwable` method. This method is called by the garbage collector on an object just before its memory is reclaimed. Its purpose is to give the object a chance to perform any final cleanup activities before it is destroyed, such as releasing non-Java resources (like file handles or native graphics resources). However, relying on `finalize()` is not recommended because:

  • There is no guarantee as to when (or if) it will be called.
  • It can negatively affect performance.
  • It has been deprecated since Java 9.

Using `try-with-resources` statements or `finally` blocks is a better and more reliable way to perform resource cleanup.

(c) JavaFX and its features JavaFX is a modern, open-source platform for creating desktop applications and Rich Internet Applications (RIAs). It is the successor to Swing and AWT for Java, providing a richer and more modern GUI toolkit. Key Features:

  • FXML: This is an XML-based markup language that allows you to separate the layout of the UI from the Java code. It simplifies UI design and facilitates collaboration between developers and designers.
  • Styling with CSS: JavaFX applications can be styled using Cascading Style Sheets (CSS), making it easy to customize the UI and create themes.
  • Rich UI Controls: It provides a comprehensive set of built-in UI controls, including charts, tables, trees, menus, and more.
  • Graphics and Multimedia: JavaFX has powerful APIs for 2D and 3D graphics. It also supports multimedia content, including audio and video playback.
  • WebView: It includes a `WebView` component that can embed and render web pages supporting HTML5, CSS3, and JavaScript directly within the application.
  • Hardware-Accelerated Graphics: It uses a graphics pipeline that takes advantage of the GPU to improve performance, resulting in smooth animations and rendering.

(d) Utility of TreeSet and HashSet Both `HashSet` and `TreeSet` are implementations of the `java.util.Set` interface, which means they do not allow a collection of duplicate elements. However, they store and manage elements differently internally, which leads to different utilities. Utility of HashSet:

  • Implementation: It is based on a hash table (a `HashMap` instance).
  • Ordering: `HashSet` makes no guarantees concerning the order of the elements. The order of elements may change over time.
  • Performance: It offers very fast, constant-time (O(1)) performance for `add()`, `remove()`, and `contains()` operations, provided the hash function distributes elements properly among the buckets.
  • Null value: It allows one `null` element.
  • Usage: `HashSet` is the best choice when you simply need to ensure that a collection has no duplicates and do not care about the order of the elements. It is the fastest `Set` implementation.

Utility of TreeSet:

  • Implementation: It is based on a Red-Black Tree (a type of self-balancing binary search tree).
  • Ordering: `TreeSet` stores elements in a sorted order, either according to their natural ordering or by a `Comparator` provided at creation time.
  • Performance: Performance for `add()`, `remove()`, and `contains()` operations is slightly slower, taking log(n) time (O(log n)), where n is the number of elements.
  • Null value: It does not allow `null` elements (as it cannot sort them).
  • Usage: Use `TreeSet` when you need a sorted set. It is ideal for scenarios where you need a collection of unique elements that must always be iterated in a specific order.


Download IGNOU previous Year Question paper download PDFs for MCS-206 to improve your preparation. These ignou solved question paper IGNOU Previous Year Question paper solved PDF in Hindi and English help you understand the exam pattern and score better.

  • IGNOU Previous Year Solved Question Papers (All Courses)

Thanks!

Share this:

  • Share on Facebook (Opens in new window) Facebook
  • Share on X (Opens in new window) X
  • More
  • Share on WhatsApp (Opens in new window) WhatsApp
  • Share on Telegram (Opens in new window) Telegram
  • Print (Opens in new window) Print
  • Email a link to a friend (Opens in new window) Email

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

लेटेस्ट अपडेट पायें

Telegram Telegram Channel Join Now
Facebook FaceBook Page Follow Us
YouTube Youtube Channel Subscribe
WhatsApp WhatsApp Channel Join Now

Search

Recent Posts

  • MSU Baroda Study Materials Free Download
  • Bhavnagar University Study Materials Free Download
  • Kachchh University Study Materials Free Download
  • BMTU Study Materials Free Download
  • SGGU Study Materials Free Download

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,611 other subscribers

Categories

  • 10th model paper (3)
  • bed books (3)
  • Bihar Board Model Paper (7)
  • Bihar Jobs (1)
  • cg board model paper (1)
  • DELED Books (1)
  • English Posts (1)
  • Essay (1)
  • Exam Prep (9)
  • G.K quiz in hindi (7)
  • General Knowledge in hindi (सामान्य ज्ञान) (24)
  • gk 2018 in hindi (12)
  • GK 2020 (2)
  • GK HINDI 2019 (9)
  • gk pdf download (16)
  • High school science notes in Hindi (3)
  • IERT (3)
  • MODEL PAPER (30)
  • Motivational quotes in hindi (1)
  • mp board model paper (4)
  • My Thoughts (Thoughts by Sachin Yadav) (1)
  • Navy (2)
  • NCERT Books in hindi free download (1)
  • Police (2)
  • Polytechnic (6)
  • Pratiyogita Darpan 2019 (2)
  • RBSE Model Papers (2)
  • School Books (1)
  • SSC GENERAL KNOWLEDGE (7)
  • StudyTrac (69)
  • Uncategorized (54)
  • University Books (106)
  • University Question Papers (153)
  • University Study Materials (89)
  • University Syllabus (144)
  • UP Board Books (5)
  • up board model paper (10)
  • Up board model papers (16)
  • UPSC Notes (3)
  • Uttar Pradesh Jobs (2)
  • रेलवे (7)
  • सामान्य हिन्दी (3)

Footer

University Books

University Study Materials (Books and Notes) in PDF Format in Hindi and English languages.

Click here to download.

University Question Papers

University Previous Year Question Papers and Sample Papers in PDF Format for all Courses.

Click here to download.

University Syllabus

Universities Syllabus in PDF Format in the English and Hindi languages for all courses.

Click here to download.

Copyright © 2026 ·GKPAD by S.K Yadav | Disclaimer