0 ratings0% found this document useful (0 votes) 79 views197 pagesJava Notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Ains sing paradigm where
an object i¢ known ag tral
ing language.
kk ic considered ac the firct truly object-oriented
programming language.
2 OOP: (Object Oriented Programming System,
0 Object means a real word entity cuch ag pen, chair, table
etc. Object-Oriented Programming i¢ a methodology or
paradigm to design a program using claccec and objects. It2 state and behavior i¢ known ac an
“or example: chair, pen, table, keyboard, bike etc. It
physical and logical.
ail
o Clase
o Collection of objects i¢ called clase. It is a logical entity.
o Inheritanceoie. known as
e cuctomer
ape or rectangle ete.
thod overloading and method overriding to
olymorphicm. Another example can be to speak
amething €.9. cat speaks meaw, dog barks woof ete.
Abstraction
o Hiding internal detaile and chowing functionality ic known as
abstraction. For example: phone
a call we dont know the internal processing.
0 Th java, we uce abstract clase and interface to achieveoh. Java bean ig the
data members are
Ine of the key benefite of inheritance i¢ to minimize the
| amount of duplicate code in an application by sharing common
code amongst several subclaccec. Where equivalent code existe
in two related clacces, the hierarchy can usually be refactored
to move the common code up to a mutual superclass. This also
tende to recult in a better organization of code and cmaller,
simpler compilation unite.un decide to keep come data
by t adler class
lural and object oriented programming paradigms
@ Jove Programming- History of Java
0 The history of java ctarte from breen Team. Java team
members (alco known ac Green Team), initiated a revolutionary
tack to develop a language for digital devices cuch ac cet-top
boxes, televigions ete.| Patrick Naughton
ject in June 1997. The small
ginally decigned for cmall, embedded cysteme in electronic
appliances like cet- top boxes.
3) Firstly, it was called "Greentalk” by James Gosling and file
extencion was gt.
4) After that, it was called Qak and was developed as a part o|
the Green project.11) 10.Java SE 8 (18th March,
There is given many features of java. They are also known as
java buzzworde. The Java Features given below are simple and
easy to understand.
1. Cimple
2. Object-Oriented
3. Portable
4. Platform independentare statements that are not executed b
and interpreter. The comments can be uced to
le information or explanation about the variable, method,
clase or any statement. It can alco be uced to hide program
code for specific time.
Types of Java Comments
There are 3 types of comment? in java.public clase CommentExample1
public static void main(String/] args) { nit i=10,//Here, i ic a
variable Syctem.out.println(i);public clace CommentExample2
public static void main(Ctring/] arge,
7
et’s declare and print variable in java. ”/
int i=10; Syctem.out.println (i);Example:
“* The Calculator class provides methode to get addition and
subtraction of given 2 numbers. /
public clace Caleulator
“* The add() method returns addition of given numbers.”UL files created for your Caleulator clase
h tory. Open the HTML filec and cee the
of Caleulator class provided through documentation
T
Data Types
lata types represent the different values to be stored in the
variable. In java, there are two types of data types:_|e6 te
love. Variable Example: Add Two Numbers
clase Simple
public ctatic void main(String/] args,
int a=10; int b=10; int c=atbh;pec in java: primitive and non-
faviable
here are three types of variables in java:
0 local variable
o instance variable
o static variableot declared ac
iable that ic declared ac static ic called static variable. It
cannot be local. We will have detailed learning of these
variablee in next chapters.
Example to understand the types of variables in java
class A,
int data=50,//inctance variable ctatic int m=100,//static
variable void methodoutside that block.
how long the variable exists
oying variable refers to
memory that was allotted to the variables
eclaring it. We have written a few clascec till now. You
ht have observed that rot all variables are the came. The
ones declared in the body of a method were different from
those that were declared in the clase itself. There are three
pec of variables: inctance variables, formal parameters or
local variables and local variables.
Instance variables| Argument variables
Thece are the variablec that are defined in the header oaf
constructor or a method. The scope of these variables ic the
method or constructor in which they are defined. The lifetime
i¢ limited to the time for which the method keeps executing.
Once the method finiches execution, thece variablec are
destroyed.applied to instance
to local variable.
al bles defined in a method, we alco
at are defined in books life an if block and an
» scope and i¢ the came ac that of the block
a
Operator in java ic a cymbol that ic ued to perform
operations. For example: +, ~*~ te. There are many types o
operatore in java which are given below:
0 Unary Operator,ential building blocks of any Java program,
d to produce a new value, although sometimes an
ion simply assigns a value to a variable. Expressions are
Built using values, variables, operators and method calle.
pec of Expressions
While an expression frequently produces a result, it doecnt
always. There are three typec of expreccions in Java:place when two data types are
vert ed. hig happens when:
types are compatible.
| When we assign value of a cmaller data. type to a bigger
| data
For Example, in java the numeric data types are compatible
with each other but no automatic conversion ic cupported From
numeric type to char or boolean. Alco, char and boolean are
not compatible with each other.lata. type that contain fixed set o
“Tt can be used for days of the week (SUNDAY. MONDA
| AY, WEDNESDAY, THURSDAY, FRIDAY and
ATURDAY) directions (NORTH, SOUTH, EAST and WEST)
ete. [he java enum constants are ctatic and final implicitly. It
i¢ available from [DK 1.5. Java Enume can be thought of ac
clascec that have fixed cet of constants.
‘imple example of java enumva allow you to run oF Skip
conditions are met.
rement in Java works exactly like in most
gramming languages. With the help of “if” you can choose to
execute a specific block of code when a predefined condition ic
met. The structure of the “if” statement in Java looks like this:
if (condition
execute this codetring[] args) 5.
__| 8. Make cure your code i¢ compiled, and that you have tested it
thoroughly.
7. If youre using Windows, you will need to cet your path to
include Java, if you haven't done co already. [hic ic a delicate
operation. Open Explorer, and look inside C:\ProgramFilec\ Java
and you chould cee come version of the JDK. Open thie Folder,
and then open the bin folder. Select the complete path from4 right end,
scing Ctrl-V/ to pacte the path
head and cave your changes. (If
{ windows open, you will need to cloce them.
ou're using Windows, go to the Start menu and type
| emd” to run a program that brings up a command prompt
window. If youre using a Mac or Linux machine, run the
ferminal program to bring up a command prompt.
11. In Windows, type dir at the command prompt to lict the
contents of the current directory. On a Mac or Linux machine,
type Ie to do thie.very time you change to anew directory, lict the contents o
BE rr ienece Where to no next. Continue licting and
changing directories until you reach the directory that
contains
‘our clase files.
13. Tf you compiled your program using Java 1.6, but plan towray, which ctores a
ements of the came type. An
ollection of data, but it ic often more
an array ac a collection of variables of the
Lnstead of declaring individual variables, cuch ag numberO,
numbert, ..and number??, you declare one array variable
cuch ag numbers and use numbers[O], numbers[1], and _...
numbers[77] to represent individual variables.
Thi tutorial introducee how to declare array variables, createered. The style
e C/C++ language and
date C/C++ programmers.
_The following code snippets are examples of this syntax:
double[] mylist; or
double myCict/],
eating Arrays:
preferred way.ewly created array to the
an array variable, creating an array, and assigning
e reference of the array to the variable can be combined in
one statement, ac chown below:
Alternatively you can create arrays as follows:
The array element are accecsced through the index. Arras
indices are 0-baced; that ic, they start From 0 tolements, we often uce either for loop
ecauce all of the elements in an array are o
and the size of the array ic known.
=| Example:
Here ic a complete example of showing how to create, initialize
and process arrays:
Thig would produce the following recult:red to get input From concole. It
exte and paccwords.
ad pascword using Console clase, it will not be
red to the user.
he java.io.Console clase i¢ attached with system console
internally. The Console clase ic introduced since 1.5.
etc cee a cimple example to read text from console.Enter your name: ')-
.out.println(‘Weleome +n);
lonctructor in java ic a special type of method that ic used to
initialize the object.
lava constructor i¢ invoked at the time of object creation. It
constructe the values i.e. provides data for the object that ic
why it i¢ known ac constructor.onstructor,
ronstructor
A conctructor that have no parameter ic known as default
constructor.
intax of default constructor:2 created the constructor of Student
0 parameters. We can have any number o
in the constructor.
tudent 4;
int id; String nome;
tudent Y(int i, String w)f d= i;
dine = h;
play() {System.out.println(id+” "+name):a technique in Java in which a class
+ of constructors that differ in parameter
Herentiatec thece conctructore by taking
account the number of parameters in the list and their
Example of Constructor Overloading
clase Student 5,
int id: String name; int age;
tudent5 (int i, String n){ d= i;; al Output:
lava. Copy Constructor
There ig no copy constructor in java. But, we can copy the
values of one object to another like copy constructor in C++.2¢ of one object
tudent6(Student6 o)f d=
ABE =C.VBME;
void dicplas ctem.out.printla(id+” “+name);ements that are grouped
} an operation. When you call the
ntln() method, for example, the cyctem actual,
scutes ceveral statements in order to display a message on
the console.
Now you will learn how to create your own methods with or
without return values, invoke a method with or without
parameters, and apply method abstraction in the program
design.
reating Methode of the method
— formal parameters
+ int a int b — list of parameters
Method definition consists of a method header and a method
ody. The came ic chown in the following cyntax —
ntaxThe method
d the parameter lict.
e fi ee parameters, it ic the type, order,
¢ ametere of a method. These are optional,
od contain zero parameters.
od body — The method body defines what the method
does with the ctatements.
‘all by Value and Call by Reference in Java
here ic only call by value in java, not call by reference. If we
call a method pascing a value, it i¢ known ac call by value. The
changes being done in the called method, ic not affected in the
calling method.efore change ’+op.data);
er change "+op.data);
In Java, parameters ave always pasced by value. For example,
‘ollowing program prints i = 10,
Test.java clase Test
cwap() doecnt owap i and jtie Fielde and Methods
he static keyword in java ic used for memory management
mainly. We can apply java static keyword with variables,
methods, blocks and nested class. The static keyword belongs
to the clace than inctance of the clace.‘atic, it i¢ known static
c variable can be uced to refer the common
rty of all objects (that i¢ not unique for each object) e.g.
company name of employees, college name of ctudente etc.
o The static variable gets memory only once in class area at
the time of clase loading.
Advantage of ctatic variableic String college ="TTS”: StudentB(int +, String n){ ailno =
void dieplas ctem.out.printlh(rollnor” "+namer” “+college);
public ctatie void main(Ctring argc[], fadent® of = new
tudent8(111,"Karan”)- Student o2 = newmethod, it i¢ known as
ethod belongs to the clace rather than object of a
oA static method can be invoked without the need for
creating an instance of a class.
0 static method can accece static data member and can
change the value of it.
Example of static method‘em.out.printin(rollnor” "tnamer” "+college):
void main(String args[]){ Eadent 7.change();
nt? 07 = new Student? (111,"Karan”); Student? 02 =
new Student? (222, "Aryan"); Student? 03 = new Student?
333, "Conoo'); 1.displas
¢2.digplas
63.digplasmout.printla(’Hello
=| Accece Modifiers in java.
here are two types of modifiers in java: access modifiers and
hon-access modifiers.
The aecece modifiers in java specifies acceccibility (scope) of aible only within clase.
te accece modifier
have created two classes A and Simple. A
ing private data member and private method. We
accessing these private members from outside the class, so
there ic compile time error.
class A,
private int data=40;
private void msg ctem.out.printla( Hello java).
public clace Fimple
public static void main(String argc[]){ Abj=new Ac A clase from outside ite package,
sublic, co it cannot be accecced from
A java package pack; clase A;
id msg istem.out.println( Hello”);
‘cave by B.java package mypack; import pack.*;
class B
public static void main(String argc[]){ Abj = newlifter can be applied on the data
d constructor. It can't be applied on the
le of protected accece modifier
| Th thie example, we have created the two packages pack and
mypack. The A clase of pack package is public, so can be
accessed from outside the package. But meg method of this
package ic declared as protected, ¢o it can be accesced from
outside the clace only through inheritance.ic accescible everywhere. It has the
ple of public accese modifier
‘cave by A.java package pack; public clacs A
public void meg stem.out.printlh (‘Hello’);
‘cave by B.java package mypack; import pack”; clase B
public static void main(String args[]){ Abj = new A
0bj.mogclase instance variable.
te current clase method (implicit
d to invoke current clage constructor.
i¢ can be passed a¢ an argument in the method call.
5. thie can be passed ac argument in the constructor call.
6. thie can be used to return the current clase instance From
the method.
clace Student{ nit rollno; String name; float fee;
tudent(int rollno, String name float fee,nkit 5000
112 sumit 6000
lava. Constructor Java Method
onstructor ic used to initialize the ctate of an object. Method
ic uced to expoce behaviour of an object.
lonstructor must not have return type. Method must haveloading in Java
ique in Java in which a class
of constructors that differ in parameter
rentiates thece constructors by taking
int the number of parameters in the lict and their
_type.
Example of Constructor Overloading
class Student5{ nt id: String name; int
age;
tudentS (int i String wf d= i;
bine = h;Method Overloading in java
Tf a clase hac multiple methode having came name but
different in parameters, it i¢ known as Method Overloading.
Tf we have to perform only one operation, having came name o|d(int aint b) {return arb;
add(int aint bint c) {return arb+e;
| class TectOverloading 1,
public static void main(String/] args,
€em.out.println(Adder.add(11,11
otem.out.println(Adder.add(11,11,11,¢ in which a method calle itself
rethod in java that calle iteelf i¢ called
lava. Recursion Example 1: Factorial Number
public clase RecursionExomple3
static int factorial(int »
h 1) return 1; elee> unreferenced objecte.
Collection ic procece of reclaiming the runtime unuced
ory automatically. In other words, it i¢ a way to destro
__| the unused objects.
lo do co, we were using free() function in C language and
delete() in C++. But, in java it ic performed automatically. So,
java provides better memory management.
Advantage of Garbage Collectionple of garbage collection in java public clase
_Testbarbage!,
public void finalize ctem.out.printlr( object ic garbage
collected’);
public ctatic void main(String args[]){ &ktbarbaget ot=new
TestGarbage1(); TestGarbage1 s2=new Testbarbage
null;
all. Syctem.ge:of methods to perform
as compare(), concat(), equale
comparelo(), intern(), cubstring
3. The java.lang.String clase implements Serializable,
=| lomparable and CharSequence interfaces.
har Gequence Interface
The Char Sequence interface ic uced to reprecent cequence o|
characters. It ic implemented by String, StringBuffer anding literal ic created by using double quotes. For
ple:
|
1. String s="welcome’:
Each time you create a string literal the JVM checks the
string conctant pool firct. If the ctring already exicte in the
pool_a reference to the pooled instance ic returned. Tf ctringew ctring object in normal
d the literal Welcome” will be placed
ant pool. The variable ¢ will refer to the
(‘non pool).
lave. String Example
public clace StringExample;
public static void main(Ctring argc[],
tring ¢1=java’s//oreating string by java string literal
char ch{fafer teri ni aie):
tring e2=new String(ch),//converting char array to stringutable cimply means
ce string object ic created ite
anged but a new string object ic
‘0 understand the immutability concept b
ectimmutablectring
public ctatic void main(String argec/] Ging c="Sachin",
s.concat(’ Tendulkar’) //concat() method appends the string
at the end Syctemout.printlr(c)//will print Cachin because
strings are immutable objects
Output:Sachinamechanicm in which one object
properties and behaviors of parent object.
e reprecente the IC-A relationship, alco known ac
| child relationchip.
Why use inheritance in java
0 For Method Overriding (co runtime polymorphism can be
achieved).
o For Code Reucability.extends Employee,
ublic static void main(String argc[] Pogrammer p=new
, al ‘rogrammer();
stem.out.printh(Programmer salary is:’+p.calary);
ctem.out.printla( Bonus of Programmer ic:"+p.bonuc);
Bonus of programmer i¢:10000Jest Inheritance
__| public ctatic void main(String argc[]){ Dy d=new Dog
d.bark();
d.eat();
Output:
barking... eating...out.printlr(weeping...”);
est Inheritance?2,
|
public static void main(String args//
BabyDog(); d.weep
d.bark();
d.eat();stem.out.println(‘meowing...");
class TectInheritance3;
public static void main(String args[]){ Bt c=new Cat();
c.meow
c.eat(];
c.-bork() //C.T-Error¢ referred by cuper
be used to refer immediate parent clace instance
‘able.
; _ | 2. super can be used to invoke immediate parent clase method.
3. cuper() can be used to invoke immediate parent clase
constructor.
cuper ic uced to refer immediate parent clase inctance variable.Output:
Final Keyword in Java
The final keyword in java ic uced to restrict the user. The javavariable can be static alco
tatic block only.
Ybject clase ic the parent clase of all the classes in java
y defoult. In other words, it i¢ the topmost clase of java.
he Object clase ic beneficial if you want to refer any object
whose type you dont know. Notice that parent clase reference
variable can refer the child clace object, know as upcasting.
etc take an example there i¢ getObject() method thatct can be cloned,
hild clace) has the came method ag declared in
parent clase, it ic known ac method overriding in java.
| cage of Java Method Overriding
o Method overriding i¢ uced to provide specific implementation
of a method that ic already provided by ite cuper clase.
o Method overriding i¢ used for runtime polymorphisin
Rules for Java Method Overridingunning cafely’):
[Dt fre2 obj = new
Output:Bike ic running cafely
1. clase Bank,
int getRateOfInterect(}{return 0;
clase SBI extende Bank,AXIE aznew A,
(SBI Rate of Interest:
teOfIuterect()); Syctemout.println( ICICI Rate o|
terect: "si.getRateOf[nterect()): System.out.printh (AXIS
Rate of Interest: “+a.getRate(fluterest,
Abstract clase in Java
A clase that ic declared with abstract keyword i¢ known asact method
4 extends Bike;
run istem.out.printlh(‘running cafely..”);
public static void main(String args[]){ fre obj = new
Honda4();
obj.run
if
Interface in Javaelationchip. It cannot be
ze reacons to use interface. They are
iced to achieve abstraction.
_o By interface, we can support the functionality of multiple
| inheritance.
o Tt can be used to achieve loose coupling.
Taternal addition by compiler
Inderctanding relationship between classes and interfacesm.out.println(‘drawing circle’);
face: by third ucer
ect Interface,
public ctatic void main(Ctring arge[]
Drawable d=new Cirele();//Tn real scenario, object is provided
by method e.g. getDrawable() d.draw();
Output:drawing circlen.out.println(“Hello’);) public void
printhn('Welcome’);) public static void
q argc[]
bj = new A? (); obj.print();
Output:Hello
Welcome
Abstract clase Interfaceblie abstract
public abstract
es
clase void
thape, daw(); Example:
public interface void
J___
Drawable{nner_clase,
Advantage of java inner classes
There are basically three advantages of inner classes in java.
They are ac follows:¢ code to write.
nested clace and inner class in Java.
er clace ic a part of nected clase. Non-ctatic nected clacces
© knowh ag inner classes.
pec of Nested classes
There are two types of nested classes non-static and static
nected clacces. The non-ctatic nected clacces are alco known of
inner clacces.placces, interfaces
be categorized in two
ined package. There ave
ich as java, lang awt, javax, swing
Advantage of Java Package
age ic used to categorize the clacces and
terfaces co that they can be easily maintained.
=
lava package provides acces protection.
3) Java package removes naming collision.
package mypack;‘ully qualified name
Example of package by import Fully qualified name
‘cave by A.java package pack; public class A
public void meg ictem.out.printlr( Hello");
‘cave by B.java package mypack; clase B(PUTER SCIENCE &
fon handling in java ic one of the powerful
anicin to handle the runtime errors co that normal low
of the application can be maintained.
What i¢ exception
Th java, exception ig an event that dicrupte the normal flow o
the program. It i¢ an object which i¢ thrown at runtime.checked and
pnsidered ac unchecked exception.
ic there are three typec of exceptions:
ae
Inchecked Exception
| 3. Error
ifference between checked and unchecked exception’
1) Checked Exception: The classes that extend Throwable class
except RuntimeException and Error are known ac checked
exceptions e.9.10Exception, SQlException etc. CheckedJavo.try block __
Java try block ic used to encloce the code that might throw an
exception. It must be used within the method.
Java. try block must be followed by either catch or finally block.toh block ic uced to handle the Exception. It must be
_used after the try block only. You can use multiple catch block
with a cingle try.
Problem without exception handling
etc try to understand the problem if we dont use try-catch
block.+t of the code ic not
e code... statement i¢ not
be 100 lines of code after exception. So all the code
+ exception will not be executed.
lution by exception handling
ete cee the solution of above problem by java try-catch block.
public clase Tecttrycatch2,ct of the code ic
statement i¢ printed.
ou have to perform different tasks at the occurrence o|
different Exceptions, uce java multi catch block.
ets cee a cimple example of java multi-catch block.
1. public clase TectMultipleCatchBlock,
2. public static void main(String argc/]of the code...’); 13.
lave. nected try example
et’c cee a cimple example of java nected try block.
clase Excep6,
public static void main(String args[],t.println( other statement):
mout.printh (‘handeled’).
lave finally block ic a block that i¢ used to execute important
code cuch ag clocing connection, stream ete.
lave finally block ic always executed whether exception i¢
handled or not. Java finally block follows try or catch block.on e){Syctem.out.println(e);
printin( finally block i¢ always executed’);
lave. throw keyword
The Java throw keyword i¢ used to explicitly throw an
exception.2 created the validate method that
ue ac a parameter. If the age is lece than 18,
wing the ArithmeticException otherwise print a
cage welcome to vote.
1. public clace Test Throw,
static void validate(int age,
if(age< 18,
throw new ArithmeticException(“not valid’);
elceticException:not
‘ows keyword ic used to declare an exception. It
¢ an information to the programmer that there may occur
an exception co it ic better for the programmer to provide the
exception handling code co that normal flow can be
maintained.
Exception Handling ic mainly used to handle the checked
exceptions. If there occurs any unchecked exception cuch awe clause which decoribes
in be propagated by throws keyword.
aio. L0Exception;
estthrows7,
void m()throws IOException
throw new T0Exception( device error”);//checked exception
void n()throwe [0Exception!pwn Exception that ic known ac
nor user-defined exception. Java custom
are used to customize the exception according to
wer need.
=
By the help of custom exception, you can have your own
exception and meccage. Let's cee a simple example of java.
custom exception.
clase InvalidAgeException extends Exception
nvblidAgeException(Ctring ¢ctem.out.printlh (Exception occured:
stem.out.printla(‘rect of the code...");
Output:Exception occured: InvalidAgeException:not valid rest
of the code...mmultiproceccing because
on memory area. They dont allocate
nory area co Caves memory, and context-cwitehing
» the threads takes lece time than process.
MMM ecpentiie ioctl, uced in games, animotion ete.
Advantages of Java Multithreading
1) It doecn't block the user becauce threade are independent
and you can perform multiple operations at Came time.ding to oun,
cle in java new, runnable
ere if ho running state.
lerstanding the threads, we are explaining it
he life cycle of the thread in java ic controlled b |. The
java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked,constructors and methode to create and
rations on a thread. Thread clase extends Object
and implements Runnable interface.
‘ommonly used Constructors of Thread class:
o Thread(
0 Thread(Ctring name,
o Thread(Runnable r,¢ the current
y ceace execution) for the
‘or a thread to die.
inllong miliceconds): waits for a thread to die
Perepecifedimiliceconde.
». public int getPriority(): returns the priority of the thread.
| 2. public int cetPriority (int priority): changec the priority o
the thread.
8. public String getVame(): returns the name of the thread.
7. public void setName(String name): changes the name of the
thread.
10. public Thread currentThread(): returns the reference o|‘ume the cucpended
is used to stop the thread(depricated).
icDaemon(): tests if the thread i¢ a daemon
__|_17. public void cetDacmon(boolean b): marke the thread as
daemon or user thread.
20. public void interrupt (): interrupts the thread.
21. public boolean icInterrupted(): tecte if the thread has
been interrupted.
22. public ctatic boolean interrupted(): teste if the current
thread hag been interrupted.read clace i¢ used to start a newk
d thread. It performs following tacke:
new thread ctarts(with new callctack).
0 The thread moves from New state to the Runnable ctate.
o When the thread gets a chance to execute, its target run
method will run.
lave. Thread Example by extending Thread clasewnnable interface
lie void run
‘thread i¢ running... ’);
jie static void main(String args[] Mtiz mT=new
Malti3
hread t71 =new Thread(m1); t1.start
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by af ead i¢ 5 (MORM_PRIORITY). The
Y RIORITY i¢ 1 and the value o|
RIORITY is 10.
Example of priority of a Thread: clace TectMultiPriority?
extende Thread! whlic void run
stem out.printla(‘running thread name
ig: Thread.current [hread().get Name:
ictem.out.printla(‘running thread priorit
i¢:+ Thvead.current [hread().getPriorit}2 ie:Thread-0 running thread
name i¢:Thread-1 running thread priovity i¢:1
| lava. synchronized method
Tf you declare any method ac synchronized, it ic known as
nchronized method. Synchronized method ic used to lock an
object for any chared resource.
Wher a thread invokes a synchronized method, itdraw...”):
-out.println( ‘Cece balance; waiting for
O;feateh (Exception e,
Reo ne. Gyetem out printin( “withdraw
completed...”);
inchronized void deposit (int amount,
fem out.println(‘going to depocit..."); thic.amount+=amount;
ctem.out.printh(‘depocit completed... ’); notilroup in Java
lava provides a convenient way to group multiple threads in a
cingle object. In cuch way, we can suspend, recume or interrupt
group of threads by a single method call.AGroup(‘Group A’):
sad(t91,new MyRunnable(),one”);
new Thread(tg1, new MyRunnable(), two
d t3 = new Thread(tg1,new MyRunnable(), three’);
| Now all 3 threade belong to one group. Here, tg7 ic the thread
group name, MyRunnable ic the class that implements
Runnable interface and "one ‘two” and ‘three’ are the thread
AAmes.
Now we can interrupt all threads by a single line of code only./ containc a collection o|
ide the low-level communication
write programs that focus on solving
net package provides support for the two common
etwork protocols —
|
P-TCP stands for Transmission Control Protocol, which
allows for reliable communication between two applications.
TCP is typically used over the Internet Protocol, which is
referred to ac T(
\P - UDP stande for User Datagram Protocol anececcary for every java developer to
ce it has a lot of clacces that ic helpful in
ting cuch ac dates, numbers, and meccagec.
| java.text Classes
he following are the clacces available for java.text package
table,
lace[Deseription
‘impleDateFormatlic a concrete clace that helpe in formatting
and parsing of dates. [/tableon
group of objecte.
ou perforin on a data cuch ag
rting, incertion, manipulation, deletion ete. can be
lave. Collections.
| lava Collection cimply means a single unit of objects. Java
‘ollection Framework provides many interfaces (Set, List,
Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriovityQueue, HashSet, LinkedHashSet, TreeSet ete).
What ic framework in java.‘chy of Collection Framework
: | lava. ArrayList clase
lava ArrayList class usec a dynamic array for storing the
elements. [t inherits Abctractlict clase and implements List
interface.
The important pointe about Java Arraylict clase are:lavation for java.utilArraylict clase.
Constructors of Java Arraylict
constructor Description
Arvaylict() It ic used to build an empty array Li
Arraylict(Collection c) It ic uved to build an array list that i¢through Iterator Iterator itr=lict.iterator();
boasNext, Setem.out.printla(itr. next)
| vector
Arraylict and Vector both implements Lict interface and
maintains insertion order.
But there are many differences between Arraylict and Vectorwce it i¢ non-cynchronized.
ext it i¢ synchronized i.e. in multithreading
ment, it will hold the other threade in runnable or non-
tnnable ctate until current thread releaces the lock of object.
5) Arraylic tuses Iterator interface to traverse the elements.
fector useo Enumeration interface to traverse the elements.
But it can use Iterator alco.
Example of Java Vectoring Enumeration
ation e=v.elementc();
while(ehasMoreElements(
ctem.out.println(e.nextElement()); 12.
lave. Hashtable claceinc valuec based on the
elements.
at have any null key or value.
¢ synchronized.
| Hashtable clace declaration
etc cee the declaration for java.util. Hashtable class.
1. public clace Hashtable extende Dictionary implements Map
loneable, Ser ializablethe default constructor of hach table it
tec the Hachtable class.
chtable(int size) Tt i¢ used to accept an integer parameter
and creates a hash table that hac an initial size specified b
integer value cize.
lachtable(int fillRatio) size, float
It ie uced to create a bach table that has an initial cize
specified by size and a fill ratio specified by fillRatio."meget Value
tack
tack ic a cubclace of Vector that implements a standard last-
in, first-out stack.
tack only defines the default constructor, which creates anch(Stack st, int a) { tpuch(new
stemout.printla(‘push(" + a+
_| Systemout-println(“stack: "+ ct),
; al static void chowpop(Ctack ct, Sotem.out.print(“pop -> ");
Tnteger a = (Integer) st.pop(); Syetem.out.println(a);
ctemout.printhn(‘stack: "+ ct); public static void
main(String args/]
tack ct = new Stack(); Syctem.out.printin("ctack: "+ ct);
chowpuch(ct, 42);