Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 30

JAVA PROGRAMMING

UNIT – I

Internet Overview
Internet is defined as an Information super Highway, to access information over the
web. However, It can be defined in many ways as follows:
 Internet is a world-wide global system of interconnected computer networks.
 Internet uses the standard Internet Protocol (TCP/IP).
 Every computer in internet is identified by a unique IP address.
 IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer
location.
 A special computer DNS (Domain Name Server) is used to give name to the IP Address so
that user can locate a computer by a name.
 For example, a DNS server will resolve a name http://www.tutorialspoint.com to a
particular IP address to uniquely identify the computer on which this website is hosted.
 Internet is accessible to every user all over the world.

Evolution
The concept of Internet was originated in 1969 and has undergone several
technological & Infrastructural changes as discussed below:
 The origin of Internet devised from the concept of Advanced Research Project Agency
Network (ARPANET).
 ARPANET was developed by United States Department of Defense.
 Basic purpose of ARPANET was to provide communication among the various bodies of
government.
 Initially, there were only four nodes, formally called Hosts.
 In 1972, the ARPANET spread over the globe with 23 nodes located at different countries
and thus became known as Internet.
 By the time, with invention of new technologies such as TCP/IP protocols, DNS, WWW,
browsers, scripting languages etc.,Internet provided a medium to publish and access
information over the web.

Advantages
Internet covers almost every aspect of life, one can think of. Here, we will discuss
some of the advantages of Internet:

 Internet allows us to communicate with the people sitting at remote locations. There are
various apps available on the wed that uses Internet as a medium for communication. One
can find various social networking sites such as:
o Facebook

o Twitter

o Yahoo

o Google+

o Flickr

o Orkut

 One can surf for any kind of information over the internet. Information regarding various
topics such as Technology, Health & Science, Social Studies, Geographical Information,
Information Technology, Products etc can be surfed with help of a search engine.
 Apart from communication and source of information, internet also serves a medium for
entertainment. Following are the various modes for entertainment over internet.
o Online Television

o Online Games

o Songs

o Videos

o Social Networking Apps

 Internet allows us to use many services like:


o Internet Banking

o Matrimonial Services

o Online Shopping

o Online Ticket Booking

o Online Bill Payment

o Data Sharing

o E-mail

 Internet provides concept of electronic commerce, that allows the business deals to be
conducted on electronic systems

Disadvantages
However, Internet has prooved to be a powerful source of information in almost every
field, yet there exists many disadvanatges discussed below:
 There are always chances to loose personal information such as name, address, credit card
number. Therefore, one should be very careful while sharing such information. One should
use credit cards only through authenticated sites.
 Another disadvantage is the Spamming.Spamming corresponds to the unwanted e-mails in
bulk. These e-mails serve no purpose and lead to obstruction of entire system.
 Virus can easily be spread to the computers connected to internet. Such virus attacks may
cause your system to crash or your important data may get deleted.
 Also a biggest threat on internet is pornography. There are many pornographic sites that
can be found, letting your children to use internet which indirectly affects the children
healthy mental life.
 There are various websites that do not provide the authenticated information. This leads to
misconception among many people.
INTERNET PROTOCOLS

Transmission Control Protocol (TCP)


TCP is a connection oriented protocol and offers end-to-end packet delivery. It acts as
back bone for connection.It exhibits the following key features:
 Transmission Control Protocol (TCP) corresponds to the Transport Layer of OSI Model.
 TCP is a reliable and connection oriented protocol.
 TCP offers:
o Stream Data Transfer.

o Reliability.

o Efficient Flow Control

o Full-duplex operation.

o Multiplexing.

 TCP offers connection oriented end-to-end packet delivery.


 TCP ensures reliability by sequencing bytes with a forwarding acknowledgement number
that indicates to the destination the next byte the source expect to receive.
 It retransmits the bytes not acknowledged with in specified time period.

TCP Services
TCP offers following services to the processes at the application layer:
 Stream Delivery Service
 Sending and Receiving Buffers
 Bytes and Segments
 Full Duplex Service
 Connection Oriented Service
 Reliable Service

Stream Deliver Service


