0% found this document useful (0 votes)
407 views187 pages

Core Java Notes

The document provides an overview of Java programming including object-oriented programming concepts, Java features, the Java development kit structure, and tools. It discusses procedural programming versus object-oriented programming and compares C++ to Java.

Uploaded by

Boy2 tecH
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
Download as odt, pdf, or txt
0% found this document useful (0 votes)
407 views187 pages

Core Java Notes

The document provides an overview of Java programming including object-oriented programming concepts, Java features, the Java development kit structure, and tools. It discusses procedural programming versus object-oriented programming and compares C++ to Java.

Uploaded by

Boy2 tecH
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1/ 187

+

Complete Java ( J2SE ) Programming

Core Java

Getting Started with OOPS and Java

• Object Oriented Programming

• What is Java?

• History of Java

• How to get Java

• Compiling and interpreting application

• The JDK directory structure , JRE

• Inside JVM

• A first java program

• Introduce SOP and Scanner

• Comments ( Line, Block, Java Doc )

• Command Line Arguments

Java – James Gosling

what is java and its features ? ---- Java is a high level Object Oriented programming Language.

It is also a Platform.

It is also a Technology.

It is platform independent which can be executed on n number of platform.


CORA -- Compile One Run Anywhere.

Object - 1.object oriented -- The language which having all the characteristic of OOPs

2.object base -- jo oops ke followinng characteristics apne pass nhi rakhte ho-

runtime polymorphism,inheritance.

3.pure object oriented --they all are concepts , Programming technic

Approaches to develop a software

1.)Procedural Oriented (C lang) - POPL -- bana kar khao

2.)Object oriented (simula, C++ , java) - OOPL -- bhahar jakar khao

3.)Aspect oriented ( Spring (java)) - AOPL -- order karke khao

OOPs---the programming langauge which having all characteristics of oops is call object oriented programming language.

--Object

--Class

--Encapsulation

--Abstaction

--Inheritance

--Polymorphism

Coupling (Dependency) -- loose

--Tight Coupling

--Loose Coupling

Cohesion (Bonding) -- tight

Documentaton -- how the software works in written form

Features in Object Oriented

1.No Dependency

2.Loose Coupling

3.Connect with real world

4. Reusability

5. Data hiding

SDLC- Software Development Life Cycle

1. Requirement Gathering ( Business Analyst - understand the software requirement)


2. Analysis (time,resource,cost)

3. Design (GUI,DataBase)

4. Coding

5. Testing (STLC-software testing life cycle)

6.

Software development model.

--Waterfall Model

What is Software ?

Software is the combination of program. --- SRS+Implimentation+Doc

set of instruction is program and set of program is software

$---Invented by SunMicroSysytem by James Goislin but later Acquire by Oracle

$---This language have the capability to develop various varity of software like :- Desktop application(single system
software) , Windows application, Web Application, Android Application, Embbed application, Cloud application , System
software (Operating System), Antivirus

$ -- language -- syntax + semantic

$---procedural Oriented (C language) is an approach (tarika) to develop software


what is program -

