Methods in Java
एक Method कोड का एक block होता है यह तभी run होता है जब इसे call किया जाता है. हम method में parameters को pass
कर
सकते
हैं.
methods का प्रयोग कुछ विशेष कार्यों को करने के लिए किया जाता है, और इन्हें functions भी कहा
जाता
है.
दूसरे शब्दों में कहें तो, “Java method जो
है
वह
statements का एक collection होता
है
जो
कि
किसी
विशेष
कार्य
को
पूरा
करता
है.”
METHODS का प्रयोग
code को दुबारा से use करने के लिए किया जाता है. अर्थात् हम एक बार code को लिख देते है और उसे बार-बार use कर
सकते
हैं. हमें दुबारा से code को लिखने की जरूरत नहीं पड़ती
है. इसके अलावा हम methods का
प्रयोग करके आसानी से code बदल
सकते है.
Method Declaration
function
declaration को function
definition या function
statement भी कहते हैं
Syntax
:-
visibility static/non-static returntype method_name()
{
//perform task here
return value according to
returntype.
}
·
Visibility :
Class में methods
define करने से पहले उनकी Visibility भी define करनी पड़ती है ,
visibility means , class के अंदर define किये जाने वाले methods
को कहाँ कहाँ access
कर सकते हैं और कहाँ नहीं। यह 4 types की होती है - public , protected , private और by default
, default ही होती है। हालाँकि उन्हें कैसे use में लेते हैं वो , आगे पढ़ेंगे।
·
STATIC / NON-STATIC :
class में methods
2 types के हो सकते हैं -
·
Static Methods -
इन्हे हम बिना Object
initiate किये भी Class name
से access कर सकते हैं ,
लेकिन class के अंदर आप इन्हे directly
(without class name) भी call
कर सकते हैं। static
member define करने के लिए static keyword का use किया जाता है।
·
Non Static members -
इन्हे हम Object initiate किये बिना access नहीं कर सकते हैं। By Default
define किये गए methods का type Non
Static ही रहता है।
·
return type :
method define करते समय हमें उसका return
type define करना होता है , जो define करता है कि method
किस type की value return करेगा। अगर function कोई value
return नहीं करता तो , आप void type declare कर सकते हैं।
·
method_name :
कोई भी valid name हो सकता है ,
जो कि string या underscore के साथ start हो और Java में predefined keywords से match नहीं करता हो। Java
में method
name number से start
नहीं होता है ,
numbers को function
name के बीच में या last
में दे सकते हैं। But कहीं भी floating point numbers नहीं दे सकते हैं।
·
return statement,
method run होने के बाद method declaration के type के according
value return करता है।
public class MethodExample {
// define method.
static void my_method() {
System.out.println("Test
Method..");
}
public static void main(String[]
args) {
my_method();
}
}
Call a Method –
जावा में एक method को call करने के लिए,
method के नाम के बाद parentheses
() और semicolon
; लिखा जाता है. एक मेथड को बहुत बार call किया जा सकता है.
नीचे दिए गये उदाहरण में myMethod()
का प्रयोग text को print करने के लिए किया गया है,
जब इसे call किया जाता है तो.
public class MethodExample
{
// define method.
static void my_method() {
System.out.println("Test
Method..");
}
public static void main(String[] args) {
my_method();
my_method();
my_method();
}
}
Output
javac MethodExample.java
java MethodExample
Test Method..
Test Method..
Test Method..
Method
With return type
public class MethodExample {
// now define with return type.
static String my_method() {
// return any string value.
return "Test
Method..";
}
public static void main(String[]
args) {
String message = my_method();
System.out.println(message);
}
}
Output
javac MethodExample.java
java MethodExample
Test Method..
Advantages of Methods
·
Code Re-usability : methods use करने का सबसे बड़ा advantage यही है कि , हम code को reuse कर सकते हैं। same
processing के लिए एक बार method define करने के बाद उसे हम कही भी और कितनी बार भी use कर सकते हैं।
1. Less Code : चूंकि हम same code के लिए methods use करते हैं जिससे Program की length कम जाती है।
2. Reduce Coding Time :
method use करने से coding time
reduce होता है , जो कि किसी भी developer के लिए important है।
3. Easy To
Understand : Code को समझना आसान हो जाता है।
OOPs Concepts
OOPs Object
Oriented Programming System का ही short form है।
OOPs
(Object Oriented Programing System) Real World Entity/Object को Programming में represent करने का method / way है। और जैसा कि आप जानते हैं कि Java में सब कुछ object है। और Java programming language के through आप real world entity को programming में represent कर सकते हैं।
what are classes and objects
simple भाषा में समझे तो class
किसी real world
object में define
करने का blueprint है जिसे user define करता है इसलिए इसे user
defined type भी कहते हैं। एक Class,
properties (variables) और behaviour
(method) का एक collection
है जो logically एक दूसरे से related
होते हैं। जैसा नीचे दिए गए template
में दिखाया गया है।
और class के instance को object कहते हैं या समझ सकते हैं कि classes , objects के लिए template होती हैं। जब भी किसी class का object create किया जाता है , तो object उस class के सभी variables
और methods को inherit करता है , ताकि उन्हें access कर सके। हालाँकि किस variable/method
को access करना है या नहीं वो हम class में decide कर सकते हैं।
Class in
Java
Class एक user के
द्वारा define किया हुआ prototype होता है जिसमें
से objects को create किया जाता है.
दूसरे शब्दों में कहें तो, “एक
क्लास objects का एक समूह होता है जिसमें एकसमान properties होती हैं. यह एक blueprint होता
है जिसमें से objects को create किया जाता है.
यह एक logical
entity है. यह physical नहीं
हो सकती.”
Rules for
Java Class
java
में एक class को declare करने पर निम्नलिखित बातों का पालन किया जाता है
Modifiers – एक class के पास केवल public
या default
access हो सकता है.
CLASS KEYWORD – एक class को create करने के लिए class
keyword का प्रयोग किया जाता है.
Class name – इसका नाम capital letter से शुरू होना चाहिए.
Superclass (parent class)
– एक class
केवल एक ही parent
class को extend
कर सकती है. इसके लिए extends कीवर्ड का प्रयोग किया जाता है.
Body – class
की body,
curlybraces {} के अंदर होती है. curlybraces
के अंदर variables
और methods होते हैं.
एक क्लास fields, methods, constructors और blocks को contain कर सकता है.
Java
class syntax –
class ClassName {
// fields
// methods
}
Java Class
Members Type
किसी भी class में 2 types के members (Variables
/ Methods) हो सकते हैं -
- Static Members - इन्हे हम बिना Object initiate किये भी access कर सकते हैं। static member define करने के लिए static keyword का use किया जाता है। जैसा कि आपने पिछले examples में देखा कि main()
method से पहले static keyword use किया गया है।
- Non Static members - इन्हे हम Object
initiate किये बिना access नहीं कर सकते हैं। By Default define किये गए methods और variables
का type Non Static ही रहता है , हालाँकि इनके बारे में आप Next
Chapter में details से पढ़ेंगे।
Java
Access Specifier
Class में methods
और variables
define करने से पहले उनकी Visibility भी define करनी पड़ती है ,
visibility means , class के अंदर define किये जाने वाले variables
और methods को कहाँ कहाँ access
कर सकते हैं और कहाँ नहीं। यह 3 types की होती है -
- private - इन्हे सिर्फ class के अंदर ही access
किया जा सकता है। private
members को class के बाहर से access नहीं किया जा सकता है , और न ही इन members
को child class द्वारा access किया जा सकता है। हालाँकि class के सभी member by
default private ही होते हैं, इसलिए यदि class में कोई access
specifier define नहीं है तो class
के सभी members
अपने आप private
हो जाएंगे। इसके अलावा आप private keyword
का use करके class members को private कर सकते हैं।
- protected - इन्हे class के अलावा इनकी Child Class में भी access किया जा सकता है।
- public - एक class
के सभी members
by default private होते हैं इसलिए उन्हें public बनाने के लिए public
keyword का use किया जाता है।
class में variables
/ methods को private
/ public / protected के साथ static या non static
भी define किये जा सकते हैं। हालाँकि इस बारे में आप आगे detail में पढ़ेंगे।
Java Class Syntax
Java में class
define करने के लिए predefined keyword class का use
किया जाता है , और
उसके बाद class का name
define किया जाता है।
class Person
{
//
private members
//
protected members
// public
members
}
Java Access Members
Class members को define
किये गए access specifier के
according दो तरह से access कर सकते हैं।
- static members को आप class name को dot . operator के साथ access कर सकते हैं।
- जबकि non static members करने के लिए class का object बनाना पस्ता है फिर object variable dot . operator के साथ class variables/methods access करते हैं।
Java create Object
तो जैसा कि आपको
पता है कि strongly
typed programming language है
मतलब , कि define
किये गए data का एक type है।
किसी भी type के variable
के define
करते समय यह भी define करना
पड़ेगा कि उसका type क्या है ? जैसे कोई integer variable को कुछ इस तरह से define करते
थे।
int age = 90;
यह variable age से पहले int लगाने का मतलब
है कि यह इस variable में integer
value assign होगी।
ठीक इसी तरह से किसी class का
object बनाते समय object variable से पहले class name use किया जाता है। और new keyword का use
करके class
object बनाया जाता है। suppose करो
हमें एक class Person name
से बनाई है उसका Object कुछ
इस तरह से बनाएंगे -
Person persontObj = new Person();
Java Class
Example
class Person {
// define properties /
variables.
String name = "John";
int age = 12;
public static void main(String[]
args) {
// now create object.
Person personObj = new
Person();
System.out.println("Name
: "+ personObj.name);
System.out.println("Age :
"+ personObj.age);
}
}
Output
javac Person.java
java Person
Name : John
Age : 12
इससे
पहले तक जो भी example थे
उनमे हम variables को main()
method के अंदर define करते थे इसीलिए उन्हें हम बिना class object किये access कर
पा रहे थे , लेकिन normally
variables को main()
method के बाहर ही define किया जाता है , जिससे
उन्हें दुसरे methods में
भी use किया जा सके।
Java
Constructor
Constructor
special methods होते हैं जो कुछ भी return
नहीं करते हैं। मतलब constructor without return statement
define किये जाते हैं। जब किसी class
का Object बनाते हैं तो Constructor automatically run होता है।
इसे run
करने के लिए call करने जरूरत नहीं पड़ती है। लेकिन अगर Class का Object नहीं बना तो Constructor method run नहीं होगा।
हालाँकि किसी भी class के लिए constructor define करना optional होता है। आप अपनी need के according define कर सकते हैं। हाँ , अगर किसी class में constructor नहीं होता है तो java compiler automatically empty
body के साथ एक constructor
create करता है।
constructor
को निम्नलिखित बिन्दुओं के आधार पर आसानी से समझ सकते है:-
·
Constructors का प्रयोग क्लास के data members की values को initialize करने के लिए किया जाता है.
·
constructor जो है वह क्लास का member function होता है.
·
क्लास का जैसा नाम होता है वही नाम constructors का भी होता है.
·
constructors के पास return type नहीं होता है.
·
जब क्लास का ऑब्जेक्ट create होता है तो constructor अपने आप कॉल हो जाता है.
·
ये कभी भी virtual नहीं होते है.
·
ये public सेक्शन में declare होते है.
·
ये derived class के द्वारा inherit नहीं होते है.
·
constructors तीन प्रकार के होते है- default, parameterized तथा copy constructors.
·
जब हम प्रोग्राम में कोई constructors नहीं देते है तो कम्पाइलर हमारे लिए default constructor को जनरेट कर देता है.
Define
constructor
java में constructor को class name के साथ ही define किया
जाता है , जो class का name होगा
वही constructor का name रखना पड़ेगा। हाँ इसमें define किये गए parameters को need के according कम या ज्यादा कर सकते हैं।
Java
constructor example
public class A {
// define
default constructor.
A() {
System.out.println("Default
Constructor");
}
public static
void main(String[] args) {
// now just
create an Object.
A a = new
A();
}
}
Output
Default
Constructor
Rules to
define constructor in Java
- class name और constructor name same होना चाहिए।
- constructor का कोई return type होना चाहिए और न ही कोई value return करना चाहिए।
- Java programming language में कोई भी constructor abstract, static, final, और synchronized नहीं हो सकता है।
Access
modifiers
constructor define करते समय आप access
modifiers का use
कर सकते हैं ,
मतलब constructor
को आप private , protected, public और default
define कर सकते हैं।
पिछले topics
में आपने देखा होगा कि Properties / Method को define करने से पहले public keyword
का use किया गया था। वह Class
Properties / Method का एक visibility / access
mpdifier type ही था।
Class Visibility का मतलब Property / Method का scope
define करना होता है। की वह Property /
Method कहाँ - कहाँ Accessible
होगा। class
visibility को define
करने वाले keywords को ही Access Specifiers कहते हैं।
Java में Class
Visibility 4 Types की होती है -
- default
- private
- protected
- public
किसी भी class में किसी भी type
के members
(Static या Non
Static Properties / Methods ) को define
करने से पहले उस Properties
/ Method की visibility
define करनी पड़ती है।
और अगर define नहीं करते हैं तो वह property / method
automatically default define हो जाती है।
Java private Access Modifier
private Property / Method सिर्फ और सिर्फ Class
के अंदर ही accessible होंगे। Class के बाहर कहीं भी इन्हे access नहीं कर सकते हैं।
इस मॉडिफायर को private कीवर्ड का प्रयोग करके specify किया जाता है.
- private के रूप में declare
किये गये methods
या data members केवल उसी class के अंदर access किये जा सकते हैं जिसमें वे declare
होते हैं.
- समान package की कोई दूसरी class इन members को access नहीं कर सकती.
- top level class या interface को हम private
के रूप में declare
नहीं कर सकते. परन्तु हम nested
classes को private के रूप में declare
कर सकते हैं.
- private keyword का use करके किसी class के Properties / Methods को as a private define किया जाता है।
private class A {
// define private method.
private void privateMethod() {
System.out.println("This
is private method");
}
}
public class B {
public static void main(String[]
args) {
// try to access privateMethos.
A a = new A();
a.privateMethod(); // it
generates error.
} }
Java default Access Modifiers
अगर आप class में modifiers define नहीं करते हैं तो वह property / method as
a default treat की जाती है। default modifiers सिर्फ same package में access किया जा सकता है।
जब हम किसी class, constructor, methods आदि के लिए किसी भी access modifier का प्रयोग नही करते हैं तो उसे default एक्सेस मॉडिफायर समझा जाता है.
Default modifier का प्रयोग केवल इसी package के अंदर हो सकता है. इसका मतलब यह है कि यदि हमारे पास एक package में default modifier के साथ एक class है तो जो दूसरी classes इस package के अंदर है सिर्फ वो ही इस class को access कर सकती हैं. package के बाहर कोई दूसरी class इस class को access नहीं कर सकती.
यह modifier, private की तुलना में ज्यादा accessibility प्रदान करता है परन्तु यह protected और public से ज्यादा restricted है.
किसी दूसरे package में default modifiers को access नहीं कर सकते हैं। यह private से थोड़ी ज्यादा accessibility provide कराता है लेकिन protected, और public से कम।
// define package.
package
packageA;
class A {
// define deault method
void myMethod() {
System.out.println("Default method in
packageA");
}
}
// now define
another package.
package
packageB;
// import all
classes from packageA to use inside current package.
import
packageA.*;
public class B
{
public static void main(String args[]) {
A a = new A();//Compile Time Error
a.myMethod();//Compile Time Error
}
}
Java protected Access
Modifier
protected access modifiers , same package में accessible तो होगा ही साथ ही इसे Inheritance के through किसी दूसरे package में भी access कर सकते हैं। इसके लिए protected keyword की ही use किया जाता है।
Inheritance को आप आगे detail में पढ़ेंगे।
protected access modifiers को आप class के data member, method और constructor पर apply कर सकते हैं , class पर नहीं। मतलब किसी class को आप protected declare नहीं कर सकते हैं।
इस मॉडिफायर को protected कीवर्ड का प्रयोग करके specify किया जाता है.
- protected के रूप में declare किये गये methods या data members को उसी package के अंदर access कर सकते है या दूसरे package के sub-class के अंदर access कर सकते हैं.
Java public Access
Modifiers
public access modifiers , हर जगह accessible है , मतलब कोई भी class या Class में public keyword का use करके define किये गए Property / Method को कहीं से भी access कर सकते हैं।
Class के अंदर , बाहर , इसके Child class में या same package और different package में भी access कर सकते हैं।
Public access modifier को public कीवर्ड के द्वारा specify किया जाता है.
- इस modifier को कही भी access किया जा सकता है.
- इसमें किसी भी प्रकार का restriction (प्रतिबंध) नहीं होता है.
- इसके पास दूसरे modifiers की तुलना में सबसे बड़ा scope होता है.
Java
Libraries
Java
Libraries for Data Input (Java में डेटा इनपुट लेने के लिए लाइब्रेरी)
Java
में यूजर से इनपुट लेने के लिए कई लाइब्रेरी उपलब्ध हैं। कुछ महत्वपूर्ण लाइब्रेरी हैं:
Scanner
Class (आसान और सबसे ज्यादा उपयोग की जाने वाली)
1️⃣ Scanner Class (सबसे आसान तरीका)
👉 Scanner class का उपयोग यूजर से कीबोर्ड इनपुट लेने के लिए किया जाता है।
👉 यह java.util.Scanner package
में होता है।
👉 यह integers, float, string,
double, boolean आदि सभी डेटा टाइप को सपोर्ट करता है।
Syntax (Scanner Class)
import java.util.Scanner; // Scanner class को import करना जरूरी है
Scanner sc = new
Scanner(System.in); |
|
|
|
|
|
Array Manipulation
Array
Manipulation का मतलब होता है array
में elements को modify (बदलना), add (जोड़ना), remove (हटाना), sort (क्रमबद्ध करना), या search (खोजना) करना।
Sorting और Binary
Search दो बहुत important
operations हैं, जिनका use fast searching और efficient data handling के लिए किया जाता है।
1. Sorting (क्रमबद्ध करना)
Sorting
का मतलब होता है array के elements को ascending (छोटे से बड़े) या descending (बड़े से छोटे) order में arrange करना। Sorting algorithms जैसे कि Bubble Sort, Selection
Sort, Insertion Sort, Merge Sort, Quick Sort आदि का इस्तेमाल किया जाता है।
Arrays.sort(array);
// Default sorting (Ascending Order)
Arrays.sort(array,
Collections.reverseOrder()); // Descending Order
2. Binary
Search (तेजी से खोज करना)
Binary
Search एक efficient searching algorithm है, जिसका इस्तेमाल sorted array में किसी element को जल्दी से खोजने के लिए किया जाता है।
🔹 Binary Search कैसे काम करता है?
Array
को पहले sort किया जाता है (Binary Search सिर्फ sorted array में काम करता है)।
Middle
element को check
किया जाता है:
अगर middle element == target, तो index return करो।
अगर middle element < target, तो right half में search करो।
अगर middle element > target, तो left half में search करो।
यह process
तब तक repeat होती है जब तक element नहीं मिल जाता या array खत्म नहीं हो जाता।
Java
में Binary Search करने के लिए हम Arrays.binarySearch()
method का use
कर सकते हैं।
Syntax (Binary Search in Java)
int index = Arrays.binarySearch(array,
target);
अगर element
मिल जाता है, तो उसका index return होगा,
अगर element नहीं मिलता है, तो negative value return होगी।
String Manipulation
String
Manipulation का मतलब होता है Strings को modify (बदलना), जोड़ना, हटाना, compare करना, split करना, replace करना आदि।
Java में String immutable (अपरिवर्तनीय) होती है, मतलब एक बार बनी हुई String को modify नहीं किया जा सकता।
Java
में महत्वपूर्ण String Methods (सिर्फ व्याख्या)
1️⃣
length()
यह method
String की कुल लंबाई (character की संख्या) return करता है।
2️⃣
charAt(index)
यह method
दिए गए index पर स्थित character को return करता है।
3️⃣ toUpperCase()
यह method
पूरी String को uppercase (बड़े अक्षरों) में बदल देता है।
4️⃣
toLowerCase()
यह method
पूरी String को lowercase (छोटे अक्षरों) में बदल देता है।
5️⃣
concat(str2)
यह method
दो Strings को जोड़ने के लिए उपयोग किया जाता है।
6️⃣ equals(str2)
यह method
दो Strings की तुलना करता है और case-sensitive comparison करता है।
7️⃣ equalsIgnoreCase(str2)
यह method
case-ignore करते हुए दो Strings
की तुलना करता है।
8️⃣ contains
(subStr)
यह method
check करता है कि कोई substring
String में मौजूद है या नहीं।
9️⃣
startsWith (prefix)
यह method
check करता है कि String
किसी विशेष prefix से शुरू होती है या नहीं।
🔟 endsWith (suffix)
यह method
check करता है कि String
किसी विशेष suffix पर समाप्त होती है या नहीं।
1️⃣1️⃣
indexOf (char/str)
यह method
String में दिए गए character
या substring का पहला index return करता है।
1️⃣2️⃣
lastIndexOf (char/str)
यह method
String में किसी character
या substring का आखिरी index return करता है।
1️⃣3️⃣
replace(old, new)
यह method
String में किसी character
या substring को replace करने के लिए उपयोग होता है।
1️⃣4️⃣
substring(start, end)
यह method
String से एक भाग (substring) निकालने के लिए उपयोग किया जाता है।
1️⃣5️⃣
trim()
यह method
String के आगे और पीछे के spaces
को हटा देता है।
1️⃣6️⃣
split(delimiter)
यह method
किसी delimiter के आधार पर String को टुकड़ों में बांटकर array में store करता है।
Java Exception Handling
Exception
Handling , program में आयी unwanted runtime error को handle करने का एक process / method है। इन unwanted
errors की वजह से कभी कभी program terminate हो जाता है। हालाँकि program का terminate होना Exception पर depend करता है कि Exception किस तरह की है।
Understanding
Exception : Exceptions कुछ unwanted events होती हैं , जो program execution के समय आती हैं और program को disrupts/terminate करती हैं।
Advantage of Exception Handling
किसी भी programming language में exception handling का सबसे बड़ा advantage है application के normal flow को maintain करना। किसी भी type की error आते ही program का execution stop हो जाता है जिसकी वजह से हमें desired output नहीं मिलता है।
suppose
कीजिये आपके program में multiple statements हैं तो अगर कही बीच में error आयी तो उससे आगे का code run नहीं होगा।
statement 1;
statement 2;
statement 3; // any
runtime error
statement 4;
statement 5;
statement 6;
Error vs Exception
technically
देखा जाये तो Error और Exception दोनों different हैं। Errors , code syntax या system resources की कमी की वजह से आती हैं , इन errors को आप handle नहीं कर सकते हैं। जबकि Exception आपके logic या condition की वजह से आती हैं , ये runtime errors हैं जिन्हे Run Time
Exception कहते हैं ,
exceptions को आप handle
कर सकते हैं।
Java Types of Exceptions
java
में mainly दो तरह की exception है - checked और unchecked. Error को as an unchecked exception consider किया जाता है। हालाँकि Oracle के according exception 3 तरह की होती है।
- Checked Exception
- Unchecked Exception
- Error
Java Checked Exception
RuntimeException और Error को छोड़कर जो classes
directly Throwable class को inherit करती हैं उन्हें checked exceptions कहते हैं , जैसे : IOException, SQLException etc.
checked exceptions compile time पर check की जाती है।
Java Unchecked Exception
वो classes
जो RuntimeException को inherit करती हैं उन्हें Unchecked Exception कहते हैं , ये exception compile time पर check न होकर run time पर check होती है।
Java Error
जैसा कि आपने ऊपर भी पढ़ा कि Error
irrecoverable होती हैं ,
mean इन्हे आप handle
नहीं कर सकते हैं ये errors code syntax या system resources की कमी की वजह से आती हैं।
Java keywords for exception handling
Java
exception handle करने के लिए कुछ predefined
keywords का use
किया जाता है , जो कि इस प्रकार हैं -
Keyword |
Description |
try block
के अंदर हम अपना सारा code / logic लिखते हैं जिसमे exception आने के chances हैं , मतलब हम जो implementation code लिखेंगे वो try block में ही होना चाहिए। try को हमेशा catch या finally के साथ use करते हैं। |
|
catch का use exception को handle करने के लिए करते हैं , इसे हमेशा try block के साथ ही use करते हैं। single try block के साथ आप error type के according आप एक से ज्यादा catch भी use कर सकते हैं। |
|
finally block
में वो code लिखते है जिसे हमेशा run करना हो , चाहे error आये या नहीं। इसे भी हमेशा try block के साथ ही use करते हैं। |
|
throw keyword
का use custom exception को throw / create करने के लिए किया जाता है। |
Java try-catch
try block
के अंदर हम अपना सारा code / logic लिखते हैं जिसमे exception आने के chances हैं , मतलब हम जो implementation code लिखेंगे वो try block में ही होना चाहिए। try को हमेशा catch या finally के साथ use करते हैं। और catch का use exception को handle करने के लिए करते हैं , इसे हमेशा try block के साथ ही use करते हैं। single try block के साथ आप error type के according आप एक से ज्यादा catch भी use कर सकते हैं।
without try catch
हम जानते हैं कि किसी number में 0 से divide नहीं कर सकते हैं , तो अगर हम ऐसा code बिना try catch के लिखते हैं , तो कुछ इस तरह से error आती है।
try {
// code
}
catch(Exception error) {
// your custom message.
}
by
default exception catch होने पर आपको error object मिलत है , आप चाहे तो error message get करने के लिए getMessage() method
का use भी कर सकते हैं।
For example :
try {
System.out.println( 30/0 );
}
catch (ArithmeticException error) {
System.out.println("Error : " + error.getMessage());
}
//Output : Error : / by zero
Database
Connection from Java
Java को डेटाबेस से कनेक्ट करने के लिए हम JDBC
(Java Database Connectivity) का उपयोग करते हैं। JDBC
एक API (Application Programming
Interface) है जो Java को विभिन्न डेटाबेस से जोड़ने की सुविधा देता है।
JDBC ड्राइवर लोड करें → Class.forName()
डेटाबेस कनेक्शन बनाएं →
DriverManager.getConnection()
SQL स्टेटमेंट तैयार करें → Statement या PreparedStatement
SQL स्टेटमेंट को रन करें → executeQuery() या executeUpdate()
डेटाबेस कनेक्शन को बंद करें → con.close()
Assertions
Assertions
Java में debugging
tool की तरह काम करता है, जो प्रोग्राम में logic को verify करने के लिए उपयोग किया जाता है। यह रनटाइम पर conditions को चेक करता है और अगर condition false होती है, तो AssertionError थ्रो करता है।
Syntax:
assert condition : "Error
message";
Example:
public class AssertionExample {
public static void main(String[] args) {
int age = 15;
assert age >= 18 : "Age must be 18 or above";
System.out.println("Welcome! You are eligible.");
}
}
Key Points:
Assertions
को enable करने के लिए -ea flag का उपयोग करें:
java -ea AssertionExample
अगर assertion
fail होती है, तो AssertionError थ्रो होगा।
Threads
in Java
Java में Threads का उपयोग multi-tasking और parallel execution के लिए किया जाता है। एक thread एक lightweight sub-process होता है।
Thread Creation Methods:
By extending Thread class
By implementing Runnable interface
Method 1: Using Thread Class
class MyThread
extends Thread {
public void run() {
System.out.println("Thread is
running...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Thread execution starts
here
}
}
Method 2: Using
Runnable Interface
class MyRunnable
implements Runnable {
public void run() {
System.out.println("Thread is
running using Runnable interface...");
}
public static void main(String[] args) {
MyRunnable obj = new MyRunnable();
Thread t1 = new Thread(obj);
t1.start();
}
}
Key Points:
start() method thread execution को शुरू करता है।
run() method में thread का actual code लिखा जाता है।
Thread.sleep(time) → thread को कुछ समय के लिए रोकने के लिए use किया जाता है।
Thread.join() → एक thread को दूसरे thread के complete होने तक wait करने के लिए use किया जाता है।
Wrapper Classes in Java
Wrapper
classes primitive data types को objects में convert करने के लिए use की जाती हैं। Java में हर primitive data type के लिए एक corresponding wrapper class होती है।
Primitive Type |
Wrapper Class |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
char |
Character |
boolean |
Boolean |
Example:
Autoboxing (Primitive to Object Conversion)
public class
WrapperExample {
public static void main(String[] args) {
int num = 10;
Integer obj = num; // Autoboxing
System.out.println("Integer
object: " + obj);
}
}
Example: Unboxing
(Object to Primitive Conversion)
public class
WrapperExample {
public static void main(String[] args) {
Integer obj = new Integer(20);
int num = obj; // Unboxing
System.out.println("Primitive int:
" + num);
}
}
Key Points:
Autoboxing:
Primitive → Object
Unboxing:
Object → Primitive
Wrapper
classes में utility
methods (parseInt(), valueOf(), etc.) होते हैं जो primitive values को manipulate करने में मदद करते हैं।
Assertions → Debugging के लिए useful हैं, runtime पर logic check करते हैं।
Threads → Multithreading concept में उपयोग होते हैं, जिससे एक साथ multiple tasks execute किए जा सकते हैं।
Wrapper Classes → Primitive data types
को objects में wrap करने के लिए use होते हैं।
0 Comments