TCP protocol is stream oriented because it allows the sending process to send data as
stream of bytes and the receiving process to obtain data as stream of bytes.
Sending and Receiving Buffers
It may not be possible for sending and receiving process to produce and obtain data at
same speed, therefore, TCP needs buffers for storage at sending and receiving ends.
Bytes and Segments
The Transmission Control Protocol (TCP), at transport layer groups the bytes into a
packet. This packet is called segment. Before transmission of these packets, these
segments are encapsulated into an IP datagram.
Full Duplex Service
Transmitting the data in duplex mode means flow of data in both the directions at the
same time.
Connection Oriented Service
TCP offers connection oriented service in the following manner:
1. TCP of process-1 informs TCP of process – 2 and gets its approval.
2. TCP of process – 1 and TCP of process – 2 and exchange data in both the two directions.
3. After completing the data exchange, when buffers on both sides are empty, the two TCP’s
destroy their buffers.

Reliable Service
For sake of reliability, TCP uses acknowledgement mechanism.

Internet Protocol (IP)


Internet Protocol is connectionless and unreliable protocol. It ensures no guarantee
of successfully transmission of data.
In order to make it reliable, it must be paired with reliable protocol such as TCP at the
transport layer.
Internet protocol transmits the data in form of a datagram as shown in the following
diagram:

Points to remember:
 The length of datagram is variable.
 The Datagram is divided into two parts: header and data.
 The length of header is 20 to 60 bytes.
 The header contains information for routing and delivery of the packet.
User Datagram Protocol (UDP)
Like IP, UDP is connectionless and unreliable protocol. It doesn’t require making a
connection with the host to exchange data. Since UDP is unreliable protocol, there is
no mechanism for ensuring that data sent is received.
UDP transmits the data in form of a datagram. The UDP datagram consists of five
parts as shown in the following diagram:

Points to remember:
 UDP is used by the application that typically transmit small amount of data at one time.
 UDP provides protocol port used i.e. UDP message contains both source and destination
port number, that makes it possible for UDP software at the destination to deliver the
message to correct application program.

File Transfer Protocol (FTP)


FTP is used to copy files from one host to another. FTP offers the mechanism for the
same in following manner:
 FTP creates two processes such as Control Process and Data Transfer Process at both
ends i.e. at client as well as at server.
 FTP establishes two different connections: one is for data transfer and other is for control
information.
 Control connection is made between control processes while Data Connection is made
between<="" b="">
 FTP uses port 21 for the control connection and Port 20 for the data connection.
Trivial File Transfer Protocol (TFTP)
Trivial File Transfer Protocol is also used to transfer the files but it transfers the files
without authentication. Unlike FTP, TFTP does not separate control and data
information. Since there is no authentication exists, TFTP lacks in security features
therefore it is not recommended to use TFTP.
Key points
 TFTP makes use of UDP for data transport. Each TFTP message is carried in separate UDP
datagram.
 The first two bytes of a TFTP message specify the type of message.
 The TFTP session is initiated when a TFTP client sends a request to upload or download a
file.
 The request is sent from an ephemeral UDP port to the UDP port 69 of an TFTP server.

Difference between FTP and TFTP


S.N. Parameter FTP TFTP
1 Operation Transferring Files Transferring Files

2 Authentication Yes No

3 Protocol TCP UDP

4 Ports 21 – Control, 20 – Data Port 3214, 69, 4012

5 Control and Data Separated Separated

6 Data Transfer Reliable Unreliable

Telnet
Telnet is a protocol used to log in to remote computer on the internet. There are a
number of Telnet clients having user friendly user interface. The following diagram
shows a person is logged in to computer A, and from there, he remote logged into
computer B.

Hyper Text Transfer Protocol (HTTP)


HTTP is a communication protocol. It defines mechanism for communication between
browser and the web server. It is also called request and response protocol because
the communication between browser and server takes place in request and response
pairs.
HTTP Request
HTTP request comprises of lines which contains:
 Request line
 Header Fields
 Message body
Key Points
 The first line i.e. the Request line specifies the request method i.e. Get or Post.
 The second line specifies the header which indicates the domain name of the server from
where index.htm is retrieved.

HTTP Response
Like HTTP request, HTTP response also has certain structure. HTTP response
contains:
 Status line
 Headers
 Message body

INTERNET ADDRESS

Internet Protocol hierarchy contains several classes of IP Addresses to be used