` - program is a chain of steps or set of activities which is combine together in order to achieve a
specific task.

- program is in static state but when it runs it is in dynamic state

threads - subprocess

Type of programming language -

Low Level , (Machine lang , Assembly lang) -directly interact with hardware

Middle Level , (C)

High Level (C++,java,.net etc) -- not directly interact with hardware

What is Machine ?

Anything reduces the human efferts.

FOLDER = Directory

We can create a java program by two ways :- with IDE (IDE --- Copiler + LIbrary + RunTime Enviroment + Editor) -- i.e.
eclipse, netbeans, myeclips

:-without IDE -- JDK, editor , cmd

:-IDE (Integrated Development Enviroment)

To use External command in cmd we sets the variable path.

Enviroment Variable : - User variable

: - System variable

: - Path -->path is a implicit enviroment variable which is created by

windows in order to set the local of any exe file.

Types of command :- internal command

:- external command

Diffrence between C and C++?

@-C is a procedural oriented lang

@-C++ is a object oriented lang

$--All Java CMD commands path -- C:\\Programfile\\java\\bin

Compile (file name) Java program syntax :- javac filename.java

Run (class name) Java program syntax :- java filename


Java Fundamentals

Features

object oriented

Simple language -- (pointer and operator overloading are deprecated) and java support OOPs

and OOPs support real world and relating real world is easy.

Secure -- (members are private , ) -- Because we can't pointer explicity, Byte code

verifiacation , Program run inside virtual machine

sandbox, Security management, Many more security can

applied on java application like - JCA/JCE(java

cryptography architecture & java cryptography extensions)

JSSE (java secure-socket extension)

Platfom Independent -- (compile ones run anywhere ) --if a language have capability to

compile the program in one platform ,same program can be

executed on other platform without changing the object code.

Portable -- (byte code to run anywhere)

Robust -- (inbuild exception handing, automatic garbage collector)

Architectural nutral--(java program doesn't want hardware specification)


Multithreaded --

Distributed -- (use in internet )--Distributed program is common for all. C,C++,Web,Android

all use one program of java that is Distributed program.

Open Source-- (Source avilable openly)

Dynamic -- (changable on runtimes)

-------------------------------------------------------------------------------------------------------------------

Types of Programming Language

-------------------------------------------------------------------------------------------------------------------

What is Micro-Controller?

It can hold the data and process.


What is Micro-Processor (CPU)?

It can only process the data.

-------------------------------------------------------------------------------------------------------------------

Approaches of Develop a Software.

· Procedural Oriented (C language)

· Object Oriented (Java,C++)

· Aspect Oriented (Spring(Java))

Why Java develope when C,C++ already exesist?

1. written ones run anywhere

2. platform indepandant
3. class base language

Translator

1. Assembler

2. Compiler

3. Interpreter

-------------------------------------------------------------------------------------------------------------------

Flavours of Java

1.Core Java (J2SE)

2.Advance Java (J2EE)

3.Android Java (J2ME)

What is JDK, JRE, JVM ?

1.JDK - Java Development Kit ( JRE+JVM )

--Java development kit is a complete software of java which contains

java compiler(source code---to---byte code), java decompiler(byte

code----to----souce code), java libraries, java runtime enviroment,

JVM and source code

2.JRE - Java Runtime Enviroment ( JVM + Libraray ) --> JRE are dirrent for defferent

device or OS.

3.JVM - Java Virtual Machine

abstract virtual machine

software program

combination
-------------------------------------------------------------------------------------------------------------------

Tools available in JDK in bin folder.

-javac

-javap

-javah

-jconsole --> for java monitoring and management console

-javadoc etc.

What is Java Switches?

What is Java Native Interface (JNI)?

-java ke program ko c++ mai kese call lagana h and vice-versa.

DataType ka size compiler to compiler vary karti h.

-------------------------------------------------------------------------------------------------------------------

Diffrence between c++ and java?

C++ is the platform dependent and java is the platform independent.

What is Platform?

Platform is the place or runtime enviroment onn which out program is going to be executed.It could be a hardware or
combination of both.

--Software (Operating System,Server)

--Hardware (Micro-processor,Micro-controllers)

--Software + Hardware
Platform Independency

--Means program compile on one platform and can be executed on any platform

without changing their object code.In short CORA.

Compatibility

Lower (32bits)---------->High (64bits)

High (64bits)------x----->Low (32bits)

API - set of inbuild libraries and predefine functionalities in any language.

VMWare --> virtual machine

---------------------------------------------v20------------------------------------------------------------------

In Java , class Name and file Name are same.

----------------------------------------------V21----------------------------------------------------------------

Java use in -- 1. Web Development

2. Mobile Development

3. Desktop Application Development etc.

In Open Source ,Code development and Software are free but Support,Advertisement are paid.

-----------------------------------------------V22---------------------------------------------------------------

Java Fundamental (Thing which are neccessary to develop a java program. );-

· Keyword

· Identifier

· Variable ( Data Member )

· Literals ( Constant )

· Method (Member Function )

· Operators

· Separators
· Comments

· OOPs

· etc

Keyword:- Keywords or Reserved words are the words in a language that are used for some internal process or
represent some predefined actions. These words are therefore not allowed to use as variable names or objects. If we
do we will get a compile-time error as shown below as follows:

Java keywords are available in small letters.

S.No Keyword Usage

1. abstract--->Specifies that a class or method will be implemented later, in a subclass

2. assert-->Assert describes a predicate placed in a java program to indicate that the developer thinks that the
predicate is always true at that place.

3. boolean-->A data type that can hold True and False values only

4. break-->A control statement for breaking out of loops.

5. byte-->A data type that can hold 8-bit data values

6. case-->Used in switch statements to mark blocks of text

7. catch-->Catches exceptions generated by try statements

8. char -->A data type that can hold unsigned 16-bit Unicode characters

9. class-->Declares a new class

10. continue-->Sends control back outside a loop

11. default-->Specifies the default block of code in a switch statement

12. do-->Starts a do-while loop

13. double-->A data type that can hold 64-bit floating-point numbers

14. else-->Indicates alternative branches in an if statement

15. enum-->A Java keyword is used to declare an enumerated type. Enumerations extend the base class.

16. extends-->Indicates that a class is derived from another class or interface

17. final-->Indicates that a variable holds a constant value or that a method will not be overridden

18. finally-->Indicates a block of code in a try-catch structure that will always be executed

19. float-->A data type that holds a 32-bit floating-point number

20. for-->Used to start a for loop

21. if-->Tests a true/false expression and branches accordingly


22. implements-->Specifies that a class implements an interface

23. import -->References other classes

24. instanceof-->Indicates whether an object is an instance of a specific class or implements an interface

25. int-->A data type that can hold a 32-bit signed integer

26. interface-->Declares an interface

27. long-->A data type that holds a 64-bit integer

28. native-->Specifies that a method is implemented with native (platform-specific) code

29. new-->Creates new objects

30. null-->This indicates that a reference does not refer to anything

31. package-->Declares a Java package

32. private-->An access specifier indicating that a method or variable may be accessed only in the class it’s declared in

33. protected-->An access specifier indicating that a method or variable may only be accessed in the class it’s declared
in (or a subclass of the class it’s declared in or other classes in the same package)

34. public-->An access specifier used for classes, interfaces, methods, and variables indicating that an item is
accessible throughout the application (or where the class that defines it is accessible)

35. return-->Sends control and possibly a return value back from a called method

36. short-->A data type that can hold a 16-bit integer

37 static-->Indicates that a variable or method is a class method (rather than being limited to one particular object)

38. strictfp-->A Java keyword is used to restrict the precision and rounding of floating-point calculations to ensure
portability.

39. super-->Refers to a class’s base class (used in a method or class constructor)

40. switch-->A statement that executes code based on a test value

41. synchronized-->Specifies critical sections or methods in multithreaded code

42. this-->Refers to the current object in a method or constructor

43. throw -->Creates an exception

44. throws-->Indicates what exceptions may be thrown by a method

45. transient-->Specifies that a variable is not part of an object’s persistent state

46. try-->Starts a block of code that will be tested for exceptions

47. void-->Specifies that a method does not have a return value

48. volatile -->This indicates that a variable may change asynchronously


49. while-->Starts a while loop

Note: ---The keywords const and goto are reserved, even they are not currently in use.

Currently they are no longer supported in Java.

-----------------------------------------------V23---------------------------------------------------------------

OOPs ( Object-Orientd Pragramming System )

Object ( Noun )- ->Any real world entity which having their physical , logical ,tengibal- Untangible existence is known as
Object.

Every Object have 3 characteristics;

· State ( or Attribute or Data Member )

ex-Mobile ka--->model,color,price,width etc

· Behavior ( or Functionality or Member Function )

ex-Mobile se-->calling, mailing , ,messaging etc

· Identity --

ex-Mobile ka--> IMEI number

Class --> Class is a logical chategorization of similar type of Objects and Class provides the

data structue to the programmer.


4 Piller of OOPs

--------------------------------------------------V24------------------------------------------------------------

Identifier ( Name ):--> Identifier are those concepts which is used to identify the name of

class,name of packege, name of method, name of variable in a

program
---------------------------------------------------V25-----------------------------------------------------------

Rules to make identifier :-

1. Keyword can not be used as a identifier.

2. can not blank/space or length of identifier must be greater than zero.

3. white space not allowed

4. number are allowed but not from first position.

5. underscore and doller are allowed

6. special symbol are not allowed

7. unique ......etc

Convension ( Coding Standard ) :- for better code readability

8. whenever we are creating any class in java if the class containing single word the first letter should be in capital
letter. and all inbuild classes are also have there first letter in capital letter.

9. if any method identifier is single word all letter should be small case .if multiple words than camel case.

10. variable are in small letter.


---------------------------------------------V26-----------------------------------------------------------------

Variable--> variable is the name of memory location which refer the value of a specific address.

Types of Variable ( Data Member )

11. Static variable ( Static Data Member,Class data member )

12. Non Static Data Member (instance variable)

13. Local variable

4. No Global variable

What is DataType?

DataType are those concepts which explain the following information about the

variable.

14. Type for the variable

15. Size for the variable


16. Range for the variable

Types of Dataatype?

· Primitive DataType ( Pre-define datatype--type,size,range already define )


-char-(2byte)

-boolean-(1bit) not define

-byte-(1byte)
-short-(2byte)
-int-(4byte)
-long-(8byte)

-float-(4byte)
-double-(8byte)

17. Non-Primitive DataType ( User define datatype--type,size,range User define )

-class

-array

-interface

-object

-string
Computer Memory Measurement Units?

--------------------------------------------------------v27-------------------------------------------------------

-------------------------------------------------------V28-------------------------------------------------------

Local Variable :- Local variable are those variable which is declared inside a method or in a

block.The scope of Local variable in which it is declare.


In Singned Data Type;-

· Primitive Data Type

· User-define Data Type

Java ke har variable ki default value pehle de hi define hota h. pr local variable ki default value nhi hoti.local variable mai
koi na koi value deni padti h.

Local variable must be initialize before the first use.

In Java programming language a Literal repesent Constant value;-

Type of Literals

--Primitive Literal
--Non Premitive Literal

-----------------------------------------------------------v29----------------------------------------------------

Method ( Member Function ) - Behaviour

Java ka program bina main() ke compile ho jayega pr run nhi hoga.

Method is statement which creates a block in a program in which we are writting our business logic, this logic can be
reuse in a program again again.Reusable program or code.

Syntax to creating an mrthod (Member function ) in java :-

Method Termonogy :-

· method declaration

· method defination

· method calling

· method parameter

· method argument
Return Type in Method:-

· void

· Primitive data type

· non-primitive type

Type of Methods:-

· User define Method

-Parameterise

--with return ( primitive & non-primitive data type )-in method body end

return

--without return ( void )

-Non Parameterise

--with return ( primitive & non-primitive data type )-in method body end

return

--without return ( void )

· Pre-define Method

-Parameterise

--with return ( primitive & non-primitive data type )

--without return ( void )

-Non Parameterise

--with return ( primitive & non-primitive data type )

--without return ( void )

-----------------------------------------------------------------v30----------------------------------------------

Types of Logic :-

· Presentation Logic

· Business Logic ( Functionality )

· Data Base Logic

why use made Class :- for Object categorisation

Syntax to create a class in Java.


Separator :--

Note :- for decompile type in cmd -javap className

--------------------------------------------V31------------------------------------------------------------------

What is Method?

Method or Member function is the statement in a program which make a block that contain BL and be reuse again and
again.
• Program start from “main” function / “main” is a entry point of program.
• “main” is a contract method between program and programmer.
• Without “main” method program can be compile but can not be run.
• We can never create method inside a method.
• Method convert code into small pieces.
• Java mai jitne bhi method h wo sabhi member(Object) pr call hote h.
• Function akele call ho jate h pr “member function (Object)” kisi member pr call hote h.
• Class main sabse pehle “main” method chalta h.

Note:- To see all “print” method type “ javap java.io.PrintStream (package name) ” in cmd.

----------------------------------------------------------------------V32-------------------------------------------------------------------

Syntax to Call a method (Member function ) in Java :-

Method ke 3 “return” type ho sakte h.


1. Primitive type
2. non-primitive type
3. void ( no return )
--------------------------------------------------------------------V33---------------------------------------------------------------------
To see classes of an package --- javap java.util.Scanner (package name)
--------------------------------------------------------------------V34---------------------------------------------------------------------
Type Conversion:-
It is the process of converting one type of data into another type.
• Type Promotion ( Implicit ) --> Type Promotion is a process of converting one type of data into
another type implicitly by language itself.
-Once we have data and data does not found their exact match so one data is implicitly to
another type.
-Type Promotion Rule ( smaller--to--higher )

• Type Casting (Explicit ) --> It is the process of converting one type of data into another type
explicit by programmer itself.
Syntax of Type Casting :-
Method overloading:-
Ek naam se bahut sare method but different parameters is called --- Method overloading
Note:-In java by default all the integer, Literals are treated as int data type and floating-Literal are treated as
double data type

Literals (Constant ):-


Primitive –> Integer(19,46,604), floating(35.6f),char(‘a’),Boolean(true,false)
Non-Primitive --> String (“hello”)
-----------------------------------------------------------------V35------------------------------------------------------------------------
-----------------------------------------------------------------V36------------------------------------------------------------------------
-----------------------------------------------------------------V37------------------------------------------------------------------------

Question—Why in Java char size is 2 bytes but in C char size is 1 byte.


Answer—Because Java support Unicode system where as in C support ASCII code system.

Unicode

ASCII->256
character
Every country has their Unicode System like – Russia, China.
-------------------------------------------------------------------V38----------------------------------------------------------------------
Class :-
• Class is blueprint for an object.
• Class is the user define data type.
• Class is the logical categorization of similar type of object.
• Class is the collection of data member and member function.

Syntax of a Class:-
class identifier
{
[Data Member] //Optinal
[Member Function] //Optinal

[SpecialMemberFunction] //not Optinal


-Constructor

-[Initializer]-static & non static //Optinal


}

Object creation (Memory Allocation):-


1. by new keyword
2. by newlnance() method
3. factory pattern
4. clone() method

Syntax to creating object by new keyword:-

1.-new ClassIdentifier(arags if any);


2.ClassIdentifier revar=new ClassIdentifier(arags if any);
3.ClassIdentifier refvar
new ClassIdentifier(arags if any)

Types of memory allocation:-


1. Compile time memory allocation
2. Runtime memory allocation

new-->Creates new objects

-new ka kaam h heap area mai memory allocate karna.

JVM Memory Area:-

1. Heap – contain Object (Non static data member)


2. Stack – contain Local Variable

3. PC Register -

4. Native Method stack

5. Method Area – contain Class area (Static data member)

-----------------------------------------------------------------V39---------------------------------------------------

There are two type of memory allocation:-

1. Static ( Compile time ) memory allocation-- size, use ,identification are decided on Compile time

• Static memory are always refer via their name.

2. Dynamic ( Runtime ) memory allocation –size, use, identification are allocated on Runtime

• Dynamic memory are refer via pointer.

Note:-Java does not support pointer explicitly (vyakt) , But implicitly (avyakt) it is used.

Reference Variable:- Are those variable which holds the reference id of an object.

Reference id → classname@haxaString

Magic Method :- object class ke 9 methods ko magic method kehte h. ye 9 methods implicitly har class mai

available hote h.

----------------------------------------------------------------------------V40--------------------------------------------------

Ananymas Object :- Ananymas Object is a Object without reference variable.


Every Object have 3 characteristics;

What is Constructor?

Its is a special type of method which having following features from a normal method.

1. It’s name must be same as it’s class name.

2. It does not any return type, not even void.

3. Programmer can’t call constructor explicitly it is implicitly called only when object is created.

4. Main purpose of constructor to initialize the data at the time of object creation.

Syntax of Creating a Constructor


Rule:-When ever we are compiling any java program a default constructor is added by java compiler its

self when we are not adding an constructor in the program.

-----------------------------------------------------------V41-------------------------------------------------------------------

Why we create OBJECT of a class?

1. Class ke instance variable ko memory allocate karane ke liye.

------------------------------------------------------------V42------------------------------------------------------------------

• Agar class ke data (state) ko static ya local bana de to usko bina object banaye hi memory mil jayegi

• aur class ke data (state) non-static ho to usko memory allocate krne ke liye object banate h.

• class is template of an Object.

-------------------------------------------------------------V43-----------------------------------------------------------------

--------------------------------------------------------------V44----------------------------------------------------------------

--------------------------------------------------------------V45----------------------------------------------------------------

Default Constructor?
Types of Constructor?

• Parameterize

• Non-Parameterize

Ek hi program mai agar default constructor and user define constructor ho to usse Constructor overloading
kehlata h.

When we create Default Constructor?

-Jab alag alag object pr same data assign krna ho.

When we create Parameterize Constructor?

-Jab alag alag object pr alag alag data assign krna ho.

-------------------------------------------------------------------V46-----------------------------------------------------------

Why we create Class?

Class banate h same type ke object ko categorize karnne ke liye.

How many time constructor called?

Constructor ek object pr ek bar call hota h.

------------------------------------------------------------------V47------------------------------------------------------------

Difference between constructor and a method?


1. Method name may or may not same with class name but constructor name must be same as class
name.

2. Method but have return type but constructor does not have any return type not even void.

3. Method can be call on same object multiple time but constructor must be call only once on one
object.

4. Method represent behavior of an object where as constructor is used to initialized the data at the time
of object creation.

5. When we are compiling any java program a default constructor is add by java compiler at compile
time . But it is not happened in case of method.

-------------------------------------------------------------------V48------------------------------------------------

minimum Size of an Object → 8 byte in 64bit JVM

maximum Size of an Object →

---------------------------------------------------------------------V49-----------------------------------------------

initializer:-

initializer are those things which are used to initialize the data before object creation. Depending on behavior
they are two types of initializr.

1) Static block – object independent

2) Non static ( init Block ) -- object dependent

init-Block:-This is anonymous block used to initialized the data before object creation and must be

executed with respect to every object.

Syntax:-

Features:-

1. It is object dependent, means object criterion is necessary to execute the init block.

2. It execute before constructor.

3. It execute with respect to every constructor, Whereas constructor are specific.

4. You can write any logic inside init block don’t create the object of same class inside init block

5. After variable declaration we can create init block any where in the program.

6. But don’t not keep init block inside method because when you keep it inside method it is treated as a
normal statement.

7. In case of more than one init block in the program their order of execution is determine by their
order
8. Init block is Object dependent.

Note:- It means init Block is automatically paste at the top of every constructor during compilation.

-------------------------------------------------------------V50-------------------------------------------------------

Watch again
------------------------------------------------------------------------V51-----------------------------------------------------

What is Static?

Static is the keyword and this keyword can be applied with following things:-

1. DataMember

2. MemberFunction

3. NestedClass

4. Block

We can’t applied Static keyword:-

1. Class

2. Constructor

Object ko memory Heap mai milti h.

Reference variable ko memory Stack mai milti h.


--------------------------------------------------------------------------V52---------------------------------------------------

Wo data jo har Object mai comman hoga usse Static banayenge taki us data ki class area mai memory mile
instance means copy

Static means fixed

-----------------------------------------------------------------------V53-------------------------------------------------------

Difference between static data member (class) and non static ( instance data member );_

1. Static D.M represent the property of a class where non static represent the property of Object.

2. If an a program any data which is common for all makes it static otherwise non static.

3. Static data member allocates memory at class loading time in class are only once and this memory
shared multiple objects (Single copy). Where as non static datamember allocate memory in object
( heap area ) separately.

4. Standard approach to call the static data member with class name where in case of non static we call
it via object reference.
Syntax to call non static data member:-

1.) object.NSDM ( non static data member )

2.) objectRef.NSDM ( non static data member )

3.) Directly( NSDM ) inside non static method and constructor

Rule:-NSDM and NSMF can not directly access in side static context.( Static method or Staic block)

Syntax to call non static member function:-

1.) object.NSMF ( non static member function )

2.) objectRef.NSMF ( non static member function)

3.) Directly( NSMF ) inside non static method and constructor

Rule:- NSDM and NSMF can not directly access in side static context (static method or static block )

-----------------------------------------------------------------V53-------------------------------------------------------------

Syntax to call static data member :-

1. object.SDM (Same and other also class)

2. objectRef.SDM (Same and other also class)

3. Directly(SDM) Same class anywhere

4. ClassName.SDM (Same and other also class)

Syntax to call static member function:-

1. object.SDMF (Same and other also class)


2. objectRef.SDMF (Same and other also class)

3. Directly(SDMF) Same class anywhere

4. ClassName.SDMF (Same and other also class )

Note :- “Static” hamesa class ke name se call hota h generally aur “non-static” object ke referencese se call
hota h.

-------------------------------------------------------------------V54-----------------------------------------------------------

Watch again

-------------------------------------------------------------------V55-----------------------------------------------------------

-------------------------------------------------------------------V56-----------------------------------------------------------

class loading:-

JVM invoked and run our program, Before running the program JVM first load the class into memory.
Storing the class specific information (dm, mf, static data) into memory is called class loading process. Class
loading is done by class loader.

Class loaders:-are the software program which is running inside the JVM . The main purpose of class loader
to store the class specific information in memory.

EX:- bootstap, extension, application

JVM Architecture
static Block:-

IT execute only once at class loading time before main method. --

staic block class loading time pr chalta h aur issi time pr static data ko memory bhi milti h.

Bina “main” ke bhi program bana sakte h sirf “static block” ke sath.

Every work you can do inside the “static block” which you are doing in the “main” method.
------------------------------------------------------------V57-------------------------------------------------------

Sequence of constructor, static block and main method:-

command line se Runtime pe argument nhi de sakte static block mai.

-----------------------------------------------------------V58-------------------------------------------------------

CommandLine Argument:-

It is the process of passing the values from commandLine at runtime.


-----------------------------------------------------------------V59-------------------------------------------------

Data Shadowing:-

When x is a program the name of instance variable and the name of local variable are same this
concepts is called data shadowing.

In case of data shadowing always preference goes to local variable.

-----------------------------------------------------------------V60-------------------------------------------------

Static and Object ek dusre ke viprit h.

This keyword:- is the reference variable which holds the reference id of current object.

-----------------------------------------------------------------V61------------------------------------------------

“this” current class ki reference id sambal kr rakhta h. “this” mai current class ka Object hota h.

“this” ka use non static aur constructor mai hota h.

• This keyword can not be used inside static context.

• This is implicitly available in every non static method and constructor.

• Static variable ya method ko class name se call karna chahiye

----------------------------------------------------------------V62---------------------------------------------------

Use of “this” :-

1. it is used to identify the instance variable incase of data shadowing.


2. “this” keyword is used as a method argument in order to refer the current object.

3. “this” keyword is also used incase of method chaining. Calling multiple method on single
object.

4. Calling multiple constructor on a single object.

5. We can call any static or non static both method via this.

6. It is also used incase of forward referencing.

Method Chaining:- Method chaining is a process of calling a multiple method on a single object.

Constructor Chaining:- Constructor chaining is a process of calling multiple constructor on a


single object.

---------------------------------------------------------V62---------------------------------------------------------

---------------------------------------------------------V63---------------------------------------------------------

----------------------------------------------------------V64---------------------------------------------------------

----------------------------------------------------------V65---------------------------------------------------------
-----------------------------------------------------------V66--------------------------------------------------------

----------------------------------------------------interface-------------------------------11-11-23---------------

Interface just like a class, which containd only abstract method.

• Inerface methods are bydefault public & abstract.

• Interface variable are bydefault public, static , final,

• interface method must be overriden inside the implementing classes.

• Interface nothing but deals between client & developer.

Multiple Inheritance:-

We can achieve multiple inheritance through interfaces because interface contains only
abstract method, which implementation is provided by the sub classes.
------------------------------------------------------------------------------------------------------------------------

Reusability of Class Code

1. Association ( Non blood relation ) --HAS-A-relation (0 to 100% usability)--> Kisi ek class ka


objectn kisi dusre class mai banane ko Association kehte h.

Association is creating the object of a class into another class.

a.) Composition (Strong Relation )

b.)Aggregation (Weak Relation)


2. Inheritance ( Blood relation ) --IS-A-relation (100% usability)-->

It is one of the way to achieve reusability in java.

It is the process of acquiring the property and behaviour of parent class (base, super) into a new
class called child class (derived, subclass) with own property and behaviour.

-------------------------------------------------------------V67------------------------------------------------------

Note:- In java we are using extends keyword to inherit a class.

Advantages of Inheritance

1. Reusability

2. To achieve runtime polymorphism

3. Dara hiding

4. Method overriding

Note :- When ever inheritance is done all data and function are accessible in child class.

Note:- Kisi class ke non static data ko access kerne ke total 6 tarike h

------------------------------------------------------------------V68------------------------------------------------
Types of Inheritance:-

1. Single level inheritance

2. Multi Level inheritance

3. Multiple inheritance XXXX

4. Hybrid Inheritance-->Combination of any two inheritance XXXX

5. Hierarical or Network Inheritance


Note:- In java by default every class performed inheritance. -- Java.lang.Object

UML diagram -Unifinde Modaling Language (Use case diagram):- UML is popular for
its diagrammatic notations. We all know that UML is for visualizing, specifying, constructing and
documenting the components of software and non-software systems. Hence, visualization is the
most important part which needs to be understood and remembered.

ERD () & DFD(Data flow Diagram)

-------------------------------------------------------V69------------------------------------------------------------

In Java there is no any support of Multiple and Hybrid inheritance in case of classes. Because data
ambiguity

In Java we have interface by which we achieve both Multiple and Hybrid inheritance.

-------------------Very Important-------------------V70----------------------------------------------------------

Data Hiding:- When in a program the name of parent class data and the name of child class are
same this concept is called Data Hiding.

When ever data hiding is done always preference goes to child class data.

Note:- Data shadowing happen in single class where as Data hiding done in two classes (parent and
child class).

Super:- We can call parent class data in case of Data Hiding.

Super is used to call the immediate patent data not parent of parent.

Rule:- Super can’t use inside static context like ”this”.

How memory is allocated in case of inheritance:-

In case of inheritance all the data of parent class gets memory in to the child class object.
Rule:- In Java we can hold the child class Object into reference variable of parent class. This is
concept is called Upcasting.
---------------------------------------------------V71----------------------------------------------------------------

Method OverRiding:- ( Rewrite )

When in parent class and child have same name of method with signature so we can say that child
class override the parent class method and concept is called method overriding.
When ever method overriding is done always preference goes to child class overridden method.

--------------------------------------------------------V72---------------------------------------------------------

Covariant Return :-

Before jdk1.5 we are not able to override method by changing the return type but from jdk1.5. It is
possible to override a method by changing the return type this concept is called covariant type.

But we need to follow the some condition:-

1. Both class method must have return type is reference type where as primitive data type not
allowed.

2. The classes which used as a return type they also must have relation of parent and child.

3. Parent class method must return parent class object and child class method must return child
class object.

---------------------------------------------------------V73---------------------------------------------------------

Access Specifier:-

1. Public

2. Protected

3. Default
4. Private

(stronger to weaker sequence) -1-2-3-4->

• Whenever we did method overriding always sequence must be weaker to stronger.

• In Java we can’t override static method.

Static--to--non static not valid

non static--to--static not valid

static--to--static valid (method hiding)

Method Hiding:- If we override a method by making static this is method hiding.

Topic we studied

Data Shadowing
Data Hiding
Method Overloading
Method Overriding
Constructor Overloading
Method Hiding
---------------------------------------------------------V74---------------------------------------------------------

Note:- In a single Java file we can have many classes.

Ques1. In a single Java file we can have many classes?

Ans1. Yes, we can have number of classes in a single Java file.

Ques2. Is ques1 is true then what is the name of byte code?

Ans2. Byte code of every class store in a separate “.class” file.

Ques3. Can we compile Java program without main?

Ans3. Yes.

Ques4. Can we run Java program without main?

Ans4. Yes.

Ques5. If ques1 true then in which class we have main method?

Ans5. We can have main method in every class.


Ques6. If ques1 true then from which class name we have to compile the class?

Ans6. We always compile program via file name.

Rule:- In Java in a single file we can have only one public class is allowed.

Rule:- If the class is public then the class name and file name must be same.

Rule:- Byte code of every class store in a separate “.class” file.

Steps when Java Program Compile and Execute:-

1. Compilation --- javac filename.java


During Compilation compiler did the below activity.

1.1. Byte code generated

1.2. During combination compiler create default constructor if we are explicitly providing any
constructor in the program.

1.3. Compiler added the magic number for security

1.4. Compiler did the static binding.

1.5. Create init block to initialize all then on static data.

1.6. Create the static block to initialize all the static data.

1.7. Compiler added “this” and “super” when required.

1.8. Compiler extends the object class in every class directly or indirectly.

1.9. Compiler changes the method signature and added the assembly instruction in byte code.

-----------------------------------------------------------V75,76,77-----------------------------------------------

2. Run the Java program. -- java classname

2.1. java tool invoke the JVM and JVM taken the class name as input.(JVM is an Interpreter)
2.2. jvm start so many threads in memory. (like-Main, GC, etc)

Note:- All the program of java running on the separate thread class main thread.

2.3. class Loading (on main thread)

It is the process of storing class specific information (D.M , M.F, Constructor etc) into memory.

Class loading is done by class loaders.

Class Loaders:- They are software which is responsible to performed class loading process.

Types of Class Loaders

1. Extension Class Loaders ( C:\Program_Files\java\jdk1.8_231\jre\ext )

2. Application Class Loaders ( enviroment variable )

3. Bootstrap Class Loaders ( C:\Program_Files\java\jdk1.8_231\jre\lib ) -rt.jar

Class ki kon-kon si cheze kaha kaha jati h.

1. Static data member –go to -->class areas

2. Instance variable object –go to -->heap areas

3. All Methods –go to -->method area ke (method table)


4. All local variable –go to -->stack areas

Memory is allocate to all the static data member.

Default values are initialized to static data member.

Static block are executed in given order (if any)

(All these above are Class loading)

Ques. How class loader doing the class loading process?

JVM—>main thread-->class loading—>linking--->verification—>execution.

--------------------------------------------------------V78---------------------------------------------------------

To see which class main thread are running currently-

-------------------------------See Again------------------V79-----------------------------------------------------

API:- set of inbuilt libraries and predefine functions in every programming language is call API ,
The form of API is vary from language to language.
Java Reflection :- Java Reflection is a process of examining or modifying the run time behavior of
a class at run time. Java Reflection API is used to manipulate class and its members which include
fields, methods, constructor, etc. at runtime.

Reflection API :- java.lang.reflect

In java there is an class whose name is class.

class Class

class Class ke methods :-


Types of class loading:-

1) Static class loading:- In case of static loading compiler have already knowledge about

loaded class.

When we use any other class into our class.

 Static Data Member class

 Object Create

 Inheritance

2) Dynamic class loading:- In case of static class loading done not have knowledge about

loaded class.

------------------------------------------------------V80----------------------------------------------------------

JVM Architecture

-------------------------------------------------------V81----------------------------------------------------------

“main” is the entry point of the program . Its name is main because C and C++ is also main
function.

“main” method ko bina kisi object ke call kr skte h aur krte h.

Static method ko bina object ke call kr skte h.

“main” is an identifier.

---------------------------------------------V82-----------------------------------------------------------

Wrapper Class:- Wrapper classes are those which provide us facility to convert any primitive data

into object and vice-versa.

In java to represent every data type into object there is some wrapper class is available.

In java there are so many wrapper classes are available for every primitive data type.
----------------------------See Again------------------V83--------------------------------------------------------

E-Encapsulation

I-Inheritance

P-Polymorphism

Encapsulation:- Encapsulation is the process of wrapping the data member and member function

into a single unit called class.

The process of encapsulation is to achieve data hiding and class providing the implementation of
encapsulation.

Note:- Normal class are not providing 100% implementation of encapsulation.

JavaBean class(POJO) – plain old java object:-

JavaBean class provides 100% implementation of encapsulation. It is the general purpose reusable
piece of code.and this have the following characteristics:-

1) class should be public

2) It should have public default constructor

3) its data member should be private

4) This class should not extends any specific class or implement any interface ( but must
implements serializable )

5) It should have public settter and getter method.


---------------------------------------------------------V84-------------------------------------------------------

Rules of Constructor incase of Inheritance:-

Before executing any child class constructor firstly execute its immediate parent class default
constructor implicitly not parameterized.

---------------------------------------------------------V85--------------------------------------------------------

“super” and “this” ek constructor mai ek sath nhi ho skte.

----------------------------------------------------------V86--------------------------------------------------------

“this” apne class ke constructor ko call krta h

“super” apne parent class ke constructor ko call krta h.

----------------------------------------------------------V87--------------------------------------------------------

RuntTime Polymorphism mtlb runtime pr ek method ki calling ka, method ki definition se binding
hona.

Jaha pr upcasting aur method overidding dono ho rahe ho wahi Runtime Polymorphism ka example
h.
RunTime Polymorphism or Dynamic method dispatch or Dynamic Binding all are same thing.

Q.. How we can achieve RuntTime Polymorphism in java?

Ans..We have create the two classes parent and child and we have to override the method of parent
class into the child class . We have method for parent and child class . Then create the object of
child class having the reference variable of parent class when we are calling the method of parent
class at compile time the method is going to be call by the compiler or parent class but at runtime if
this object is of the child type so in child class method is overridden or not if the method is
overridden preference goes to overridden method to achieve runtime polymorphism using method
overriding.

Example:-
-----------------------------------------------------V88-------------------------------------------------------

Binding:- connection (Linking) a member call gets their member definition called Binding.

Binding is a physical entity.

Types of Binding

1. Compile Time Binding or Static Binding or Early Binding ( doing by Compiler ) -- when
a member call gets their member definition at compile time it is called compile Time
Binding. Compile time binding done by compiler on the basis of Type of reference.

2. RunTime Binding or Late Binding or Dynamic Binding ( doing by JVM ) -- when a


member call gets their member definition at runtime time it is called runtime time binding.
Runtime time binding done by JVM on the basis of type of Object.

Note:- In Java only non static ( virtual method ) method are dynamically and rest are bind statically.

Rule:- the object child is Child Type also it is of parent type.

Instanceof Operator
----------------------------------------------------V89---------------------------------------------------------

Things which are statically bind:-

1. Data member ( static or non static)

2. static method

3. private method

4. final method

5. constructors

6. initializer

7. method call via super keyword

Things which are dynamically binds:-

1. non-static method or virtual method.

Jo compiler ko pta ho wo static binding aur jo JVM ko pta ho wo dynamic binding.


----------------------------------------------------------V90------------------------------------------------------

----------------------------------------------------------V91------------------------------------------------------

-----------------------------------------------------------V92------------------------------------------------------

Polymorphism : -One name many forms or If one entity have different form called polymorphism.

It is a logical concept.
Poly – many

morphism – forms

Note:- Polymorphism always achieve on method/member function not on data member. In order to
achieve polymorphism we are using the concept like method overloading , method overriding,
operator overloading, constructor overloading .And these are the terminologies we are using in
order to achieve the polymorphism concept.

Note :- operator overloading concept is not available in java . But it is implicitly available in java
like instanceof operator.

Example :-
In General Type of Polymorphism:-

1. Compile Time or Static Polymorphism:- jab koi object apne behaviour ke sath compile time
pr bind ho to compile polymorphism.

2. RunTime or Dynamic Polymorphism:- jab koi object apne behavior ke sath runtime pr bind
ho to runtime polymorphism.

-------------------------------------------------------V93-----------------------------------------------------------

RunTime Polymorphism

ex- Method overriding:-

Method overloading:- In a program if we have a same name with different signature this is

called method overloading. And polymorphism Object ka feature h.

Note:- In method overloading accessRule and return type are not participating. It means in method
overloading only role parameter is applicable.
Argument:-

1. Same argument with different data type.

2. Same data type with and number of argument is different.

3. Argument and Data type both are different.

Note:- Static method or variable class ke name se call ya access ki ja skti h (it is call static
binding) . jabki baki non-static method or variable object ke reference se call ya access kiye ja skte
h.

----------------------------------------------------------V94------------------------------------------------------

----------------------------------------------------------V95------------------------------------------------------

----------------------------------------------------------V96------------------------------------------------------

Topics we discussed--> Object, class, this, super, encapsulation, inheritance, polymorphism,

abstraction

Final keyword:-

1. Final

2. Finally

3. Finalized
Final:-

It is the keyword that can be use on the following places.

1. class

2. method

3. local variable

4. data member

Finla class :- when we put final keyword with class then class become final and it is called final

class.

Note:- final class can not inherited in java.


Final method :-When we put final keyword with method then method become final.

Note:- final method can not override in java.

Final local variable:- if local variable is final so its value can not re-assigned.

Final Data Member:- If data member is final so its value can not re-assigned.

-------------------------------------------------------V97------------------------------------------------------

Abstraction:- kisi bhi object ki jarurat wali chizo ko show karana aur uss object ki jo jarurat wali
cheze nhi h usko hide karna Abstraction kehlata h.

It is the process of creation generic method.

Generic method have only declaration and its implementation is providing by different-2 user
accordingly.

It is the process of showing the essential functionality of an object and hiding unessential
complexity. ( Show functionality and hide complexity )

• Abstraction is always achieved on method and member function.

• We can’t doing any abstraction on data.

Advantage:-

• By abstraction we can achieve RunTime polymorphism.

• Complexity reduction

Working of Abstraction --> Show function and hide its implementation.

Implementation of Abstraction:-
1. Abstraction class ke through – yeh 0 to 100% abstraction deta h

2. Interface ke through – yeh 100% abstraction deta h.

Astract keyword can be applied:-

1. class pr --> When we use the abstract keyword with class then its is called abstract class.

2. method pr --> When we use the abstract keyword with method then its is called abstract

method.

Abstract keyword can’t be applied:-

1. data member pr nhi

2. constructor pr nhi

Features of Abstract class:-

• It may or may not have abstract method.

• We can not create the object of an abstract class.

Features of Abstract Method:-


• Abstract method can not have body

• It have only declaration

• It’s implementation is providing by different-2 user accordingly.

• Abstract method must be inside the Abstract class.

• Abstract method kabhi final ,private, static nhi ho skta.

Rule:- If any child class extends the abstract class then child class have to override all the

abstract method of abstract class otherwise child have to be abstract.

------------------------------------------------V98-----------------------------------------------------------

Interface:-

• It is another way to achieve abstraction.

• It is blueprint of class.

• It is combination of public. Static. Final data member and public abstract method.
• It is contract between two parties programmer and programming language.

• When a class implements an interface then class has to override all the method of
interface with public access privilege otherwise class has be abstract.

Note:- We can’t create object of a interface class because interface is abstract type.

Some Points:-

• class ko class main use krne ke liye to inheritance ka Extends

• koi class interface mai use ho ra h to implements

• ek interface dusre interface ko extends kr skta h.

Rules of Inheritance
--------------------------------------------------------V99--------------------------------------------------------

--------------------------------------------------------V100-------------------------------------------------------
--------------------------------------------------------V101-------------------------------------------------------

Operators:- are the symbol which are used to performed operation over operand.

Operators and their precedence:-


Do operator programs

Construct:-

• looping ( for, while, do while )---- Repetition task done by loop

1. For loop :- use if condition is finite

2. While loop:- use if condition is infinite

• conditional ( if, else, if else, switch case )

-------------------------------------------------------V102--------------------------------------------------------

Topics of Java SE( Standard Edition ) _CORE_:-

• Package

• access rule

• array
• string

• exception

• thread

• AWT & Swing

JEE( Java Enterprises )_Advance_:-

• Collection

• JDBC SQL

• I18N

• Servlet and JSP

• HTML bootstrap ( web designing )

• Web Services

• RMI

• EJB

Framework:-

• Struts

• Hibernate

• Spring

Package

A package is the logical categorization of similar type of classes , interface and sub packages. In
java, java categorized their classes and interface into a logical container and this container is called
package.
Physical package is the folder and logically it is the container.

Advantages:-

• Linking & Searching

• Unique name space

• Implementation of Access Rule

Type of packages

• Predefine

• User define

How to create a package in java:-


1. creating logical packages

2. creating physical package

How to import Package:-


---------------------See Again------------------------------V103-------------------------------------------------

For making java packages by CMD :-

Two ways to use packages in class:-

1. Import java.util.Scanner ---( package ko import krte h )

2. java.util.Scanner sc = new java.util.Scanner(); -----( class ko inherit krte h )

-----------------See Again--------------------------------V104---------------------------------------------------

-------------------------------------------------------------V105----------------------------------------------------

Package Accessibility:-

Same Other
package package
Same class Sub class Non sub Subclass Non sub
class class
Public Yes Yes Yes Yes Yes
Protected Yes Yes Yes Yes (only No
with child
reference)
Default Yes Yes Yes No No
Private Yes No No No No
Example:-

-----------------------------------------------------------------

Arrays (contiguous):- collection of similar type of data store in the contiguous memory location
(i.e. index form).

Types of Array

1. Single Dimensional Array

2. Multi Dimensional Array

In C programming array is static and in Java array is dynamic.


In Java array id represented by Objects.

----------------------------------------------------------V106------------------------------------------------------

Memory structure of Array:-

2D Array:-
----------------------------------------------------------V107------------------------------------------------------

----------------------------------------------------------V108------------------------------------------------------

String:-

• It is a sequence of character.

• It is the combination of character.

• It is class in java found in java.lang package.

• It is implicit array of character type.

• It provide the implementation array.

String Handling:- The process of performing over the string is called string handing.
• Length

• concat

• substring

In java string is represented by an object.

In java in order to perform operation over the string we have following classes

1. java.lang.String

2. java.lang..StringBuffer

3. java.lang..StringBuilder

4. java.lang..StringTokenizer
String class:-#

• It is public and final.

• It is the immutable sequence character.

Immutable—unchangeable , Means in the ine object of string class we can not perform operation
like append , delete, sub string.

How to create the object of string class:-


1. with new

2. without new or by string literal:- in this approach when we are creating the string object via

literal – actually we are just holding the string literal into

the variable.

And in java it is rule all the string literal are treated as the string object.

And when ever we are creating the string object via literal it allocated memory in String
Constant Poll area (it does not allowed duplicated element).

----------Don’t see-------------------------------------V109-----------------------------------------------------

-----------------------------------------------------------V110-----------------------------------------------------

String Comparision:-
1. equals:- There are two equals Object ka equal and Class ka equal.

• equals method it is object.

• Object reference id comparisons

• If same then return true otherwise return false

• equals method of String :- string override the object class equals method.
• If content same the return true otherwise return false.

2. == operator

• ==operator is equivalent to the equals method of object class.

3. equalsIgnoreCase

4. CompareTo

5. CompareToIgnoreCase

------------See again-----------------------------------V11--------------------------------------------------------

Java String class methods


The java.lang.String class provides many useful methods to perform operations on sequence of char
values.

No. Method Description


It returns char value for the particular
1 char charAt(int index)
index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

static String format(Locale l, String format, It returns formatted string with given
4
Object... args) locale.

It returns substring for given begin


5 String substring(int beginIndex)
index.

It returns substring for given begin


6 String substring(int beginIndex, int endIndex)
index and end index.

It returns true or false after matching


7 boolean contains(CharSequence s)
the sequence of char value.

static String join(CharSequence delimiter,


8 It returns a joined string.
CharSequence... elements)

static String join(CharSequence delimiter,


9 It returns a joined string.
Iterable<? extends CharSequence> elements)

It checks the equality of string with the


10 boolean equals(Object another)
given object.

11 boolean isEmpty() It checks if string is empty.


12 String concat(String str) It concatenates the specified string.

It replaces all occurrences of the


13 String replace(char old, char new)
specified char value.

String replace(CharSequence old, CharSequence It replaces all occurrences of the


14
new) specified CharSequence.

It compares another string. It doesn't


15 static String equalsIgnoreCase(String another)
check case.

16 String[] split(String regex) It returns a split string matching regex.

It returns a split string matching regex


17 String[] split(String regex, int limit)
and limit.

18 String intern() It returns an interned string.

It returns the specified char value


19 int indexOf(int ch)
index.

It returns the specified char value


20 int indexOf(int ch, int fromIndex)
index starting with given index.

21 int indexOf(String substring) It returns the specified substring index.

It returns the specified substring index


22 int indexOf(String substring, int fromIndex)
starting with given index.

23 String toLowerCase() It returns a string in lowercase.

It returns a string in lowercase using


24 String toLowerCase(Locale l)
specified locale.

25 String toUpperCase() It returns a string in uppercase.

It returns a string in uppercase using


26 String toUpperCase(Locale l)
specified locale.

It removes beginning and ending


27 String trim()
spaces of this string.

It converts given type into string. It is


28 static String valueOf(int value)
an overloaded method.

----------------------------------------------------------V12--------------------------------------------------------
---------See again-------------------------------------V113-------------------------------------------------------

java.lang..StringBuffer:- StringBuffer ke methods synchronized h.

• it is the mutable sequence of character.

• In the one object of String buffer we can do modification like, insert , delete ,append,
update.

• SringBuffer ke most methods Synchronized h.

Methods

java.lang..StringBuilder:- StringBuilder ke methods asynchronized h.


• SringBuilder ke most methods Synchronized nhi h.

Methods

java.lang..StringTokenizer
Methods Of StringTokenizer Class

Method Action Performed

countTokens() Returns the total number of tokens present

Tests if tokens are present for the StringTokenizer’s


hasMoreToken()
string

nextElement() Returns an Object rather than String

hasMoreElements() Returns the same value as hasMoreToken

Returns the next token from the given


nextToken()
StringTokenizer.

-----------Important See Again---------------------V114-------------------------------------------------------

Exception:- Exception is an abnormal condition/situation which occur in an program at runtime.

Exception handling (Apwad – abnormal condition ):- Exception handling is a process of handling
runtime errors.

Java Exception Hierarchy:-


For Exception handling java gives 5 keywords:-

• try

• catch

• finally

• throw

• throws

Difference between Error and Exception


• Error: An Error indicates a serious problem that a reasonable application should not try to
catch.

• Exception: Exception indicates conditions that a reasonable application might try to catch.

--------------See Again------------------------------V115--------------------------------------------------------

--------------------------------------------------------V116--------------------------------------------------------

Exception:- Exception ek abnormal situation h jo kisi program pr runtime pr ata h. Iss exception se
hamara program terminate ho jata h. Rest of code maintain ho paye isliye Exception handling krte
h.

• Iss line of code mai exception aane ke chances ho uss line of code ko try block mai dalte h.

• Try ke sath Catch ya Final block hona chahiye.


------------------------------------------------------V117----------------------------------------------------------

Alag-alag Exception aane pr alag-alag message dene ke liye multiple try-catch lagate h.

--------------See Again---------------------------V118-----------------------------------------------------------

------------------------------------------------------V119-----------------------------------------------------------
------------------------------------------------------V120-----------------------------------------------------------

Finally:- finally ka block hamesa chalega hi chalega.

In Java, there are two types of exceptions:

• Checked Exception:- Checked Exception are known by Compiler at compile time.

--These are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must
specify the exception using the throws keyword. In checked exceptions, there are two types:
fully checked and partially checked exceptions. A fully checked exception is a checked
exception where all its child classes are also checked, like IOException, and
InterruptedException. A partially checked exception is a checked exception where some of
its child classes are unchecked, like an Exception.

• Unchecked Exception:- Checked Exception are known by JVM at Runtime.

--These are the exceptions that are not checked at compile time. In C++, all exceptions are
unchecked, so it is not forced by the compiler’s to either handle or specify the exception. It
is up to the programmers to be civilized and specify or catch the exceptions. In Java,
exceptions under Error and RuntimeException classes are unchecked exceptions, everything
else under throwable is checked.

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run.
The compiler allows it to compile because ArithmeticException is an unchecked exception.
------------------------------------------------------V121-----------------------------------------------------------

Types of Finally Condition:-

------------------------------------------------------V122-----------------------------------------------------------

Difference between throw and throws :-

• throw ( used for both Checked and Unchecked Exception ):- kisi bhi program mai koi
bhi Exception forcefully (Explicitly) throw karane ke liye h. Program mai Explicitly apni
requirement ke hisab se Exception throw karane ke liye throw keyword ka use krte h. In
case of custom Exception throw used.
• throws ( mostly used for checked Exception ):- Throws keyword is just providing the
indication to the end user that what type of Exception may occur in the program.

Program mai kis trh ki Exception aa skti h ye indicate krta h.


Jis bhi method ke aage throws likha hota h us method ko jab ham call krte h . to uss method
ko call krne se pehle try catch lagana jaruri hota h. Qki throws indicate krta h ki uss method
mai kis kis trh ke Exception aa skte h.

------------------------------------------------------V123-----------------------------------------------------------

Difference between throw and throws :-


throw throws
• Throw keyword is used to throwing an • Throw keyword is not used to throwing
Exception Explicitly in a program. an Exception Explicitly in a program.

• Throws is a part of method • Throws is a part of method signature


implementation
• Throws keyword is just providing the
indication to the end user that what type
of Exception may occur in the program.

Exception Propagation ( apwado ka sancharan ):- Agar kisi program ke bilkul top of the stack mai
koi Exception aata h. To wah apne bottom of the stack mai jati h aur check krti h ki waha try-catch
h ya next wale mai and so on. Jab tak try-catch nahi mil jata ya program ke end mai nhi pahuch jata.
Exception Propagation kewal unchecked Exception ke liye hoti h.

• If in a program any Exception is going to be occur in a top of the stack so it is automatically


redirected to the bottom of the stack until it is going to be the bottom of the stack or it is
going to be handle with try and catch.

Example:-
------------------------------------------------------V124-----------------------------------------------------------

Custom Exception:- Khud ki Exception class bnana

Steps to create Custom Exception:-


Example:-

------------------------------------------------------V125-----------------------------------------------------------

Thread:-

• It is the light weight process/task/program.

• it is a subprocess.

• it is a process inside process.

• it is a smallest part of processes.


How we create Thread program:-

1. by extending thread class

2. by association-(Object creation) of thread class-(by implementing Runnable interface)

Note:-

------------------------------------------------------V126-----------------------------------------------------------

Program-(Task) in active state is call Process


-----------See Again-------------------------------V127-----------------------------------------------------------

Thread:- Before introducing the thread concept, we were unable to run more than one task in
parallel. It was a drawback, and to remove that drawback, Thread Concept was introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the process that
allows a program to operate more efficiently by running multiple tasks simultaneously.
In order to perform complicated tasks in the background, we used the Thread concept in Java. All
the tasks are executed without affecting the main program. In a program or process, all the threads
have their own separate path for execution, so each thread of a process is independent.

Note:- Multi-threading ka concept Application mai hota h . Aur Multi-Processing ka concept


Operating system mai hota h.

Use of Thread:-

• Application ke andar Multi-tasking krne ke liye.

thread vs Process :-
Program vs Process vs Thread :-

Thread in Computer Architecture:-


------------------------------------------------------V128-----------------------------------------------------------

Implementation of thread:-

How we create Thread program:-

• by extending thread class

Example of Single task Multi-Thread:-


• by association-(Object creation) of thread class-(by implementing Runnable interface)

Note :- Thread ka koi sequence nhi hota.

-----------------V129--------------

-----------------V30----------------

------------------------------------------------------V131-----------------------------------------------------------

Multi-Threading and Multi-Tasking :-


Java Thread Methods:-

S.N. Modifier and Type Method Description


It is used to start the
1) void start() execution of the
thread.

It is used to do an
2) void run()
action for a thread.

It sleeps a thread for


3) static void sleep() the specified amount
of time.

It returns a reference
to the currently
4) static Thread currentThread()
executing thread
object.

It waits for a thread


5) void join()
to die.

6) int getPriority() It returns the priority


of the thread.

It changes the
7) void setPriority() priority of the
thread.

It returns the name


8) String getName()
of the thread.

It changes the name


9) void setName()
of the thread.

It returns the id of
10) long getId()
the thread.

It tests if the thread


11) boolean isAlive()
is alive.

It causes the
currently executing
thread object to
12) static void yield()
pause and allow
other threads to
execute temporarily.

It is used to suspend
13) void suspend()
the thread.

It is used to resume
14) void resume() the suspended
thread.

It is used to stop the


15) void stop()
thread.

It is used to destroy
16) void destroy() the thread group and
all of its subgroups.

It tests if the thread


17) boolean isDaemon()
is a daemon thread.

It marks the thread


18) void setDaemon() as daemon or user
thread.

It interrupts the
19) void interrupt()
thread.

It tests whether the


20) boolean isinterrupted() thread has been
interrupted.
It tests whether the
21) static boolean interrupted() current thread has
been interrupted.

It returns the number


of active threads in
22) static int activeCount()
the current thread's
thread group.

It determines if the
currently running
23) void checkAccess() thread has
permission to
modify the thread.

It returns true if and


only if the current
24) static boolean holdLock() thread holds the
monitor lock on the
specified object.

It is used to print a
stack trace of the
25) static void dumpStack() current thread to the
standard error
stream.

It returns an array of
stack trace elements
26) StackTraceElement[] getStackTrace() representing the
stack dump of the
thread.

It is used to copy
every active thread's
27) static int enumerate() thread group and its
subgroup into the
specified array.

It is used to return
28) Thread.State getState() the state of the
thread.

It is used to return
the thread group to
29) ThreadGroup getThreadGroup()
which this thread
belongs

30) String toString() It is used to return a


string representation
of this thread,
including the
thread's name,
priority, and thread
group.

It is used to give the


notification for only
31) void notify() one thread which is
waiting for a
particular object.

It is used to give the


notification to all
32) void notifyAll()
waiting threads of a
particular object.

It sets the context


33) void setContextClassLoader() ClassLoader for the
Thread.

It returns the context


34) ClassLoader getContextClassLoader() ClassLoader for the
thread.

It returns the default


handler invoked
static
getDefaultUncaughtExceptionHan when a thread
35) Thread.UncaughtException
dler() abruptly terminates
Handler
due to an uncaught
exception.

It sets the default


handler invoked
setDefaultUncaughtExceptionHand when a thread
36) static void
ler() abruptly terminates
due to an uncaught
exception.

by association-(Object creation) of thread class-(by implementing Runnable interface)

Better Approach
Note :- Always use Implementation over Extends incase of Threads.

Thread class internal architecture in Java:-


------------------------------------------------------V132-----------------------------------------------------------

Life Cycle of Thread in Java :-


------------------------------------------------------V133-----------------------------------------------------------

--------------See Again----------------------------V134-----------------------------------------------------------

Join method in Thread:-

Join:- Jis thread ko join krte h aur jaha join krte h.wo thread (jisne join kiya h) wahi suspend ho jati
h . Aur wo tabtak suspend rhti h . jabtak join thread apna pura kaam na kr le ya timeout na ho jaye.
Example:- Thread without join method

import java.lang.Thread;

class ThreadTest1 extends Thread


{
ThreadTest1(String name)
{
super(name);
}

public void run()


{
for(int i=1;i<=5; i++)
{
System.out.println("Thread1:"+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":Dead");
}
}
}

class ThreadTest2 extends Thread


{
ThreadTest2(String name)
{
super(name);
}

public void run()


{
for(int i=1;i<=10; i++)
{
System.out.println("Thread2:"+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":Dead");
}
}
}

class ThreadTest3 extends Thread


{
ThreadTest3(String name)
{
super(name);
}

public void run()


{
for(int i=1;i<=15; i++)
{
System.out.println("Thread3:"+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":Dead");
}
}
}

class JoinMethod
{
public static void main(String argd[])
{
ThreadTest1 t1=new ThreadTest1("First");
ThreadTest2 t2=new ThreadTest2("Second");
ThreadTest3 t3=new ThreadTest3("Third");

t1.start();
t2.start();
t3.start();

/*try
{
t1.join(10);
t2.join(10);
t3.join(10);
}
catch(InterruptedException e1)
{
e1.printStackTrace();
}*/
}
}
Output without Join method

----------------------See Again-------------------V135-----------------------------------------------------------
Types of Thread:-

• main Thread

• User define Thread

• Daemon / Service provider / Background / Low Priority-(Bhoot, Pisaach, Rakchas--> Jo


dikhe nhi) Thread:- Daemon Thread veh threads hote h jo dikhte nhi h aur background mai
apna task krte h . like – Garbage Collector .. Ham User Define thread ko Daemon Thread
bana skte h.

Daemon Thread ek esa thread h jo background mai kaam krta rehta h. Hame kuch output nhi
deta but background mai apna serivce aur task achieve krta rehta h.

Koi bhi application ke andr background task krne ke liye uss task ko Doemon thread ke andr
bankr rkh skte h.

Daemon Thread main thread ko Service provide karata h. Agar Main thread dead ho jage to
Daemon thread bhi dead ho jayegi.

Example:-

import java.lang.Thread;

class MyThread extends Thread


{
MyThread(String string)
{
super(string);
}

public void run()


{
for(int i=1;i<=5; i++)
{
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().isDaemon());
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}

class DaemonThread
{
public static void main(String argd[])
{
MyThread t1=new MyThread("child");
t1.setDaemon(true);
t1.start();

for(int i=1;i<=5; i++)


{
System.out.println(Thread.currentThread().getName());
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}

Output

• Green Thread

• Shutdown Hook Thread ----- See Again 15:00 -----

------------------------------------------------------V136-----------------------------------------------------------
Synchronization-( Taal-Mel ) :-

• The process of executing thread in a sequencial manner is nothing but Synchronization.

• Synchronization Process aur Thread dono pr hota h ... ismai Thread ki baat ho ri h.

• Synchronization na hone se Threads mai interference hoti h.

• Synchronize Thread is safe and slow. Asynchronize Thread is unsafe and fast
Synchronization Vs Concurrency :-

Mutual Exclusive :-

• Synchronized Method :- Method ke aage synchronized keyword ka use krke.

Example:-

import java.lang.Thread;

class Table //Common Resource


{
synchronized public void printTable(int x)
{
for(int i=1; i<=10; i++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println(x*i);
}
}
}

class MyThread1 implements Runnable //First Thread


{
Table t;

public MyThread1(Table t)
{
this.t=t;
}

public void run()


{
t.printTable(2);
//Table.printTable(2);
}
}

class MyThread2 implements Runnable //Second Thread


{
Table t;

public MyThread2(Table t)
{
this.t=t;
}

public void run()


{
t.printTable(3);
//Table.printTable(2);
}
}

class MyThread3 implements Runnable //Third Thread


{
Table t;

public MyThread3(Table t)
{
this.t=t;
}

public void run()


{
t.printTable(6);
//Table.printTable(2);
}
}

class SynchronizeDemo
{
public static void main(String argd[])
{
Table t=new Table();

MyThread1 t1=new MyThread1(t);


Thread tt1=new Thread(t1,"one");

MyThread2 t2=new MyThread2(t);


Thread tt2=new Thread(t2,"two");

MyThread3 t3=new MyThread3(t);


Thread tt3=new Thread(t3,"three");

tt1.start();
tt2.start();
tt3.start();
}
}

Output – without synchronization

Output – with synchronization


-----------------------------------------------------V137------------------------------------------------------------

Lock in Java:- Lock ek implicit monitor variable hota h. Aur ye do tariko se liya ja skta h implicit

and explicit.

Lock means:- Lock means until the first thread or work is not done or complete it can’t release that

work.

• Agar method Static h aur Synchronized h to lock ki checking class level pr hoti h.

• Agar method non_Static aur Synchronized h to lock ki checking object level pt hoti h.

Types of Locking:-

1. Implicit monitor-( locking / lock ):- (a) If method is synchronized non-static then lock is
check on current object.

(b) if method is synchronized static then lock is check


on class.

(c) if method have synchronized block then

• Object Level Locks

• Class Level locks


2. Explicit monitor-( locking / lock )
Difference between Object level lock and Class level lock in Java:-
• Object Level Locks − It can be used when you want non-static method or non-static block
of the code should be accessed by only one thread.

• Class Level locks − It can be used when we want to prevent multiple threads to enter the
synchronized block in any of all available instances on runtime. It should always be used to
make static data thread safe.

-----------------------------------------------------V138------------------------------------------------------------

What is Synchronization and Why we require Synchronization:- In Java by default all the
threads are going to be executed in asynchronous-(random / zig-zag) manner and sometime we
requires to execute the thread in a sequencial manner so in this situation we have to go
Synchronization concept.

Why we require Synchronization:-

• Thread ki interference rokne ke liye

Synchronization na hone se kya problem aa skti h:-

1. Inconsistency problem

2. Interference problem

Synchronization achieve krne ke tarike:-

1. Mutual Exclusive:- ismai thread pr exact controlling nhi hoti like koi bhi thread kabhi bhi
chal skta h pr pura chalega.

• Synchronized Method:- Synchronized method is used to synchronized the whole

method.

• Synchronized Block:-Synchronized block is used to synchronized the portion

of method. Synchronized block method alway into the

method.
• Static Synchronized

2. ITC:- ismai thread pr exact controlling hoti like kon sa thread kab chalega.

• Wait()

• notify()

• notifyAll()

Note:- Method Synchronized ho skte h. Class kabhi Synchronized nhi hoti.

-----------------------------------------------------V139------------------------------------------------------------

Inter Thread Communication ( ITC ):- ek thread dusre se communicate krte h.

• wait() :- ye method currently executing thread ko running se suspended state mein lekr jata
h. Aur aur lock ko release kr deta h. Uss lock ko koi dusri thread use kr leti h.

• notify():- ye method suspended state thread ko firse running main la deti h.

• NotifyAll():- ye method sare suspended state methods ko firse running state mai la deti h.

-----------------------------------------------------V140------------------------------------------------------------

Inter Thread Communication Program:-

-------------------See Again----------------------V141------------------------------------------------------------

other ITC methods:-

• sleep()

• suspend() <-- depricated

• resume() <-- depricated

• intrupt()

Note:- kisi bhi package ke sabhi methods ko dekhne ke liye javap package_name ko CMD mai type
kr.

Example:-
------------------------------------------------IO Streams-V1------------------------------------------------------

InputOutputStream

in Hinid# input Output ek esa machanism hota h jaha se ham kisi bhi source se data ko read krte h
then process krte h after processing uss particular data ko further ham produce-(write) krte h .

in English# input Output is a facility in java by which we read the data from any source and write
the data to the any destination.

For import -- [ import java.util.Stream ]

Stream:-

• flow of any thing

• in Java -- flow of any data in the form of bytes

• in coding point of view Stream is a buffer

• Stream is represented by an Object or Stream is an Object in Java

• there is no any class in java whose name is Stream , Stream just a concept

• Stream is a flow of data in the form of bytes


C program:- C program is directly connected to any input output device.

Java :- Java program is not directly connected to any input output device so Java provides
inputOutputStream to communicate input output devices.

------------------------------------------------------V2--------------------------------------------------------------
• Byte Stream 8 bits (ASCII Code) ka buffer banata h . Aur 8 bits ke form main data redirect
krta h

• Character Stream 16 bits (Unicode) ka buffer banata h . Aur 16 bits ke form main data
redirect krta h

------------------------------------------------------V3--------------------------------------------------------------

ByteStream Classes in Java


ByteStream classes are used to read bytes from the input stream and write bytes to the output
stream. In other words, we can say that ByteStream classes read/write the data of 8-bits. We can
store video, audio, characters, etc., by using ByteStream classes. These classes are part of the
java.io package.
The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream.
These classes are abstract and the super classes of all the Input/Output stream classes.

• InputStream:-

InputStream Class
The InputStream class provides methods to read bytes from a file, console or memory. It is an
abstract class and can't be instantiated; however, various classes inherit the InputStream class and
override its methods. The subclasses of InputStream class are given in the following table.
SN Class Description
1 BufferedInputStream This class provides methods to read bytes from the buffer.

ByteArrayInputStrea
2 This class provides methods to read bytes from the byte array.
m

3 DataInputStream This class provides methods to read Java primitive data types.

4 FileInputStream This class provides methods to read bytes from a file.

This class contains methods to read bytes from the other input
5 FilterInputStream
streams, which are used as the primary source of data.

6 ObjectInputStream This class provides methods to read objects.

This class provides methods to read from a piped output stream to


7 PipedInputStream
which the piped input stream must be connected.

SequenceInputStrea This class provides methods to connect multiple Input Stream and
8
m read data from them.
The InputStream class contains various methods to read the data from an input stream. These
methods are overridden by the classes that inherit the InputStream class. However, the methods are
given in the following table.

• OutputStream:-

OutputStream Class
The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is the
superclass of all the output stream classes. This class can't be instantiated; however, it is inherited
by various subclasses that are given in the following table.
SN Class Description
1 BufferedOutputStream This class provides methods to write the bytes to the buffer.

ByteArrayOutputStrea
2 This class provides methods to write bytes to the byte array.
m

This class provides methods to write the java primitive data


3 DataOutputStream
types.

4 FileOutputStream This class provides methods to write bytes to a file.

5 FilterOutputStream This class provides methods to write to other output streams.

6 ObjectOutputStream This class provides methods to write objects.

7 PipedOutputStream It provides methods to write bytes to a piped output stream.

8 PrintStream It provides methods to print Java primitive data types.


The OutputStream class provides various methods to write bytes to the output streams. The methods
are given in the following table.

Concrete class:- Esi class jo kisi abstract class ko extends kare ya kisi interface ko implement kre

to wo Concrete class kehlata h.

Difference between Abstract and Interface :-

Character Stream:-

------------------------------------------------------V4--------------------------------------------------------------

FileInputStream:- FileInputStream is the concrete class or subclass of inputStream class . The one
object of FileInput class is responsible to read the data from file

Read an file with FileInputStream


FileOutputStream:- FileOutputStream is the concrete class or subclass of OutputStream class .
The one object of FileOutput class is responsible to write the data from file.

Write in a file with FileOutputStream


Note :- Java mai file handling ke liye fileInputStream class aur fileOutputStream class use hoti h.

Slash:-

In Microsoft Windows operating systems, backslashes are used in file paths to separate
directories. However, for a relative path, Windows uses forward slashes.

In Unix-based systems, \ is an escape character. This means that \ tells the parser that this is a space
and not the end of the statement. On Unix systems, / is the directory separator.

In text, a slash is used to separate alternatives (good/evil) and to separate lines of poetry. When used
for poetry, there is a space before and after the slash.

------------------------------------------------------V5--------------------------------------------------------------
------------------------------------------------------V6--------------------------------------------------------------

ByteArrayInputStream:-

ByteArrayOutputStream:- Create a new byte array output stream. The buffer capacity is initially 32

bytes , though it size increase if necessary.

------------------------------------------------------V7--------------------------------------------------------------

SequenceInputStream :- Sequencially read data from 2 files.

Note:- there is no SequenceOutputStream is available because we didn’t write operation in two


file concurrently.
Example:-
DataInputStream(stream s1):- Kisi bhi Primitive data ki form mai file ko read karane ki facility
deta h

DataOutputStream(stream s1):- Kisi bhi Primitive data ki form mai file mai write karane ki
facility deta h

--------------Important See Again---------------V8--------------------------------------------------------------

• System class ke pass operating system/ Machine ki saari information hoti h. Keyboard aur
Console(Monitor) tak pahuchne ki information
• I/O class ke pass Read and Write ki permission hoti h.

• Server is a program that run on a machine.

------------See Again------------------------------V9--------------------------------------------------------------

System.out.println:- System is a class , out is static final reference variable of System class ,
println is the non-static method of printstream class.

System.in :-

Java Pattern Programs


Link ---- https://www.geeksforgeeks.org/java-pattern-programs/
------------------------------------------------------V10-------------------------------------------------------------

• System.out.print() :- Use for print any message on screen.

• System.err.print() :- Use for print any message (specially error message) on screen.

• System.setOut(_file reference_)

• System.setErr(_file reference_)

Both are used to redirect the console output into a file.

------------------------------------------------------V11-------------------------------------------------------------

Input in Java

for Import - [ import java.io.Scanner ]

• to get input by user from console we use --- System.in


• Different-2 input device se data get karne ke liye InputStream mai different classes aur
unke different methods hote h.

• Ham kisi bhi class or ByteStream ke kisi bhi class ke Object mai System.in likh sakte hai.
Jiske parameter mai InputStream ata ho

Question:- User se input lene ke kitne tarike ho skte h?

Answer:- User se input kitne bhi tarike se lo lekin System.in ka use to krna hi padega chahe
Scanner , DataInputStream, FileInputStream , BufferInputStream etc

• check java.io.console

------------------------------------------------------V12-------------------------------------------------------------

Java File class is Java’s representation of a file or directory pathname. Because file and directory
names have different formats on different platforms, a simple string is not adequate to name them.
Java File class contains several methods for working with the pathname, deleting and renaming
files, creating new directories, listing the contents of a directory, and determining several common
attributes of files and directories.

•It is an abstract representation of files and directory pathnames.


•A pathname, whether abstract or in string form can be either absolute or relative. The parent of
an abstract pathname may be obtained by invoking the getParent() method of this class.
•First of all, we should create the File class object by passing the filename or directory name to
it. A file system may implement restrictions to certain operations on the actual file-system
object, such as reading, writing, and executing. These restrictions are collectively known as
access permissions.
•Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.

How to Create a File Object?


A File object is created by passing in a string that represents the name of a file, a String, or another
File object. For example,

File a = new File("/usr/local/bin/geeks");

This defines an abstract file name for the geeks file in the directory /usr/local/bin. This is an
absolute abstract file name.

Fields in File Class in Java


Ty
Field Description
pe

Stri the character or string used to separate individual paths in a list of


pathSeperator
ng file system paths.

pathSeperatorCh Cha the character used to separate individual paths in a list of file
ar r system paths.

Stri
separator default name separator character represented as a string.
ng
Ty
Field Description
pe

Cha
separatorChar default name separator character.
r

Constructors of Java File Class


•File(File parent, String child): Creates a new File instance from a parent abstract pathname
and a child pathname string.
•File(String pathname): Creates a new File instance by converting the given pathname string
into an abstract pathname.
•File(String parent, String child): Creates a new File instance from a parent pathname string
and a child pathname string.
•File(URI uri): Creates a new File instance by converting the given file: URI into an abstract
pathname.

Methods of File Class in Java


S. Return
Method Description
No. Type

Tests whether the application can execute


1. canExecute() boolean
the file denoted by this abstract pathname.

Tests whether the application can read the


2. canRead() boolean
file denoted by this abstract pathname.

Tests whether the application can modify


3. canWrite() boolean
the file denoted by this abstract pathname.

Compares two abstract pathnames


4. compareTo(File pathname) int
lexicographically.

Atomically creates a new, empty file named


5. createNewFile() boolean
by this abstract pathname.

createTempFile(String prefix, Creates an empty file in the default


6. File
String suffix) temporary-file directory.

Deletes the file or directory denoted by this


7. delete() boolean
abstract pathname.

Tests this abstract pathname for equality


8. equals(Object obj) boolean
with the given object.
S. Return
Method Description
No. Type

Tests whether the file or directory denoted


9. exists() boolean
by this abstract pathname exists.

10 Returns the absolute pathname string of


getAbsolutePath() String
. this abstract pathname.

11 Returns an array of strings naming the files


list() String[]
. and directories in the directory.

12 Returns the number of unallocated bytes in


getFreeSpace() long
. the partition.

13 Returns the name of the file or directory


getName() String
. denoted by this abstract pathname.

14 Returns the pathname string of this abstract


getParent() String
. pathname’s parent.

15 Returns the abstract pathname of this


getParentFile() File
. abstract pathname’s parent.

16 Converts this abstract pathname into a


getPath() String
. pathname string.

17 Marks the file or directory named so that


setReadOnly() boolean
. only read operations are allowed.

18 Tests whether the file denoted by this


isDirectory() boolean
. pathname is a directory.

19 Tests whether the file denoted by this


isFile() boolean
. abstract pathname is a normal file.

20 Tests whether the file named by this abstract


isHidden() boolean
. pathname is a hidden file.

21 Returns the length of the file denoted by


length() long
. this abstract pathname.

22 Returns an array of abstract pathnames


listFiles() File[]
. denoting the files in the directory.
S. Return
Method Description
No. Type

23 Creates the directory named by this abstract


mkdir() boolean
. pathname.

24 Renames the file denoted by this abstract


renameTo(File dest) boolean
. pathname.

25 setExecutable(boolean A convenience method to set the owner’s


boolean
. executable) execute permission.

26 setReadable(boolean A convenience method to set the owner’s


boolean
. readable) read permission.

setReadable(boolean
27 Sets the owner’s or everybody’s read
readable, boolean boolean
. permission.
ownerOnly)

28 setWritable(boolean A convenience method to set the owner’s


boolean
. writable) write permission.

29 Returns the pathname string of this abstract


toString() String
. pathname.

30 Constructs a file URI that represents this


toURI() URI
. abstract pathname.

____________________________________V13________________________________________

Serialization
Q-> What is Serialization and why we need it ?

A--> Serialization process is required to converts the object into the stream . So that we can traverse
it on the network and treverse our object from one place to another place.

• Object to Stream conversion – Serialization

• Stream to Object conversion – Deserialization

Q--> Why we use Serialization?


A--> Serialization is required to treverse the object over the network.

Q--> Why we are converting Object into the Stream?

A--> We wanted to travel the object over the network.

Q--> Why we use Serialization ?

A--> Whenever we are travelling our Object from one place to other place in this situation there
may chances to Object having the data can be loss. Those data can’t be loss So we use Serialization.

Note:- Persistency means State ko manage krna

Note:- Object ki state == Object ka data

Uses of Serialization

• Object ko Network par travel karwane ke liye.

• Object ki Persistency ko maitain krne ki liye

Q--> What is Marker interface?

A --> Marker Interface waha interface hote h jinke andr koi method nahi hota. Aur Serializable ek
Marker interface h.

String class/Type implicitly serializable , Comparable<String>, Charsequence ko implement krti h.

Q--> What is Transient and what is there usage?

A--> Transient is a keyword and yeh esa keywords h jo kisi bhi data/variable ke aage lagane se uss
particular data ka Serialization process mai hissa nhi leta. Transient ka data network pr loss ho skta
h.

Implementation of Serialization.
____________________________________V14________________________________________

PipedInputStream and PipedOutputStream classes

The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of the
PipedOutputStream class.

• Do threads mai simultaneously data read and write kr skte h.

• PipedOutputStream.connect(PipeInputStream)

import java.io.*;

class PipedWR{
public static void main(String args[])throws Exception{
final PipedOutputStream pout=new PipedOutputStream();
final PipedInputStream pin=new PipedInputStream();

pout.connect(pin);//connecting the streams


//creating one thread t1 which writes the data
Thread t1=new Thread(){
public void run(){
for(int i=65;i<=90;i++){
try{
pout.write(i);
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
//creating another thread t2 which reads the data
Thread t2=new Thread(){
public void run(){
try{
for(int i=65;i<=90;i++)
System.out.println(pin.read());
}catch(Exception e){}
}
};
//starting both threads
t1.start();
t2.start();
}}

________Socket Programming___________V1_________________________________________

Networking:-Computer networking refers to interconnected computing devices that can exchange


data and share resources with each other. These networked devices use a system of rules, called
communications protocols, to transmit information over physical or wireless technologies.
Network Topology:-
Key Component of Network:-

Types of Network:-

• LAN (Local Area Network):- yeh ek building ya office tak limited hota h.

• MAN (Metropolitan Area Network) :- yeh ek town/city yak limited hota h.

• WAN (Wide Area Netwok):- ek puri duniya tak limited h. Like – Internet
____________________________________V2_________________________________________

Network Stablish krne ke liye kis kis chiz ki jarurat padti h.

• Hardware

• Communication media

-wired

-wireless

• Software :- ham software level pr networking krenge

Network ke liye software banana ya network mai software banana hota h Socket programming aur
wah software ya program Socket program kehlata h.

Q-->What is Socket Programming?

A-->Socket programming is a process in which we share data from one place to another place.

Thing we know before doing Socket Programming

• IP Address:- is a unique address of a device on internet. To identify that device over the
network or internet.

• To know IP address detail type in CMD – ipconfig, ipconfig /all

Types of Addresses on internet

1. IPV4

2. IPV6
Types of IP Addresse

• Static IP:- Jo change na ho fixed , jo ham device ko khud assign krte h

• Dynamic IP:- jo change hota rahe, jo ISP hame assign kre


• PORT Number:- Port number ke through hi data application to application share hoti h.

Or A port number is a numeric value that identifies a specific process to which a network
message should be forwarded when it arrives at a server.
IP Address PORT Number/Address
IP Address machine ka hota h PORT number Application software/program ke
hote h
Port number ek unique number hota h jo kisi
machine mai kisi Application ko identify krta h
Ham program ya application ko PORT assign
kra skte h.
Google aur Facebook ke PORT number hote h
Har Application ka apna ek unique
Address/Number hota h jisse wah identify hota
h. Usse PORT number kehte h.

• Protocol

• Socket

etc

________________________________________V3_____________________________________

Protocol :- In networking, a protocol is a set of rules for formatting and processing data. Network
protocols are like a common language for computers. The computers within a network may use
vastly different software and hardware; however, the use of protocols enables them to communicate
with each other regardless.

Or Protocol/Standard is the rule and regulation for the communication.


TCP vs UDP :-

• TCP is for safe communication and slow

• UDP is for unsafe communication and fast

Socket is a buffer whose one object is resposible to share the message form one end to another end.

• Socket class and Server Socket class follow TCP/IP protocol. Socket representing Client
side and Server Socket representing Server side.

• DataGram packet and DataGram socket follow UDP protocol.


Java Socket Programming

Java Socket programming is used for communication between the applications running on different
JRE.
Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, an
2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are being
used: Socket and ServerSocket. The Socket class is used to communicate client and server. Through
this class, we can read and write message. The ServerSocket class is used at server-side. The
accept() method of ServerSocket class blocks the console until the client is connected. After the
successful connection of client, it returns the instance of Socket at server-side.

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be
used to create a socket.

Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream returns the OutputStream attached with this


getOutputStream() socket.
3) public synchronized void close() closes this socket

Creating Client: To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port number. Here, we are
using "localhost" because our server is running on same system.

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Important methods
Method Description
returns the socket and establish a connection between server
1) public Socket accept()
and client.

2) public synchronized void


closes the server socket.
close()

Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we are
using 6666 port number for the communication between the client and server. You may also choose
any other port number. The accept() method waits for the client. If clients connects with the given
port number, it returns an instance of Socket.

_______________________-_______________V4_________________________________-_____

What Is a BAT File?


A file with the .BAT file extension is a Windows batch file. It's a plain text file that contains
various commands used for repetitive tasks or to run groups of scripts one after another.
Software of all types use BAT files for various purposes—for example, to copy or delete files, run
applications, and shut down processes.
They're also called scripts, batch programs, command files, and shell scripts, and may instead use
the .CMD extension.

Working with BAT files can be very dangerous to not only your personal files but also important
system files. Take extreme caution before opening one.

How to Open a .BAT File


Even though the BAT extension immediately makes Windows recognize such a file as executable,
they are still composed entirely of text commands. This means any text editor, such as Notepad,
included in all versions of Windows, can open one for editing.

To open the BAT file in Notepad, right-click it and choose Show more options > Edit from the
menu (or just Edit in some Windows versions). You might find it helpful to use more advanced text
editors that support syntax highlighting when editing a BAT file.

Opening it in a text editor will display the code that makes up the file. For example, this is the text
inside one used to empty the clipboard:
cmd /c "echo off | clip"

Here's another example of a BAT file that uses the ping command to see if the computer can reach
a router with this particular IP address:

ping 192.168.1.1
pause

Again, as an executable file extension, take great care when opening BAT files you have received
via email, downloaded from websites you're not familiar with, or even created yourself.

Still Can't Open It?


If the file doesn't display readable text in a text editor, then you're not dealing with a BAT file.
Check the file extension to make sure you aren't mixing it up with another file that just appears to
be similar because of a similar file extension. BAK files and BAR files (Age of Empires 3 data files)
are some examples.

How to Use a BAT File


Using a BAT file in Windows is as simple as double-clicking or double-tapping it. You don't need to
download any special program or tool.

To use the first example from above, entering that text into a text file with a text editor and then
saving the file with the .BAT extension will make it an executable that you can open to immediately
erase anything saved to the clipboard.

The second example will ping that IP address; the pause command keeps the Command
Prompt window open when the process is finished so you can see the results.

How to Create a Batch File in Windows 10

How to Convert a .BAT File


As shown, the code of a BAT file isn't hidden in any way, which means it's very easy to edit.
Because certain instructions in one (such as the del command) can wreak havoc on your data,
converting the BAT file to a format like EXE to make it more like an application file might be wise.
You can convert BAT to EXE using a few command line tools. See How-To Geek for directions on
how to do that.

•Windows' built-in IExpress tool provides another way to build an EXE file from a BAT file.
Open it from the Run box with iexpress.
•Although the free version is only a trial, EXE to MSI Converter Pro can convert the
resulting EXE file to an MSI (Windows Installer Package) file.
•You can use the free NSSM command-line tool if you want to run a BAT file as a Windows
Service.
•PowerShell Scriptomatic can help you convert the code in a BAT file to a PowerShell
script.

Instead of searching for a BAT to SH (bash shell script) converter to use the commands in programs
such as Bourne Shell and Korn Shell, try just rewriting the script using the Bash language. The
structure of the two formats is rather different because the files are used in different operating
systems. There is a Stack Overflow thread and this Unix Shell Scripting tutorial for some
information that might help you translate the commands manually.

Usually, you can't change a file extension (like BAT) to one that your computer recognizes and
expect the newly renamed file to be usable. An actual file format conversion using one of the
methods described above must take place in most cases. Given that a BAT file is just a text file with
the .BAT extension, however, you can rename it to .TXT to open it with a text editor. Remember
that doing a BAT-to-TXT conversion will prevent the batch file from executing its commands.

How to Save a .BAT File as a .TXT File


Instead of manually changing the file extension from BAT to TXT, you also can open the batch file
in Notepad for editing and then save it to a new file, choosing .TXT as the file extension before
saving instead of .BAT.

See More :- https://www.lifewire.com/bat-file-2619796

-_____________See Again_________________V5_______________________________________
Creating 3 Client and one Server

___________________See Again____________V6______________________________________

_______________________________________V7______________________________________

InetAddress class:- InetAddress class is a inbuild class in java whose one object is responsible to
representing the IP Address of any machine.
Commonly used methods of InetAddress class:

• public static InetAddress getByName(String host) throws UnknownHostException :-

It returns the IP of the given host.

• public static InetAddress getLocalHost() throws UnknownHostException :-

It returns the LocalHost IP and name.

• public String getHostName():-

It returns the host name of the IP address.

• public String getHostAddress():-

It returns the IP address in string format.

URL class:

The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It points to a
resource on the World Wide Web.

A URL contains many informations:

• Protocol: In this case, http is the protocol.

• Server name or IP Address :

• PORT Number: It is an optional attribute.

Commonly used methods of URL class:

• public String getProtocol():- it returns the protocol of the URL.

• public String getHost():- It returns the host name of the URL.

• public String getPort():- It returns the port Number of the URL.


• public String getFile():- It returns the file name of the

URL classes in java:-

• class URL connection:- kisi URL se connection banane ke liye

• class URL:- URL ko represent krne ke liye.

UDP based classes:-

• DatagramPacket

• DatagramSocket

____________GUI Programming_1________V8________________________________________

CUI(Character User Interface):-

GUI(Graphical User Interface):-

Difference between CUI and GUI :-

GUI CUI

Types of Logical Programming in Project/Software/Application making:

• PL(Presentation Logic)--> Used for User Interface/FrontEnd Programming

• BL(Business Logic)-->Used for Backend Programming

• DL(DataBase Logic)-->Used for Database Programming

For GUI Programming in Java we have these APIs(Application Programming Interface).

• AWT(Abstract Windowing Toolkit)

• Swing

• JAVAFX
In Java the APIs are in the form of:

• Class

• Package

• Interface

AWT class Hierarchy

• Frame:-
• Dialog:-

Difference between Association and Inheritance

Note:-Button class ka Object , button banata h, Frame class ka Object , frame banata h and so on.

GUI Program:-

________________2__________________V9__________________________________________

Program of GUI Application:-

import java.awt.Frame;
import java.awt.Button;
import java.awt.Label;
import java.awt.TextField;
import java.awt.FlowLayout;
import java.awt.Color;

class GuiApp
{
Frame f;
Button b1,b2;
Label l1,l2,l3;
TextField tf1,tf2,tf3;

GuiApp(String title)
{
f=new Frame(title);
f.setVisible(true);
f.setSize(400,400);
f.setLocation(200,200);
f.setBackground(Color.YELLOW);

b1=new Button("Add");
b2=new Button("Sub");
l1=new Label("Enter First Number");
l2=new Label("Enter Second Number");
l3=new Label("Result");
tf1=new TextField(10);
tf2=new TextField(10);
tf3=new TextField(10);

f.setLayout(new FlowLayout());

f.add(l1);
f.add(tf1);
f.add(l2);
f.add(tf2);
f.add(l3);
f.add(tf3);
f.add(b1);
f.add(b2);
}

public static void main(String args[])


{
GuiApp g=new GuiApp("GuiApp");
}
}

OUTPUT
________________3__________________V10_________________________________________

Making Client and Server

____________4______________________V11_________________________________________

What is Event:-

• kisi Object ka state change krna.

• Change the state of an Object is called Event.

Eventhandling:- The process of handling an event is called Eventhanding.


Eventhandling krne ke liye java mai Event Daligate Model diya gya h.

Event Daligate Model mai kisi Event ke hone ke liye 3 chize ka hona jaruri h.

1. Source :- jaha ya jispr Event hona h.---- Component

2. Listener :- Event ko sunne wala ---- Interface

3. Registration :- jiska registration hoga wahi listen karega --- Method

Event-Class Listener-Interface callback-method


ActionEvent ActionListner Void actionPerformed()
MouseEvent MouseListner
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WIndowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Registration Method--addTypeOfListner(passing the object of Listner class)

addActionListener();

addMouseListener();

addActionLIstner();

____________5______________________V12_________________________________________

Listener class 4 tariko se banta h :-

• same class Listener (inner)

• other class listener (outer)

• annonamous class listener

• adapter class listener


Logic:-

• For-round Event (uper-uper ka code) :- is done by programmer itself

• Background Event (piche ka code) :- is done by Application itself

Note:- this means current class ka Object

Note:- callback-method --> ham call krte h button ko aur response deta h ye method

__________6_________See Again______V13__________________________________________

same class Listener (inner)

__________7_________See Again______V14__________________________________________

other class listener (outer)

annonamous class listener

_________8________________________V15__________________________________________

_________9________________________V16__________________________________________
Calculater

________10_______________________V17___________________________________________

AWT Graphics

________11_______________________V18___________________________________________

GUI Application ko Java ke andar banane ke 2 tarike h

• AWT

• Swing

Hierarchy of Swing Classes


The class hierarchy of Swing's top-level containers (JFrame, JDialog, JApplet) are as
follows. These top-level Swing containers are heavyweight, that rely on the underlying windowing
subsystem of the native platform.

The class hierarchy of Swing's JComponents is as follows. JComponent and its descendants are
lightweight components.
Java AWT vs Java Swing

__________12____________________V19____________________________________________
Java Swing | Look and Feel
Swing is GUI Widget Toolkit for Java. It is an API for providing Graphical User Interface to Java
Programs. Unlike AWT, Swing components are written in Java and therefore are platform-
independent. Swing provides platform specific Look and Feel and also an option for pluggable
Look and Feel, allowing application to have Look and Feel independent of underlying platform.
Initially there were very few options for colors and other settings in Java Swing, that made the
entire application look boring and monotonous. With the growth in Java framework, new changes
were introduced to make the UI better and thus giving developer opportunity to enhance the look of
a Java Swing Application.

“Look” refers to the appearance of GUI widgets and “feel” refers to the way the widgets
behave.
Sun’s JRE provides the following L&Fs:

1.CrossPlatformLookAndFeel: this is the “Java L&F” also known as “Metal” that looks the
same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the default.
2.SystemLookAndFeel: here, the application uses the L&F that is default to the system it is
running on. The System L&F is determined at runtime, where the application asks the system to
return the name of the appropriate L&F.
For Linux and Solaris, the System L&Fs are “GTK+” if GTK+ 2.2 or later is installed, “Motif”
otherwise. For Windows, the System L&F is “Windows”.
3.Synth: the basis for creating your own look and feel with an XML file.
4.Multiplexing: a way to have the UI methods delegate to a number of different look and feel
implementations at the same time.
We can use UIManager to load the L&F class directly from classpath. For which the code goes like
this:
UIManager.setLookAndFeel("fully qualified name of look and feel");

1. CrossPlatformLookAndFeel:
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAnd
Feel");
2. MotifLookAndFeel: Just change Line number 14 and 79 to:
Line 14: f=new JFrame("Motif Look and Feel");
Line 79:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

3. SystemLookAndFeel: Change Line number 14 and 79 to:


Line 14: f=new JFrame("System Look and Feel");
Line 79:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

4. WindowsClassicLookAndFeel: Change Line number 14 and 79 to:


Line 14: f=new JFrame("WindowsClassic Look and Feel");
Line 79:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
_______13____________________________V20________________________________________

_______14___________________V21___________________________

NetBeans

______15_______________________V22________________________________

How to create Executable jar file

• By NotePad

• By Eclipse

Dialog Box:-

Java JOptionPane

The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information or get
input from the user. The JOptionPane class inherits JComponent class.

JOptionPane class declaration


1. public class JOptionPane extends JComponent implements Accessible

Common Constructors of JOptionPane class


Constructor Description
JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object It is used to create an instance of JOptionPane to display a


message) message.

JOptionPane(Object It is used to create an instance of JOptionPane to display a


message, int messageType message with specified message type and default options.

Common Methods of JOptionPane class


Methods Description
It is used to create and return a new parentless
JDialog createDialog(String title)
JDialog with the specified title.

static void showMessageDialog(Component It is used to create an information-message


parentComponent, Object message) dialog titled "Message".

static void showMessageDialog(Component


It is used to create a message dialog with
parentComponent, Object message, String title,
given title and messageType.
int messageType)

static int showConfirmDialog(Component It is used to create a dialog with the options


parentComponent, Object message) Yes, No and Cancel; with the title, Select an
Option.

It is used to show a question-message dialog


static String showInputDialog(Component
requesting input from the user parented to
parentComponent, Object message)
parentComponent.

It is used to set the input value that was


void setInputValue(Object newValue)
selected or input by the user.

import javax.swing.*;

class JOptionDemo
{
public static void main(String args[])
{
String str=JOptionPane.showInputDialog(null, "Enter ur Name");
if(str!=null)
{
JOptionPane.showMessageDialog(null, "Ur Name is:"+str);
int i=JOptionPane.showConfirmDialog(null,"Swing is better
than Awt");

if(i==JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "u r right...");
}
else if(i==JOptionPane.NO_OPTION)
{
JOptionPane.showMessageDialog(null," u r wrong, take
retirement");
}
else
{
JOptionPane.showMessageDialog(null,"u r goof for
nothing , leave this planet");
}
}
else
{
JOptionPane.showMessageDialog(null, "You pressed cancel
button");
}
}
}

For more link :- https://www.javatpoint.com/java-joptionpane

Swing all classes:-


______16_________________________V23___________________________________________

Make Notepad :- https://www.javatpoint.com/notepad

______!7_________________________V24____________________________________________

______18_________________________V25___________________________________________

_________________________________V1____________________________________________

Applet:- is a java progtam . It is a java component which can be run or stored on a server and
transmitted over the web is a kind of internet program it execute from server to browser .

A Java application that is integrated into a webpage is called an applet. It functions as a front-end
and is run within the web computer. It makes a page more interactive and dynamic by operating
inside the web browser. Applets are hosted on web servers and inserted into HTML pages via the
OBJECT or APPLET tags.

Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.

• Secured

• It can be executed by browsers running under many plateforms, including Linux,


Windows, Mac Os etc.

Drawback of Applet
• Plugin is required at client browser to execute applet.
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.

Lifecycle of Java Applet


1.Applet is initialized.

2.Applet is started.

3.Applet is painted.

4.Applet is stopped.

5.Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.

public void init(): is used to initialized the Applet. It is invoked only once.

1.public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.

2.public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser
is minimized.

3.public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1.public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.
How to run an Applet?
There are two ways to run an applet

1.By html file.

2.By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

Note: class must be public because its object is created by Java Plugin software that
resides on the browser.

myapplet.html

_____________________________________v2_________________________________________
________Reflection API__________V1_______________________________________________

Reflection (pratibimb) API :-

• Kisi class ko run time pr analyse krne ki facility deta h.

• Java mai jo kuch ham nahi kr skte wo sab ham Reflection API ke through kr skte h.

• Reflection API ka use FrontEnd mai kam aur BackEnd mai jada hota h.

• Every class is the instance of class Class

• The Reflection copy of any class is nothing but class Class ka Object

Kisi class ki Duplicate image/copy 3 tariko se nikaal skte h.

• Dynamically

• Statically

• Direct hold krke

Java Reflection API


Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and
change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.

Where it is used
The Reflection API is mainly used in:

• IDE (Integrated Development Environment) e.g., Eclipse, MyEclipse, NetBeans etc.

• Debugger

• Test Tools etc.

Commonly used methods of Class class:


Method Description
1) public String getName() returns the class name

2) public static Class forName(String className)throws loads the class and returns
ClassNotFoundException the reference of Class class.

3) public Object newInstance()throws


creates new instance.
InstantiationException,IllegalAccessException

4) public boolean isInterface() checks if it is interface.

5) public boolean isArray() checks if it is array.

6) public boolean isPrimitive() checks if it is primitive.

returns the superclass class


7) public Class getSuperclass()
reference.

returns the total number of


8) public Field[] getDeclaredFields()throws SecurityException
fields of this class.

9) public Method[] getDeclaredMethods()throws returns the total number of


SecurityException methods of this class.

10) public Constructor[] getDeclaredConstructors()throws returns the total number of


SecurityException constructors of this class.

11) public Method getDeclaredMethod(String name,Class[]


returns the method class
parameterTypes)throws
instance.
NoSuchMethodException,SecurityException

How to get the object of Class class?


There are 3 ways to get the instance of Class class. They are as follows:

• forName() method of Class class


• getClass() method of Object class

• the .class syntax

1) forName() method of Class class


• is used to load the class dynamically.

• returns the instance of Class class.

• It should be used if you know the fully qualified name of class.This cannot be used for
primitive types.
Let's see the simple example of forName() method.
FileName: Test.java

Output:
Simple

2) getClass() method of Object class


It returns the instance of Class class. It should be used if you know the type. Moreover, it can be
used with primitives.
FileName: Test.java
Output:
Simple

3) The .class syntax


If a type is available, but there is no instance, then it is possible to obtain a Class by appending
".class" to the name of the type. It can be used for primitive data types also.
FileName: Test.java

Output:
boolean
Test
Determining the class object
The following methods of Class class are used to determine the class object:
1) public boolean isInterface(): determines if the specified Class object represents an interface
type.
2) public boolean isArray(): determines if this Class object represents an array class.
3) public boolean isPrimitive(): determines if the specified Class object represents a primitive
type.
Let's see the simple example of reflection API to determine the object type.
FileName: Test.java

Output:
false
true

Pros and Cons of Reflection

Java reflection should always be used with caution. While the reflection provides a
lot of advantages, it has some disadvantages too. Let's discuss the advantages first.
Pros: Inspection of interfaces, classes, methods, and fields during runtime is possible using
reflection, even without using their names during the compile time. It is also possible to call
methods, instantiate a clear or to set the value of fields using reflection. It helps in the creation of
Visual Development Environments and class browsers which provides aid to the developers to write
the correct code.
Cons: Using reflection, one can break the principles of encapsulation. It is possible to access the
private methods and fields of a class using reflection. Thus, reflection may leak important data to
the outside world, which is dangerous. For example, if one access the private members of a class
and sets null value to it, then the other user of the same class can get the NullReferenceException,
and this behaviour is not expected.
Another demerit is the overhead in performance. Since the types in reflection are resolved
dynamically, JVM (Java Virtual Machine) optimization cannot take place. Therefore, the operations
performed by reflections are usually slow.

Conclusion
Because of the above-mentioned cons, it is generally advisable to avoid using reflection. It is an
advanced feature that should only be used by programmers or developers who have a good
knowledge of the basics of the language. Always remember! Whenever reflection is used, the
security of the application is compromised.

Next Topics of Reflection API Tutorial


newInstance() method

Understanding javap tool

creating javap tool

creating appletviewer tool

Call private method from another class

______________________________V2_______________________________________________

______________________________V3_______________________________________________

_______________________________V1______________________________________________

Nested class Or Inner class:-


Structure:-

Static Nested Class:-

1. It is treated as a static data member as a class

2. it can have both static and non-static members.

3. It can access only static member of its inclosing(outer) class.

4. The object of this class can be created without creating its inclosing class object.
5. It can also Inherit an other class.

6. It can also implements an interface.

Note:- since it is treated as a static data member of a class so those keyword that can be applied on

data member.

Syntax to create the object:-

OuterClassName.NestedClassName referenceOfNestedClass=new

outerclassName.nestedclassName(args if any)

Non-Static Nested Class:-

1. it is treated as a non-static data member of a class.

2. It can have only non-static member.

3. It can access all the members (static as well as non-static) of its inclosing class.

4. The object of this class always created with the help of its inclosing class object.

5. It can inherit other class.

Syntax to create the object of Non-Static class:-

OuterClassName refOfOuter=new OuterClassName(args if any)

OuterClassName.NestedClassName referenceOfInnerClass=ref of Outer.new InnerClass(args

if any);

_______________________________V2______________________________________________

You might also like