MTE2 A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF CSE (EMERGING TECHNOLOGIES)


Unit-2
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. Inheritance represents the IS-A relationship, also known as parent-
child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}}

Programmer salary is:40000.0

JAVA PROGRAMMING Page 37


Bonus of programmer is:10000

Types of inheritance in java

Single Inheritance Example


File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{

JAVA PROGRAMMING Page 38


public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.e at();
}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

JAVA PROGRAMMING Page 39


Member access and Inheritance

A subclass includes all of the members of its super class but it cannot access those members of
the super class that have been declared as private. Attempt to access a private variable would
cause compilation error as it causes access violation. The variables declared as private, is only
accessible by other members of its own class. Subclass have no access to it.

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();

JAVA PROGRAMMING Page 40


d.printColor();
}}

Output:

black
white
Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.

Object class in Java

The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice
that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type
like Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

JAVA PROGRAMMING Page 41


Usage of Java Method Overriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of method overriding


Class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}

Output:Bike is running safely

1. class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}

Output:
SBI Rate of Interest: 8

JAVA PROGRAMMING Page 42


ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Abstract class in Java

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body). It needs to be extended and its method
implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method
1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
1. }
running safely..
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance in
Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

JAVA PROGRAMMING Page 43


Internal addition by compiler

Understanding relationship between classes and interfaces

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
Output:drawing circle

Multiple inheritance in Java by interface

interface Printable{

JAVA PROGRAMMING Page 44


void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}

Output:Hello
Welcome
Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods. Since
and non-abstract methods. Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Java Inner Classes


Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }}

JAVA PROGRAMMING Page 45


Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested
classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}}

JAVA PROGRAMMING Page 46


How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename


How to run java package program

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

Using fully qualified name

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

JAVA PROGRAMMING Page 47


MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF CSE (EMERGING TECHNOLOGIES)

UNIT-3

Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

What is exception

In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.

JAVA PROGRAMMING Page 48


Hierarchy of Java Exception classes

Checked and UnChecked Exceptions

JAVA PROGRAMMING Page 49


Java try block

Java try block is used to enclose 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.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{

JAVA PROGRAMMING Page 50


public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
9. }
10. catch(Exception e){System.out.println("common task completed");
11. }
12. System.out.println("rest of the code...");
13. } }

Output:task1 completed
rest of the code...

Java nested try example

Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{

JAVA PROGRAMMING Page 51


int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block

Java finally block is a block that is used to execute important code such as closing connection,
stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.

Usage of Java finally

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

The syntax of java throw keyword is given below.

1. throw exception;

JAVA PROGRAMMING Page 52


Java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

1. public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
} }

Output:

Exception in thread main java.lang.ArithmeticException:not valid


Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }
4.

Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception

JAVA PROGRAMMING Page 53


}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...

Java Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

class InvalidAgeException extends Exception{


InvalidAgeException(String s){
super(s);
}}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

JAVA PROGRAMMING Page 54


Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can performmultiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

JAVA PROGRAMMING Page 55


How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

JAVA PROGRAMMING Page 56


Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

JAVA PROGRAMMING Page 57


Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}}
Output:thread is running...

Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}}
Output:thread is running...

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and


the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[]){

JAVA PROGRAMMING Page 58


TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

Example of inter thread communication in java


Let's see the simple example of inter thread communication.

class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){

JAVA PROGRAMMING Page 59


public void run(){c.deposit(10000);}
}
start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object. In such way, we can
suspend, resume or interrupt group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by java.lang.ThreadGroup class.

Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class.

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

Let's see a code to group multiple threads.

1. ThreadGroup tg1 = new ThreadGroup("Group A");


2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");
3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");
4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");

Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.

Now we can interrupt all threads by a single line of code only.

1. Thread.currentThread().getThreadGroup().interrupt();

Exploring java.net and java.text

JAVA PROGRAMMING Page 60


java.net
The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.

The java.net package provides support for the two common network protocols −

 TCP − 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 as TCP/IP.

 UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.

This chapter gives a good understanding on the following two subjects −

 Socket Programming − This is the most widely used concept in Networking and it has
been explained in very detail.

 URL Processing − This would be covered separately.

java.text

The java.text package is necessary for every java developer to master because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.

java.text Classes

The following are the classes available for java.text package

[table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of dates.
[/table]

JAVA PROGRAMMING Page 61

You might also like