efficiently in various situations as per the requirement of hosts per network. Broadly,
the IPv4 Addressing system is divided into five classes of IP Addresses. All the five
classes are identified by the first octet of IP Address.
Internet Corporation for Assigned Names and Numbers is responsible for assigning IP addresses.

The first octet referred here is the left most of all. The octets numbered as follows
depicting dotted decimal notation of IP Address −

The number of networks and the number of hosts per class can be derived by this
formula −
When calculating hosts' IP addresses, 2 IP addresses are decreased because they
cannot be assigned to hosts, i.e. the first IP of a network is network number and the
last IP is reserved for Broadcast IP.

Class A Address
The first bit of the first octet is always set to 0 (zero). Thus the first octet ranges from 1
– 127, i.e.

Class A addresses only include IP starting from 1.x.x.x to 126.x.x.x only. The IP range
127.x.x.x is reserved for loopback IP addresses.
The default subnet mask for Class A IP address is 255.0.0.0 which implies that Class A
addressing can have 126 networks (27-2) and 16777214 hosts (224-2).
Class A IP address format is
thus: 0NNNNNNN.HHHHHHHH.HHHHHHHH.HHHHHHHH

Class B Address
An IP address which belongs to class B has the first two bits in the first octet set to 10,
i.e.

Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet mask
for Class B is 255.255.x.x.
Class B has 16384 (214) Network addresses and 65534 (216-2) Host addresses.
Class B IP address format is: 10NNNNNN.NNNNNNNN.HHHHHHHH.HHHHHHHH

Class C Address
The first octet of Class C IP address has its first 3 bits set to 110, that is −
Class C IP addresses range from 192.0.0.x to 223.255.255.x. The default subnet mask
for Class C is 255.255.255.x.
Class C gives 2097152 (221) Network addresses and 254 (28-2) Host addresses.
Class C IP address format is: 110NNNNN.NNNNNNNN.NNNNNNNN.HHHHHHHH

Class D Address
Very first four bits of the first octet in Class D IP addresses are set to 1110, giving a
range of −

Class D has IP address range from 224.0.0.0 to 239.255.255.255. Class D is reserved


for Multicasting. In multicasting data is not destined for a particular host, that is why
there is no need to extract host address from the IP address, and Class D does not
have any subnet mask.

Class E Address
This IP Class is reserved for experimental purposes only for R&D or Study. IP
addresses in this class ranges from 240.0.0.0 to 255.255.255.254. Like Class D, this
class too is not equipped with any subnet mask.
INTERNET ACCESS

Internet Services allows us to access huge amount of information such as text,


graphics, sound and software over the internet. Following diagram shows the four
different categories of Internet Services.

Communication Services
There are various Communication Services available that offer exchange of information with
individuals or groups. The following table gives a brief introduction to these services:

S.N. Service Description

1 Electronic Mail
Used to send electronic message over the internet.

2 Telnet
Used to log on to a remote computer that is attached to internet.

3 Newsgroup
Offers a forum for people to discuss topics of common interests.

4 Internet Relay Chat (IRC)


Allows the people from all over the world to communicate in real time.

5 Mailing Lists
Used to organize group of internet users to share common information through e-mail.

6 Internet Telephony (VoIP)


Allows the internet users to talk across internet to any PC equipped to receive the call.

7 Instant Messaging
Offers real time chat between individuals and group of people. Eg. Yahoo messenger, MSN
messenger.

Information Retrieval Services


There exist several Information retrieval services offering easy access to information present on
the internet. The following table gives a brief introduction to these services:

S.N. Service Description

1 File Transfer Protocol (FTP)


Enable the users to transfer files.

2 Archie
It’s updated database of public FTP sites and their content. It helps to search a file by its name.

3 Gopher
Used to search, retrieve, and display documents on remote sites.

4 Very Easy Rodent Oriented Netwide Index to Computer Achieved (VERONICA)


VERONICA is gopher based resource. It allows access to the information resource stored on
gopher’s servers.

Web Services
Web services allow exchange of information between applications on the web. Using
web services, applications can easily interact with each other.
The web services are offered using concept of Utility Computing.

World Wide Web (WWW)


WWW is also known as W3. It offers a way to access documents spread over the
several servers over the internet. These documents may contain texts, graphics, audio,
video, hyperlinks. The hyperlinks allow the users to navigate between the documents.

