Core Java Notes
Core Java Notes
Core Java
• What is Java?
• History of Java
• Inside JVM
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.
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.
OOPs---the programming langauge which having all characteristics of oops is call object oriented programming language.
--Object
--Class
--Encapsulation
--Abstaction
--Inheritance
--Polymorphism
--Tight Coupling
--Loose Coupling
1.No Dependency
2.Loose Coupling
4. Reusability
5. Data hiding
3. Design (GUI,DataBase)
4. Coding
6.
--Waterfall Model
What is Software ?
$---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
` - program is a chain of steps or set of activities which is combine together in order to achieve a
specific task.
threads - subprocess
Low Level , (Machine lang , Assembly lang) -directly interact with hardware
What is Machine ?
FOLDER = Directory
We can create a java program by two ways :- with IDE (IDE --- Copiler + LIbrary + RunTime Enviroment + Editor) -- i.e.
eclipse, netbeans, myeclips
: - System variable
:- external command
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
Platfom Independent -- (compile ones run anywhere ) --if a language have capability to
-------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------
What is Micro-Controller?
-------------------------------------------------------------------------------------------------------------------
2. platform indepandant
3. class base language
Translator
1. Assembler
2. Compiler
3. Interpreter
-------------------------------------------------------------------------------------------------------------------
Flavours of Java
2.JRE - Java Runtime Enviroment ( JVM + Libraray ) --> JRE are dirrent for defferent
device or OS.
software program
combination
-------------------------------------------------------------------------------------------------------------------
-javac
-javap
-javah
-javadoc etc.
-------------------------------------------------------------------------------------------------------------------
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.
--Hardware (Micro-processor,Micro-controllers)
--Software + Hardware
Platform Independency
--Means program compile on one platform and can be executed on any platform
Compatibility
---------------------------------------------v20------------------------------------------------------------------
----------------------------------------------V21----------------------------------------------------------------
2. Mobile Development
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
· Literals ( Constant )
· 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:
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
8. char -->A data type that can hold unsigned 16-bit Unicode characters
13. double-->A data type that can hold 64-bit floating-point numbers
15. enum-->A Java keyword is used to declare an enumerated type. Enumerations extend the base class.
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
25. int-->A data type that can hold a 32-bit signed integer
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
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.
Note: ---The keywords const and goto are reserved, even they are not currently in use.
-----------------------------------------------V23---------------------------------------------------------------
Object ( Noun )- ->Any real world entity which having their physical , logical ,tengibal- Untangible existence is known as
Object.
· Identity --
Class --> Class is a logical chategorization of similar type of Objects and Class provides the
--------------------------------------------------V24------------------------------------------------------------
Identifier ( Name ):--> Identifier are those concepts which is used to identify the name of
program
---------------------------------------------------V25-----------------------------------------------------------
7. unique ......etc
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.
Variable--> variable is the name of memory location which refer the value of a specific address.
4. No Global variable
What is DataType?
DataType are those concepts which explain the following information about the
variable.
Types of Dataatype?
-byte-(1byte)
-short-(2byte)
-int-(4byte)
-long-(8byte)
-float-(4byte)
-double-(8byte)
-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
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.
Type of Literals
--Primitive Literal
--Non Premitive Literal
-----------------------------------------------------------v29----------------------------------------------------
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.
Method Termonogy :-
· method declaration
· method defination
· method calling
· method parameter
· method argument
Return Type in Method:-
· void
· non-primitive type
Type of Methods:-
-Parameterise
--with return ( primitive & non-primitive data type )-in method body end
return
-Non Parameterise
--with return ( primitive & non-primitive data type )-in method body end
return
· Pre-define Method
-Parameterise
-Non Parameterise
-----------------------------------------------------------------v30----------------------------------------------
Types of Logic :-
· Presentation Logic
--------------------------------------------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-------------------------------------------------------------------
• 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
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
3. PC Register -
-----------------------------------------------------------------V39---------------------------------------------------
1. Static ( Compile time ) memory allocation-- size, use ,identification are decided on Compile time
2. Dynamic ( Runtime ) memory allocation –size, use, identification are allocated on Runtime
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--------------------------------------------------
What is Constructor?
Its is a special type of method which having following features from a normal method.
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.
-----------------------------------------------------------V41-------------------------------------------------------------------
------------------------------------------------------------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.
-------------------------------------------------------------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.
-Jab alag alag object pr alag alag data assign krna ho.
-------------------------------------------------------------------V46-----------------------------------------------------------
------------------------------------------------------------------V47------------------------------------------------------------
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------------------------------------------------
---------------------------------------------------------------------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.
init-Block:-This is anonymous block used to initialized the data before object creation and must be
Syntax:-
Features:-
1. It is object dependent, means object criterion is necessary to execute the init block.
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
1. Class
2. Constructor
Wo data jo har Object mai comman hoga usse Static banayenge taki us data ki class area mai memory mile
instance means copy
-----------------------------------------------------------------------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:-
Rule:-NSDM and NSMF can not directly access in side static context.( Static method or Staic block)
Rule:- NSDM and NSMF can not directly access in side static context (static method or static block )
-----------------------------------------------------------------V53-------------------------------------------------------------
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.
JVM Architecture
static Block:-
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-------------------------------------------------------
-----------------------------------------------------------V58-------------------------------------------------------
CommandLine Argument:-
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.
-----------------------------------------------------------------V60-------------------------------------------------
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.
----------------------------------------------------------------V62---------------------------------------------------
Use of “this” :-
3. “this” keyword is also used incase of method chaining. Calling multiple method on single
object.
5. We can call any static or non static both method via this.
Method Chaining:- Method chaining is a process of calling a multiple method on a single object.
---------------------------------------------------------V62---------------------------------------------------------
---------------------------------------------------------V63---------------------------------------------------------
----------------------------------------------------------V64---------------------------------------------------------
----------------------------------------------------------V65---------------------------------------------------------
-----------------------------------------------------------V66--------------------------------------------------------
----------------------------------------------------interface-------------------------------11-11-23---------------
Multiple Inheritance:-
We can achieve multiple inheritance through interfaces because interface contains only
abstract method, which implementation is provided by the sub classes.
------------------------------------------------------------------------------------------------------------------------
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------------------------------------------------------
Advantages of Inheritance
1. Reusability
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:-
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.
-------------------------------------------------------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 is used to call the immediate patent data not parent of parent.
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----------------------------------------------------------------
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.
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
Topic we studied
Data Shadowing
Data Hiding
Method Overloading
Method Overriding
Constructor Overloading
Method Hiding
---------------------------------------------------------V74---------------------------------------------------------
Ans3. Yes.
Ans4. Yes.
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.
1.2. During combination compiler create default constructor if we are explicitly providing any
constructor in the program.
1.6. Create the static block to initialize all the static data.
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.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.
It is the process of storing class specific information (D.M , M.F, Constructor etc) into memory.
Class Loaders:- They are software which is responsible to performed class loading process.
--------------------------------------------------------V78---------------------------------------------------------
-------------------------------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.
class Class
1) Static class loading:- In case of static loading compiler have already knowledge about
loaded 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” is an identifier.
---------------------------------------------V82-----------------------------------------------------------
Wrapper Class:- Wrapper classes are those which provide us facility to convert any primitive data
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
The process of encapsulation is to achieve data hiding and class providing the implementation of
encapsulation.
JavaBean class provides 100% implementation of encapsulation. It is the general purpose reusable
piece of code.and this have the following characteristics:-
4) This class should not extends any specific class or implement any interface ( but must
implements serializable )
Before executing any child class constructor firstly execute its immediate parent class default
constructor implicitly not parameterized.
---------------------------------------------------------V85--------------------------------------------------------
----------------------------------------------------------V86--------------------------------------------------------
----------------------------------------------------------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.
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.
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.
Note:- In Java only non static ( virtual method ) method are dynamically and rest are bind statically.
Instanceof Operator
----------------------------------------------------V89---------------------------------------------------------
2. static method
3. private method
4. final method
5. constructors
6. initializer
----------------------------------------------------------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
Method overloading:- In a program if we have a same name with different signature this is
Note:- In method overloading accessRule and return type are not participating. It means in method
overloading only role parameter is applicable.
Argument:-
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------------------------------------------------------
abstraction
Final keyword:-
1. Final
2. Finally
3. Finalized
Final:-
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.
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.
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 )
Advantage:-
• Complexity reduction
Implementation of Abstraction:-
1. Abstraction class ke through – yeh 0 to 100% abstraction deta h
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.
2. constructor pr nhi
Rule:- If any child class extends the abstract class then child class have to override all the
------------------------------------------------V98-----------------------------------------------------------
Interface:-
• 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:-
Rules of Inheritance
--------------------------------------------------------V99--------------------------------------------------------
--------------------------------------------------------V100-------------------------------------------------------
--------------------------------------------------------V101-------------------------------------------------------
Operators:- are the symbol which are used to performed operation over operand.
Construct:-
-------------------------------------------------------V102--------------------------------------------------------
• Package
• access rule
• array
• string
• exception
• thread
• Collection
• JDBC SQL
• I18N
• 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:-
Type of packages
• Predefine
• User define
-----------------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
----------------------------------------------------------V106------------------------------------------------------
2D Array:-
----------------------------------------------------------V107------------------------------------------------------
----------------------------------------------------------V108------------------------------------------------------
String:-
• It is a sequence of character.
String Handling:- The process of performing over the string is called string handing.
• Length
• concat
• substring
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:-#
Immutable—unchangeable , Means in the ine object of string class we can not perform operation
like append , delete, sub string.
2. without new or by string literal:- in this approach when we are creating the string object via
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 of String :- string override the object class equals method.
• If content same the return true otherwise return false.
2. == operator
3. equalsIgnoreCase
4. CompareTo
5. CompareToIgnoreCase
------------See again-----------------------------------V11--------------------------------------------------------
static String format(Locale l, String format, It returns formatted string with given
4
Object... args) locale.
----------------------------------------------------------V12--------------------------------------------------------
---------See again-------------------------------------V113-------------------------------------------------------
• In the one object of String buffer we can do modification like, insert , delete ,append,
update.
Methods
Methods
java.lang..StringTokenizer
Methods Of StringTokenizer Class
Exception handling (Apwad – abnormal condition ):- Exception handling is a process of handling
runtime errors.
• try
• catch
• finally
• throw
• throws
• 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.
Alag-alag Exception aane pr alag-alag message dene ke liye multiple try-catch lagate h.
--------------See Again---------------------------V118-----------------------------------------------------------
------------------------------------------------------V119-----------------------------------------------------------
------------------------------------------------------V120-----------------------------------------------------------
--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.
--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-----------------------------------------------------------
------------------------------------------------------V122-----------------------------------------------------------
• 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.
------------------------------------------------------V123-----------------------------------------------------------
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.
Example:-
------------------------------------------------------V124-----------------------------------------------------------
------------------------------------------------------V125-----------------------------------------------------------
Thread:-
• it is a subprocess.
Note:-
------------------------------------------------------V126-----------------------------------------------------------
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.
Use of Thread:-
thread vs Process :-
Program vs Process vs Thread :-
Implementation of thread:-
-----------------V129--------------
-----------------V30----------------
------------------------------------------------------V131-----------------------------------------------------------
It is used to do an
2) void run()
action for a thread.
It returns a reference
to the currently
4) static Thread currentThread()
executing thread
object.
It changes the
7) void setPriority() priority of the
thread.
It returns the id of
10) long getId()
the thread.
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 destroy
16) void destroy() the thread group and
all of its subgroups.
It interrupts the
19) void interrupt()
thread.
It determines if the
currently running
23) void checkAccess() thread has
permission to
modify the thread.
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
Better Approach
Note :- Always use Implementation over Extends incase of Threads.
--------------See Again----------------------------V134-----------------------------------------------------------
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 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
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 DaemonThread
{
public static void main(String argd[])
{
MyThread t1=new MyThread("child");
t1.setDaemon(true);
t1.start();
Output
• Green Thread
------------------------------------------------------V136-----------------------------------------------------------
Synchronization-( Taal-Mel ) :-
• Synchronization Process aur Thread dono pr hota h ... ismai Thread ki baat ho ri h.
• Synchronize Thread is safe and slow. Asynchronize Thread is unsafe and fast
Synchronization Vs Concurrency :-
Mutual Exclusive :-
Example:-
import java.lang.Thread;
public MyThread1(Table t)
{
this.t=t;
}
public MyThread2(Table t)
{
this.t=t;
}
public MyThread3(Table t)
{
this.t=t;
}
class SynchronizeDemo
{
public static void main(String argd[])
{
Table t=new Table();
tt1.start();
tt2.start();
tt3.start();
}
}
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.
• 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.
1. Inconsistency problem
2. Interference problem
1. Mutual Exclusive:- ismai thread pr exact controlling nhi hoti like koi bhi thread kabhi bhi
chal skta h pr pura chalega.
method.
method.
• Static Synchronized
2. ITC:- ismai thread pr exact controlling hoti like kon sa thread kab chalega.
• Wait()
• notify()
• notifyAll()
-----------------------------------------------------V139------------------------------------------------------------
• 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.
• NotifyAll():- ye method sare suspended state methods ko firse running state mai la deti h.
-----------------------------------------------------V140------------------------------------------------------------
-------------------See Again----------------------V141------------------------------------------------------------
• sleep()
• 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.
Stream:-
• there is no any class in java whose name is Stream , Stream just a concept
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--------------------------------------------------------------
• 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.
This class contains methods to read bytes from the other input
5 FilterInputStream
streams, which are used as the primary source of data.
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
Concrete class:- Esi class jo kisi abstract class ko extends kare ya kisi interface ko implement kre
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
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
------------------------------------------------------V7--------------------------------------------------------------
DataOutputStream(stream s1):- Kisi bhi Primitive data ki form mai file mai write karane ki
facility deta h
• 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.
------------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 :-
• System.err.print() :- Use for print any message (specially error message) on screen.
• System.setOut(_file reference_)
• System.setErr(_file reference_)
------------------------------------------------------V11-------------------------------------------------------------
Input in Java
• 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
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.
This defines an abstract file name for the geeks file in the directory /usr/local/bin. This is an
absolute abstract file name.
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
setReadable(boolean
27 Sets the owner’s or everybody’s read
readable, boolean boolean
. permission.
ownerOnly)
____________________________________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.
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.
Uses of Serialization
A --> Marker Interface waha interface hote h jinke andr koi method nahi hota. Aur Serializable ek
Marker interface h.
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________________________________________
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.
• 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();
________Socket Programming___________V1_________________________________________
Types of Network:-
• LAN (Local Area Network):- yeh ek building ya office tak limited hota h.
• WAN (Wide Area Netwok):- ek puri duniya tak limited h. Like – Internet
____________________________________V2_________________________________________
• Hardware
• Communication media
-wired
-wireless
Network ke liye software banana ya network mai software banana hota h Socket programming aur
wah software ya program Socket program kehlata h.
A-->Socket programming is a process in which we share data from one place to another place.
• IP Address:- is a unique address of a device on internet. To identify that device over the
network or internet.
1. IPV4
2. IPV6
Types of IP Addresse
•
• 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.
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.
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.
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.
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_________________________________-_____
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.
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.
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.
•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.
-_____________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:
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.
• DatagramPacket
• DatagramSocket
____________GUI Programming_1________V8________________________________________
GUI CUI
• Swing
• JAVAFX
In Java the APIs are in the form of:
• Class
• Package
• Interface
• Frame:-
• Dialog:-
Note:-Button class ka Object , button banata h, Frame class ka Object , frame banata h and so on.
GUI Program:-
________________2__________________V9__________________________________________
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);
}
OUTPUT
________________3__________________V10_________________________________________
____________4______________________V11_________________________________________
What is Event:-
Event Daligate Model mai kisi Event ke hone ke liye 3 chize ka hona jaruri h.
addActionListener();
addMouseListener();
addActionLIstner();
____________5______________________V12_________________________________________
Note:- callback-method --> ham call krte h button ko aur response deta h ye method
__________6_________See Again______V13__________________________________________
__________7_________See Again______V14__________________________________________
_________8________________________V15__________________________________________
_________9________________________V16__________________________________________
Calculater
________10_______________________V17___________________________________________
AWT Graphics
________11_______________________V18___________________________________________
• AWT
• Swing
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");
_______14___________________V21___________________________
NetBeans
______15_______________________V22________________________________
• 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.
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");
}
}
}
______!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
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.
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.
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_______________________________________________
• 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.
• The Reflection copy of any class is nothing but class Class ka Object
• Dynamically
• Statically
Where it is used
The Reflection API is mainly used in:
• Debugger
2) public static Class forName(String className)throws loads the class and returns
ClassNotFoundException the reference 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
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
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.
______________________________V2_______________________________________________
______________________________V3_______________________________________________
_______________________________V1______________________________________________
4. The object of this class can be created without creating its inclosing class object.
5. It can also Inherit an other class.
Note:- since it is treated as a static data member of a class so those keyword that can be applied on
data member.
OuterClassName.NestedClassName referenceOfNestedClass=new
outerclassName.nestedclassName(args if any)
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.
if any);
_______________________________V2______________________________________________