Video Conferencing
Video conferencing or Video teleconferencing is a method of communicating by two-
way video and audio transmission with help of telecommunication technologies.
Modes of Video Conferencing

Point-to-Point
This mode of conferencing connects two locations only.
Multi-point
This mode of conferencing connects more than two locations through Multi-point
Control Unit (MCU).

APPLICATIONS

Internet is a system that interconnects the different computer systems across the
world. It uses the Internet protocol suite to link devices located in different corners of
the world.
The Internet system carries an extensive range of information resources and services
including World Wide Web (WWW), telephony, electronic mail, etc. It uses standard
internet protocols, such as TCP/IP and HTTP, etc.
An internal web comprises of all Hypertext Transfer Protocol (HTTP) nodes on a
private network; for example, an organization’s LAN or WAN.

Features of Internet
Let us now discuss the features of Internet. The features are described below −
Accessibility
An Internet is a global service and accessible to all. Today, people located in a remote
part of an island or interior of Africa can also use Internet.
Easy to Use
The software, which is used to access the Internet (web browser), is designed very
simple; therefore, it can be easily learned and used. It is easy to develop.
Interaction with Other Media
Internet service has a high degree of interaction with other media. For example, News
and other magazine, publishing houses have extended their business with the help of
Internet services.
Low Cost
The development and maintenance cost of Internet service are comparatively low.
Extension of Existing IT Technology
This facilitates the sharing of IT technology by multiple users in organizations and even
facilitates other trading partners to use.
Flexibility of Communication
Communication through Internet is flexible enough. It facilitates communication through
text, voice, and video too. These services can be availed at both organizational and
individual levels.
Security
Last but not the least, Internet facility has to a certain extent helped the security system
both at the individual and national level with components such as CCTV camera, etc.

Internet Software
Internet Software comprises of all the tools needed for networking through computer.
Following are a few important components of the Internet Software −

 Transmission Control Protocol/ Internet Protocol (TCP/IP)


 Dialer Software

 Interment Browser

Internet Applications
Internet applications are server-based applications. Following are a few Internet
Applications −

 World Wide Web (WWW)


 Electronic mail (e-mail)

 File Transfer Protocol (FTP)

 Telnet (i.e., log-in to the computer located remotely)

 Internet Relay Chat (IRC) (Real time video chatting)

BASIC CONCEPTS OF OOP


The Object Oriented programming paradigm plays an important role in human-computer
interface. It has different components that take real world objects and perform actions
on them, making live interactions between man and the machine. Following are the
components of OOPS −
1. This paradigm describes a real-life system where interactions are among real objects.
2. It models applications as a group of related objects that interact with each other.
3. The programming entity is modeled as a class that signifies the collection of related real-
world objects.
4. Programming starts with the concept of real-world objects and classes.
5. The application is divided into numerous packages.
6. A package is a collection of classes.
7. A class is an encapsulated group of similar real-world objects.
Objects
Real-world objects share two characteristics − They all have state and behavior. Let us
see the following pictorial example to understand Objects.

In the above diagram, the object ‘Dog’has both state and behavior.
An object stores its information in attributes and discloses its behavior through methods.
Let us now discuss in brief the different components of object oriented programming.
Data Encapsulation
Hiding the implementation details of the class from the user through an object’s
methods is known as data encapsulation. In object oriented programming, it binds the
code and the data together and keeps them safe from outside interference.
Public Interface
The point where the software entities interact with each other either in a single computer
or in a network is known as a public interface. This help in data security. Other objects
can change the state of an object in an interaction by using only those methods that are
exposed to the outer world through a public interface.
Class
A class is a group of objects that have mutual methods. It can be considered as the
blueprint using which objects are created.
Classes being passive do not communicate with each other but are used to instantiate
objects that interact with each other.
Inheritance
Inheritance as in general terms is the process of acquiring properties. In OOP one
object inherits the properties of another object.
Polymorphism
Polymorphism is the process of using same method name by multiple classes and
redefines methods for the derived classes.

DATA TYPES, VARIABLES AND ARRAYS

Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different
data types to variables, you can store integers, decimals, or characters in these
variables.
There are two data types available in Java −

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types


There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.
byte
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50

short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000

long

 Long data type is a 64-bit signed two's complement integer


 Minimum value is -9,223,372,036,854,775,808(-2^63)

 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)

 This type is used when a wider range than int is needed

 Default value is 0L

 Example: long a = 100000L, long b = -200000L

float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f

double
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values, generally the
default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4

boolean

 boolean data type represents one bit of information


 There are only two possible values: true and false

 This data type is used for simple flags that track true/false conditions

 Default value is false

 Example: boolean one = true

char

 char data type is a single 16-bit Unicode character


 Minimum value is '\u0000' (or 0)

 Maximum value is '\uffff' (or 65,535 inclusive)

 Char data type is used to store any character

 Example: char letterA = 'A'

Reference Datatypes
 Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any compatible
type.
 Example: Animal animal = new Animal("giraffe");

Java Literals
A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation.
Literals can be assigned to any primitive type variable. For example −
byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16)
or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these
number systems for literals. For example −
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are

Example
"Hello World"
"two\nlines"
"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char literals as well. They
are −

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)
\s Space (0x20)

\t tab

\" Double quote

\' Single quote

\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Java provides a data structure, the array, which stores a fixed-size sequential


collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same
type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process
arrays using indexed variables.

Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to
accommodate C/C++ programmers.
Example
The following code snippets are examples of this syntax −
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.

Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array
to the variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is,
they start from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList −
double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and
the indices are from 0 to 9.
Processing Arrays
When processing array elements, we often use either for loop or foreach loop
because all of the elements in an array are of the same type and the size of the array is
known.
Example
Here is a complete example showing how to create, initialize, and process arrays −
Live Demo

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This will produce the following result −


Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops


JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index
variable.
Example
The following code displays all the elements in the array myList −
Live Demo

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
System.out.println(element);
}
}
}

This will produce the following result −


Output
1.9
2.9
3.4
3.5

Passing Arrays to Methods


Just as you can pass primitive type values to methods, you can also pass arrays to
methods. For example, the following method displays the elements in an int array −
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

You can invoke it by passing an array. For example, the following statement invokes
the printArray method to display 3, 1, 2, 6, 4, and 2 −
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method


A method may also return an array. For example, the following method returns an array
that is the reversal of another array −
Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++,


j--) {
result[j] = list[i];
}
return result;
}

The Arrays Class


The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all primitive
types.

Sr.No. Method & Description

1
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using
the binary search algorithm. The array must be sorted prior to making this call. This returns
index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point +
1)).

2
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are
considered equal if both arrays contain the same number of elements, and all corresponding
pairs of elements in the two arrays are equal. This returns true if the two arrays are equal.
Same method could be used by all other primitive data types (Byte, short, Int, etc.)

3
public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. The same method
could be used by all other primitive data types (Byte, short, Int, etc.)

4
public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering
of its elements. The same method could be used by all other primitive data types ( Byte, short,
Int, etc.)

Java provides various datatypes to store various data values. It provides 7 primitive
datatypes (stores single values) as listed below −

 boolean − Stores 1-bit value representing true or, false.


 byte − Stores twos compliment integer up to 8 bits.

 char − Stores a Unicode character value up to 16 bits.

 short − Stores an integer value upto 16 bits.

 int − Stores an integer value upto 32 bits.

 long − Stores an integer value upto 64 bits.

 float − Stores a floating point value upto 32bits.

 double − Stores a floating point value up to 64 bits.

TYPE CONVERSION AND CASTING

Type Casting/type conversion


Converting one primitive datatype into another is known as type casting (type
conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening
and, Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In
this case the casting/conversion is done automatically therefore, it is known as implicit
type casting. In this case both datatypes should be compatible with each other.

Example
public class WideningExample {

   public static void main(String args[]){

      char ch = 'C';

      int i = ch;

      System.out.println(i);

   }

Output
Integer value of the given character: 67

Narrowing − Converting a higher datatype to a lower datatype is known as narrowing.


In this case the casting/conversion is not done automatically, you need to convert
explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type
casting. In this case both datatypes need not be compatible with each other.

Example
import java.util.Scanner;

public class NarrowingExample {

   public static void main(String args[]){

      Scanner sc = new Scanner(System.in);

      System.out.println("Enter an integer value: ");

      int i = sc.nextInt();

      char ch = (char) i;
      System.out.println("Character value of the given integer:
"+ch);

   }

Output
Enter an integer value:
67
Character value of the given integer: C

You might also like