Translate

Search This Blog

Total Pageviews

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, December 13, 2018

Network Programming with Java: The basics

        What Is Network Programming?

A network is a group of two or more computers or other types of electronic devices such as printers that are linked together with a goal to share information.
Each device linked to a network is called a node. A computer that is linked to a network is called a host.
Network programming in Java involves writing Java programs that
facilitate the exchange of information between processes running on different computers on the network.

Java makes it easy to write network programs.
  • Sending a message to a process running on another computer is as simple as writing data to a local file system.
  • Similarly, receiving a message that was sent from a process running in another computer is as simple as reading data from a local file system.
Most of the programs we deal with involve reading and writing data over the network, and they are similar to file I/O. You have to learn about a few new that facilitate the communication between two computers on a network.
You do not need to have advanced level knowledge of networking technologies to understand or write Java programs. Here we cover high-level details of a few concepts that are involved in network communication.

A network can be categorized based on different criteria.
Based on the geographical area that a network is spread over, it is categorized as follows:
When two or more networks are connected using routers (also known as gateways), it is called internetworking, and the resulting combined network is called an internetwork, in short, internet.
The global internetwork, which encompasses all networks in the world connected together, is referred to as the Internet.

Based on the topology (the arrangement of nodes in a network), a network may be categorized as
  • star,
  • tree, 
  • ring, 
  • bus, 
  • hybrid, etc.
Based on the technology a network uses to transmit the data, it can be categorized as
  • Ethernet, 
  • LocalTalk, 
  • Fiber Distributed Data Interface (FDDI), 
  • Token Ring, 
  • Asynchronous Transfer Mode (ATM), etc.
For any details about the different kinds of networks refer to any standard textbook on networks to learn more about networks and network technologies in detail.

Communication between two processes on a computer is simple and it is achieved using InterProcess Communication(IPC) as defined by the operating system.
It is a very tedious task when two processes running on two different computers on an internet need to communicate. You need to consider many aspects of the communication before the such two processes may start communicating. Some of the points that you need to consider are as follows:
  • The two computers may be using different technologies such as different operating systems, different hardware, etc.
  • They may be on two different networks that use different network technologies.
  • They may be separated by many other networks, which may be using different technologies. That is, two computers are not on two networks that are interconnected directly. You need to consider not just two networks, but all networks that the data from one computer must pass to reach another computer.
  • They may be a few miles apart or on other sides of the globe. How do you transmit the information efficiently without worrying about the distance between the two computers?
  • One computer may not understand the information sent by the other computer.
  • The information sent over a network may be duplicated, delayed, or lost. How should the receiver and the sender handle these abnormal situations?
Simply put,
  1. two computers on a network communicate using messages (sequences of 0s and 1s).
  2. There must be well-defined rules to handle the previously mentioned issues (and many more). The set of rules to handle a specific task is known as a protocol. Many types of tasks are involved in handling network communication. There is a protocol defined to handle each specific task. There is a stack of protocols (also called protocol suite) that are used together to handle a network communication.

               Network Protocol Suite

Modern networks are called packet switching networks because they transmit data in chunks called packets.
Each packet is transmitted independent of other packets. This makes it easy to transmit the packets from the same computer to the same destination using different routes. 
However, it may become a problem if a computer sends two packets to a remote computer and the second packet arrives before the first one.
For this reason, each packet also has a packet number along with its destination address. 
There are rules to rearrange the out-of-order arrival of the packets at the destination computer. The following discussion attempts to explain some of the mechanisms that are used to handle packets in a network communication.

Figure 4-1 shows a layered protocol suite called the Internet Reference Model or TCP/IP Layering Model.
This is the most widely used protocol suite. Each layer in the model performs a well-defined task.
The main advantage of having a layered protocol model is that any layer can be changed without affecting others. A new protocol can be added to any layer without changing other layers.


Each layer knows about only the layer immediately above and below it. Each layer has two interfaces—one for the layer above it and one for the layer below it. 
For example, the transport layer has interfaces to the application layer and internet layer. That is, the transport layer knows how to communicate only with the application layer and the internet layer. It knows nothing about the network interface layer or the physical layer.

A user application such as a Java program uses the application layer to communicate to a remote application.
The user application has to specify the protocol that it wants to use to communicate with the remote application. 
A protocol in an application layer defines the rules for formatting messages and associating the meaning to the information contained in the messages such as the message type, describing
whether it is a request or a response, etc.
After the application layer formats the message, it hands over the message to the transport layer.
The examples of protocols in an application layer are
  • Hypertext Transfer Protocol (HTTP), 
  • File Transfer Protocol (FTP), 
  • Gopher, 
  • Telecommunication Network (Telnet), 
  • Simple Mail Transfer Protocol (SMTP), and 
  • Network News Transfer Protocol (NNTP).
The transport layer protocol handles the ways messages are transported from one application on one computer to another application on the remote computer. 
It controls
  • the data flow, 
  • error handling during data transmission, and 
  • connections between two applications.
For example,
  1. a user application may hand over a very large chunk of data to the transport layer to transmit to a remote application. 
  2. The remote computer may not be able to handle that large amount of data at once. It is the responsibility of the transport layer to pass a suitable amount of data at a time to the remote computer, so the remote application can handle the data according to its capacity. 
  3. The data passed to the remote computer over a network may be lost on its way due to various reasons. 
  4. It is the responsibility of the transport layer to re-transmit the lost data. Note that the application layer passes data to be transmitted to the transport layer only once. It is the transport layer (not the application layer) that keeps track of the delivered and the lost data during a transmission. 
  5. There may be multiple applications running, all of which use different protocols and exchange information with different remote applications. 
  6. It is the responsibility of the transport layer to hand over messages sent to a remote application correctly. For example, you may be browsing the Internet using the HTTP protocol from one remote web server and downloading a file using the FTP protocol from another FTP server. Your computer is receiving messages from two remote computers and they are meant for two different applications running on your computer—one web browser to receive HTTP data and one FTP application to receive FTP data.
  7.  It is the responsibility of the transport layer to pass the incoming data to the appropriate application.
You can see how different layers of the protocol suite play different roles in data transmission over the network. Depending on the transport layer protocol being used, the transport layer adds relevant information to the message and passes it to the next layer, which is the internet layer.
The examples of protocols used in the transport layer are
  • Transmission Control Protocol (TCP), 
  • User Datagram Protocol (UDP), and 
  • Stream Control Transmission Protocol (SCTP).
The internet layer accepts the messages from the transport layer and prepares a packet suitable for sending over the internet. It includes the Internet Protocol (IP).
The packet prepared by the IP is also known as an IP datagram.
It consists of a header and a data area, apart from other pieces of information.
The header contains
  • the sender’s IP address, 
  • destination IP address, 
  • time to live (TTL, which an integer), 
  • a header checksum, and many other pieces of information specified in the protocol.
The IP prepares the message into datagrams, which are ready to be transmitted over the internet.
  1. The TTL in the IP datagram header specifies how long, in terms of the number of routers, an IP datagram can keep traveling before it needs to be discarded. Its size is one byte and its value could be between 1 and 255. When an IP datagram reaches a router in its route to the destination, the router decrements the TTL value by 1. If the decremented value is zero, the router discards the datagram and 
  2. sends an error message back to the sender using Internet Control Message Protocol (ICMP). 
  3. If the TTL value is still a positive number, the router forwards the datagram to the next router.
The IP uses an address scheme, which assigns a unique address to each computer. The address is called an IP address. The internet layer hands over the IP datagram to the next layer, which is the network interface layer. The examples of protocols in an internet layer are
  1. Internet Protocol (IP), 
  2. Internet Control Message Protocol (ICMP), 
  3. Internet Group Management Protocol (IGMP), and 
  4. Internet Protocol Security (IPsec).
The network interface layer prepares a packet to be transmitted on the network. The packet is called a frame. The network interface layer sits just on top of the physical layer, which involves the hardware.

Note that the IP layer uses the IP address to identify the destination on a network.
An IP address is a virtual address, which is completely maintained in software. 
The hardware is unaware of the IP address and it does not know how to transmit a frame using an IP address. The hardware must be given the hardware address, also called Media Access Control (MAC) address, of the destination that it needs to transmit the frame to.
This layer resolves the destination hardware address from the IP address and places it in the frame header. It hands over the frame to the physical layer.
The examples of protocols in a network interface layer are
  1. Open Shortest Path First (OSPF), 
  2. Point-to-Point Protocol (PPP), 
  3. Point-to-Point Tunneling Protocol (PPTP), and
  4. Layer 2 Tunneling Protocol (L2TP).
The physical layer consists of the hardware. It is responsible for converting the bits of information into signals and transmitting the signal over the wire.

■Tip
Packet is a generic term that is used to mean an independent chunk of data in network programming.
Each layer of protocol also uses a specific term to mean the packet it deals with. For example,
  • a packet is called a segment in the TCP layer; 
  • it is called a datagram in the IP layer; 
  • it is called a frame in the network interface and physical layers. 
Each layer adds a header (sometimes also a trailer) to the packet it receives from the layer before it, while preparing the packet to be transmitted over the network.
Each layer performs the reverse action when it receives a packet from the layer below it. It removes the header from the packet; performs some
actions, if needed; and hands over the packet to the layer above it.
When a packet sent by an application reaches the remote computer, it has to pass through the same layer of protocols in the reverse order. Each layer will remove its header, perform some actions, and pass the packet to the layer immediately above it. Finally, the packet reaches the remote application in the
same format it started from the application on the sender’s computer.
Figure below  shows the transmission of packets from the sender and the receiver computer. P1, P2, P3, and P4 are the packets in different formats of the same data. A protocol layer at a destination receives the same packet from the layer immediately below it, which the same protocol layer had passed to the layer immediately below it on the sender’s computer.

  
                  IP Addressing Scheme

IP uses a unique address, called an IP address, to route an IP datagram to the destination.
An IP address uniquely identifies a connection between a computer and a router. 
Normally, it is understood that an IP address identifies a computer. However, it should be emphasized that it identifies a connection between a computer and a router, not just a computer. A router is also assigned an IP address.
A computer can be connected to multiple networks using multiple routers and each connection between the computer and the router will have a unique IP address. In such cases, the computer will be assigned multiple IP addresses and the computer is known as multi-homed
Multi-homing increases the availability of the network connection to a computer. If one network connection fails, the computer can use other available network connections.

An IP address contains two parts
  1. a network identifier (prefix) and 
  2. a host identifier (suffix).
The prefix identifies a network on the Internet uniquely; the suffix identifies a host uniquely within that network. It is possible for two hosts to have IP addresses with the same suffix as long as they have a different prefix.

There are two versions of Internet Protocol—IPv4 (or simply IP) and IPv6, version 4 and version 6.
IPv6 is also known as Internet Protocol next generation (IPng).

Note that there is no IPv5. When IP was in its full swing of popularity, it was at version 4. Before IPng was assigned a version number 6, version 5 was already assigned to another protocol called Internet Stream Protocol (ST).
Both IPv4 and IPv6 use an IP address to identify a host on a network. However, the addressing schemes in the two versions differ significantly.

Since an IP address must be unique, its assignment is controlled by an organization called Internet Assigned Numbers Authority (IANA).
  1. IANA assigns a unique address to each network that belongs to an organization. 
  2. The organization uses the network address and a unique number to form a unique IP address for each host on the network. 
  3. IANA divides the IP address allocations to five Regional Internet Registry(RIR) organizations, which allocate IP addresses in specific regions as listed in Table 4-1. You can find more information on how to get a network address in your area from IANA at www.iana.com.


                 IPv4 Addressing Scheme

IPv4 (or simply IP) uses a 32-bit number to represent an IP address. An IP address contains two parts—a prefix and a suffix. The prefix identifies a network and the suffix identifies a host on the network, as shown in Figure.

It is not easy for humans to remember a 32-bit number in binary format. IPv4 allows you to work with an alternate form using four decimal numbers. Each decimal number is in the range from 0 to 255. The decimal number format of IPv4 is called dotted decimal format because a dot is used to separate two decimal numbers. Each decimal number represents the value contained in 8 bits of the 32-bit number. For example, an IPv4 address of
 11000000 10101000 00000001 11100111 
in thhttps://en.wikipedia.org/wiki/Dot-decimal_notatione binary format can be represented as 192.168.1.231 in the dotted decimal format.


How do you know that 192.168.1 represents a prefix in an IPv4 address 192.168.1.231? A rule governs the value of a prefix and a suffix in an IPv4.
How does an IPv4 address divide its 32 bits between a prefix and a suffix? IPv4 address space is divided in five categories called network classes, named A, B, C, D, and E.
A class type defines how many bits of the 32 bits will be used to represent the network address part of an IP address.
The leading bit (or bits) in the prefix defines the class of the IP address. This is also known as a self-identifying or classful IP address because you can tell which class it belongs to by looking at the IP address.
The table lists the five network classes and their characteristics in IPv4. The leading bits in an IP address identify the class of the network.
For example,
  1. if an IP address looks like 0XXX, where XXX is the last 31 bits of the 32 bits, it belongs to the class A network;  There can be only 128(2^7) networks of class A type and each network can have 16777214((2^31/128)-2) hosts. The number of hosts that a class A network can have is very big and it is very unlikely that a network will have that many hosts.
  2. if an IP address looks like 110XXX, where XXX is the last 29 bits of 32 bits, it belongs to the class C network. In a class C type of network, the maximum number of hosts that a network can have is limited to 254(2^8 - 2).


[to be continued...]

Friday, November 30, 2018

Object-Oriented Software Development

Have you ever wondered why some organizations refer to the group responsible for computers and information systems as “data processing”?
  1. Structured programming and structured design (which grew out of structured programming) understand the mission of software as that of processing data.
  2. Structured programming and structured design are focused on the changes programs make in transforming input data to output data, seeing computer programs as action-oriented.
The early name of the computer programming profession—data processing—reflects this procedural perspective.

Object-oriented programming and design emphasize the view that software systems model the real world. 
Objects within an object-oriented system may still transform input data to output data, but this is not the only possible way to organize an object-oriented program.
From an object-oriented perspective, the group responsible for computers and information systems might aptly be named the Business Object Portfolio (BOP) group. Their function, is to assemble and maintain a portfolio of objects that model their organization’s processes.
If  you’re therefore less than enthusiastic about the prospect of being called a BOPper, never fear. You can choose to work in the health care industry, in which case you may come to be known HOPper (for “Health care Object Portfolio”) or
MOPper (for “Medical Object Portfolio”). That’s decidedly better than working in law enforcement, where you might come to be known as a COPper (for “Crime Object Portfolio”), or working in agriculture, where you might come to be known as a CROPper (for “Crop Rotation Object Portfolio”).


                            Procedural Programs

Computer programs, whether designed based on structured design or object-oriented design, usually model some process that exists in the real world.
A payroll program, for example, models the manual process that a real business goes through when it pays its employees. In a small business, the process might work something like this:
  1. Get the list of employees from the file over by the coffee machine.
  2. Get the federal and state withholding schedules out of the bottom right drawer of the desk.
  3. Get the general ledger from the supervisor’s office.
  4. For each employee on the list, do the following:
  5.   (4.1). Get the amount of pay from the employee record.
  6.   (4.2).  Calculate the amount of taxes due, based on the  withholding schedules.
  7.   (4.3). Calculate the net pay by subtracting the deductions and withholding from the gross pay.
  8.   (4.4). Prepare the check.
  9.   (4.5). Record the check in the general ledger.
  10. (5). Take the stack of checks to the boss to be signed.
  11. (6). Mail the checks at the post office.
  12. (7). Return the general ledger, withholding schedules, and list of employees to their regular places.
Most of these operations could be performed by a computer, though the computer wouldn’t do them exactly the same way the payroll clerk would.
  1. When written as part of a computer program, the steps necessary to carry out a task are called a process
  2. Each step within a process is known as a procedure
  3. When a procedure is long or complex, it may consist of several steps, called subprocedures or simply procedures.
  4. Procedures are the blocks used to build structured programs.
A typical payroll program, for example, would contain procedures to
  • open and read the files, 
  • perform the payroll calculations, and 
  • print the checks.
  • By using direct deposit, the program might even “sign” and “mail” the checks.
A procedural payroll program is structured like

Each of the boxes in Figure represents a procedure that carries out a series of steps.
Each procedure
  1. receives input data, 
  2. processes the data, and 
  3. transmits the results of its processing, either to a subsequent procedure or to a human.
Data is fed to the procedures in much the same way that raw materials are fed to an assembly line—except the procedures produce information rather than cars or toasters.
A useful property of structured programs is that the “shape” of the solution (that is, the program) closely models the shape of the problem. 
Each of the procedures of the structured program in Figure relates to one or more of the steps in the process for manually preparing payroll checks.
Structured programs are designed by means of procedural decomposition
Using procedural decomposition, a designer studies the problem and attempts to break it apart by identifying a series of actions that solve it.
When a designer is asked to automate an existing business process, the design process is often simple because procedural decomposition is easy to perform. The designer merely uses the steps of the manual process to identify the actions that the program must perform. Because these steps have successfully kept the business from devolving into chaos, using them as the basis for a computer program may be less risky that trying an entirely new series of steps.
Think again, though, about what would happen to the manual payroll process in your imaginary business if it grew to 20,000 employees instead of 20.
  • The employee file could no longer be kept in the filing cabinet over by the coffee machine. 
  • Fred, the part-time bookkeeper, could no longer finish his work each Tuesday afternoon. 
  • And, most importantly, the boss, who previously signed every check and would likely notice if Ms.Smallie’s check had $1,000 written on it, instead of $100, could no longer sign each check personally—there simply wouldn’t be enough remaining time to properly watch over the business.
When businesses grow, they change their structure to handle the added complexity caused by their growth. Finance departments, vice-presidents, controllers, and auditors are added because the simple structure that worked fine for a 20-person company is no longer adequate.
Computer programs can suffer from a similar malady. The  procedural paradigm (paradigm is just a fancy word for pattern) works fine for automating routine office processes, like preparing payroll checks. But it fails to offer sufficient structure when applied to many other kinds of problems, such as simulations and interactive environments.

If you’ve been around a while, you might remember when the main job of computer programmers and designers was writing programs that solved “assembly-line” problems like
  • payroll, 
  • batch accounting, and 
  • monthly invoicing.
Things are different today.
  • Instead of being assigned to write a data-processing program to tally the month-end statements, a bank programmer is more likely to be responsible for writing code to control the ATM or the bank’s new World Wide Web site. 
  • A programmer for a stock broker might design automatic trading programs instead of a simple client billing application.
  • Such interactive or “reactive” programs are much more complex than traditional data-processing applications, because the flow of control is no longer linear. Data doesn’t come in at the start of the program, flow through a number of predefined procedures, and exit at the end, relaxed and refreshed. 
  • In a reactive program, the procedure DoThingC() might be called first, second, last, or not at all—unlike the procedural program where DoThingC() always follows DoThingA() and DoThingB().
Look back at Figure What does it look like? A pyramid, right? The pyramid structure occurs because of the hierarchical nature of control in the program.
ReadEmployeeRecord() relies on the fact that ProcessPayroll() has already performed the OpenEmployeeFile() process. The data and the environment required by ReadEmployeeRecord() are available only because the OpenEmployeeFile() procedure has been called first.
If you attempt to write an interactive program that uses procedures as its basic building block, however, the program structure no longer resembles a neat pyramid. Instead, it begins to look like a dense web of interconnections.

If you remember your first programming class, this might set off a light bulb.
  1. Before the advent of structured programming, back in the days of “iron men,” when “big-iron” was not merely metaphorical, computer programs were largely monolithic—they had no procedures at all. Thus, when a programmer needed to execute a piece of code in another part of the program, an unconditional branch was used; such branches were called gotos. As programs got larger, the typical path of program execution began to resemble a large web. Such code became known as spaghetti code, code that was difficult or impossible to understand and thus difficult or impossible to maintain, fix, or change. The underlying problem was that programs were organized as a collection of source statements. Too many “blocks” (that is, source statements) were required to build large programs. 
  2. To solve this problem, structured programming introduced the procedure as a second, larger organizing unit. Source statements were used to build procedures, but procedures (not source statements) were used to build programs. Thus, the number of blocks required to build a program decreased, reducing the complexity of the program.

                  Object-Oriented Programs

Object-oriented programming attacks the complexity of today’s programs in a similar fashion. By grouping procedures into still larger organizing units called objects, programs require fewer blocks and are, therefore, simpler.

Studying object-oriented programming, it’s hard not to notice the fact that different folks have very different views when it comes to OOP.
Reading various OOP books and papers, it almost seems that people are talking about entirely different things.
When you finally cut through all the rhetoric, though, there are two points of view:
  1. the revolutionary: The advocate of the revolutionary view loudly proclaims that OOP is so different from traditional programming that you have to learn programming over again from scratch.
  2. the evolutionary: The evolutionists, in contrast, say that OOP is really just new packaging of old concepts. Perhaps there’s some truth, as well as some error, in each of these views.


The evolutionists are correct when they assert that it is possible to write clear, well-commented, understandable code in a procedural language, and that it is possible to write incomprehensible, unmaintainable code in an object-oriented language.
The evolutionist generally fails to recognize, however, that an OOP program is organized in a fundamentally different manner than a procedural program.

The revolutionist is right in pointing out that the OOP design process uses different tools and different types of abstraction, and that no amount of functional decomposition will ever yield an object-oriented program.
The revolutionist overestimates, perhaps, the value of such an object-oriented design when weighed against factors of clarity and understandability.
A well-designed and implemented procedural program is definitely to be preferred over a poorly conceived and written OOP program. OOP and object-oriented languages provide tools to express ideas clearly, but are not instant, automatic panaceas.
Five fundamental concepts govern object-oriented programs:
  • Objects
  • Classes
  • Encapsulation
  • Inheritance
  • Polymorphism

                      What Are Objects?

Just as procedures are used to build structured programs, objects are used to build object-oriented programs.
An object-oriented program is a collection of objects that are organized for, and cooperate toward, the accomplishment of some goal. 
Every object:
  • Contains data. The data stores information that describes the state of the object.
  • Has a set of defined behaviors. These behaviors are the things that the object “knows” how to do and are triggered by sending the object a message. 
  • Has an individual identity. This makes it possible to distinguish one object from another, just as it’s possible to distinguish one program variable from another.
Like the records or structures used in procedural programs, objects contain data. In this sense, an object looks very much like one of the employee records that would be used in the payroll program. An object’s data is used to represent the object’s state. For example, data within an employee object might indicate whether an employee is full-time or part-time, hourly or salaried.

Unlike the employee record within a procedural program, however, an employee object can also contain operations. These operations may be used to read or change the object’s data.
In this sense, an object acts like a small “mini-program” that carries its own data around on its back
If you want to do something to an object, or want to know something about it, you “ask it” to perform one of its operations. In object-oriented parlance, you send it a message.
In response, it performs some behavior.

The second characteristic of an object, then, is that it has some built-in behavior: An  employee object may know how to tell you its salary, or how to print itself out to a mailing-address label.
The third characteristic of an object is that every object has a unique identity. This doesn’t mean that every object necessarily has an ID number, or a “primary key” like you find in relational databases. Objects are very much like program variables in a procedural language. 
The integer variables i and j may have exactly the same value—say 3—and yet they are distinct variables, stored at different locations within the computer’s memory.
Changing the value of i to 4, for example, does not change the value of j.
Similarly, two employee objects that represent the identical twins who work in shipping, Fred and Ned, may have the same data contents, yet still be distinct objects.

Much, but not all, of the terminology used in object-oriented programming is the same from programming language to programming language. However, knowing about the differences in terminology might help you avoid some confusion when you find yourself “talking objects” to a Smalltalk or Object Pascal or C++ programmer.
In Java, the operations of an object or class are called methods, just as in Smalltalk.
C++ programmers call methods member functions.
While Smalltalk programmers always speak of sending a message, C++ programmers tend to refer to calling a member function.
Java programmers tend to split the difference, and speak either of  sending a message to an object, or calling an object’s method, depending on whether it is the sender or the recipient of the message that is the focus of discussion.




[to be continued...]

Monday, November 26, 2018

Java beginner4:Void Methods

So far as beginners we’ve only written short programs that have a single class and a single method (main). Now I’ll show you how to organize longer programs into multiple methods and classes and also present the Math class, which provides methods for common mathematical operations.


                                    Math Methods

In mathematics, you have probably seen functions like sin and log, and you have
learned to evaluate expressions like sin(Ï€/2) and log(1/x) .
  1. First, you evaluate the expression in parentheses, which is called the argument of the function. 
  2. Then you can evaluate the function itself, maybe by punching it into a calculator.
This process can be applied repeatedly to evaluate more complex expressions like log(1/ sin (Ï€/2) ).
First we evaluate the argument of the innermost function, then evaluate the function itself, and so on.

The Java library includes a Math class that provides common mathematical operations. Math is in the java.lang package, so you don’t have to import it. You can use, or invoke, Math methods like this:

double root = Math.sqrt(17.0);
double angle = 1.5;
double height = Math.sin(angle);

The first line sets root to the square root of 17. The third line finds the sine of 1.5
(the value of angle).
Arguments of the trigonometric functions—sin, cos, and tan—should be in radians.
To convert from degrees to radians, you can divide by 180 and multiply by Ï€. 
Conveniently, the Math class provides a constant double named PI that contains an approximation of π:

double degrees = 90;
double angle = degrees / 180.0 * Math.PI;

  1. Notice that PI is in capital letters (as all constants per convention in Java). Java(is case sensitive) does not recognize Pi, pi, or pie. 
  2. Also, PI is the name of a variable(constant), not a method, so it doesn’t have parentheses. 
  3. The same is true for the constant Math.E, which approximates Euler’s number.
Converting to and from radians is a common operation, so the Math class provides methods that do it for you.

double radians = Math.toRadians(180.0);
double degrees = Math.toDegrees(Math.PI);


Another useful method is round, which rounds a floating-point value(double) to the nearest integer and returns a long. A long is like an int, but bigger.
  1. More specifically, an int uses 32 bits(4 bytes); the largest value it can hold is 2^31 − 1, which is about 2 billion. 
  2. A long uses 64 bits(8 bytes), so the largest value is 2^63 − 1, which is about 9 quintillion.

long x = Math.round(Math.PI * 20.0);

The result is 63 (rounded up from 62.8319).

Take a minute to read the documentation for these and other methods in the Math class.
The easiest way to find documentation for Java classes is to do a web search for “Java” and the name of the class.

                             Composition Revisited

Just as with mathematical functions, Java methods can be composed. That means you can use one expression as part of another. For example, you can use any expression as an argument to a method:

double x = Math.cos(angle + Math.PI / 2.0);

This statement divides Math.PI by two, adds the result to angle, and computes the cosine of the sum.

You can also take the result of one method and pass it as an argument to another:

double x = Math.exp(Math.log(10.0));

In Java, the log method always uses base e. So this statement finds the log base e of 10, and then raises e to that power. The result gets assigned to x.

Some math methods take more than one argument. For example, Math.pow takes two arguments and raises the first to the power of the second. This line of code assigns the value 1024.0 to the variable x:

double x = Math.pow(2.0, 10.0);

When using Math methods, it is a common error to forget the Math. For example, if you try to invoke pow(2.0, 10.0), you get an error message like:
File: Test.java [line: 5]
Error: cannot find symbol
    symbol: method pow(double,double)
    location: class Test
The message “cannot find symbol” is confusing, but the last line provides a useful hint. The compiler is looking for pow (definition) in the same class where it is used, which is Test. If you don’t specify a class name, the compiler looks in the current class.


                              Adding New Methods

You have probably guessed by now that you can define more than one method in a class. Here’s an example:

public class NewLine {
    
    public static void newLine() {
        System.out.println();
    }
    
    public static void main(String[] args) {
        System.out.println("First line.");
        newLine();
        System.out.println("Second line.");
    }
    
}

The name of the class is NewLine. By Java's convention, class names begin with a capital letter. NewLine contains two methods, newLine() and main().
Remember that Java is case-sensitive, so NewLine and newLine are not the same.
Method names should begin with a lowercase letter and use “camel case”, which is a cute name for jammingWordsTogetherLikeThis. You can use any name you want for methods, except main or any of the Java keywords.
  • newLine and main are public, which means they can be invoked from other classes.
  • They are both static, but we can’t explain what that means yet.
  • And they are both void, which means that they don’t yield a result (unlike the Math methods, for example).
  • The parentheses after the method name contain a list of variables, called parameters,where the method stores its arguments. main has a single parameter, called args, which has type String[]. That means that whoever invokes main must provide an array of strings
Since newLine has no parameters, it requires no arguments, as shown when it is
invoked in main. And because newLine is in the same class as main, we don’t have to specify the class name.
The output of this program is:
First line.
Second line.
Notice the extra space between the lines. If we wanted more space between them, we could invoke the same method repeatedly:

public static void main(String[] args) {
    
    System.out.println("First line.");
    newLine();
    newLine();
    newLine();
    System.out.println("Second line.");
    
}

Or we could write a new method that displays three blank lines:

public static void threeLine() {
    
    newLine();
    newLine();
    newLine();
    
}



public static void main(String[] args) {
    
    System.out.println("First line.");
    threeLine();
    System.out.println("Second line.");
    
}

  1. You can invoke the same method more than once, and 
  2. you can have one method invoke another.
In this example, main invokes threeLine, and threeLine invokes newLine.

Beginners often wonder why it is worth the trouble to create new methods. There are many reasons, but this example demonstrates a few of them:
  • Creating a new method gives you an opportunity to give a name to a group of statements, which makes code easier to read and understand.
  • Introducing new methods can make a program smaller by eliminating repetitive code. For example, to display nine consecutive new lines, you could invoke threeLine three times.
  • A common problem solving technique is to break tasks down into sub-problems. Methods allow you to focus on each sub-problem in isolation, and then compose them into a complete solution.

                                   Flow of Execution

Pulling together the code from the previous section, the complete program looks like this:

public class NewLine {
    
    public static void newLine() {
        System.out.println();
    }
    
    public static void threeLine() {
        newLine();
        newLine();
        newLine();
    }
    
    public static void main(String[] args) {
        System.out.println("First line.");
        threeLine();
        System.out.println("Second line.");
    }
}

When you look at a class definition that contains several methods, it is tempting to read it from top to bottom. But that is likely to be confusing, because that is not the flow of execution of the program.
Execution always begins at the first statement of main(), regardless of where it is in the source file. 
Statements are executed
  1. one at a time, in order, until you reach a method invocation, which you can think of as a detour. 
  2. Instead of going to the next main()'s statement, you jump to the first line of the invoked method, 
  3. execute all the statements there, and then come back in main() and pick up exactly where you left off.
That sounds simple enough, but remember that one method can invoke another one.
In the middle of main(),
  1. we go off to execute the statements in threeLine. While we are executing threeLine, 
  2. we go off to execute newLine(). 
  3. Then newLine() invokes println(), which causes yet another detour. Fortunately, Java is good at keeping track of which methods are running. So when println() completes, 
  4. it picks up where it left off in newLine(); when newLine completes, 
  5. it goes back to threeLine, and when threeLine completes, 
  6. it gets back to main().
In summary, when you read a program, don’t read from top to bottom. Instead, follow the flow of execution.


                            Parameters and Arguments

Some of the methods we have used require arguments, which are the values you provide when you invoke the method. For example,
  1. to find the sine of a number, you have to provide the number, so the methode sin takes a double as an argument. 
  2. To display a message, you have to provide the message, so the methode println takes a String.
When you use a method, you provide the arguments (called also actual parameters). When you define(write) a method, you name the parameters (called also formal parameters).
The parameter list indicates what arguments are required. The following class shows an example:

public class PrintTwice {
    
    public static void printTwice(String s) {
        System.out.println(s);
        System.out.println(s);
    }
    
    public static void main(String[] args) {
        printTwice("Don't make me say this twice!");
    }
    
}

  • printTwice() has a parameter named s with type String. 
  • When we invoke(call) printTwice(), we have to provide an argument with type String.
  • Before the method executes, the argument gets assigned to the parameter. In this example, the argument "Don't make me say this twice!" gets assigned to the parameter s. This process is called parameter passing because the value gets passed from outside the method to the inside.
An argument can be any kind of expression, so if you have a String variable, you can use it as an argument:

String argument = "Never say never.";
printTwice(argument);

The value you provide as an argument must have the same(or a compatible) type as the parameter. For example, if you try:

printTwice(17);  // syntax error

You will get an error message like this:
File: Test.java [line: 10]
Error: method printTwice in class Test cannot be applied
            to given types;
required: java.lang.String
found: int
reason: actual argument int cannot be converted to
             java.lang.String by method invocation conversion
Sometimes Java can convert an argument from one type to another automatically(that's called implicit conversion).
For example, Math.sqrt() requires a double, but if you invoke Math.sqrt(25), the integer value 25 is automatically converted to the floating-point value 25.0. But in the case of printTwice(), Java can’t (or won’t) convert the integer 17 to a String.

Parameters(they're also considered as local variables) and other variables only exist inside their own methods. Inside main(), there is no such thing as s. If you try to use it there, you’ll get a compiler error. Similarly, inside printTwice() there is no such thing as argument. That variable belongs to main().

Because variables only exist inside the methods where they are defined, they are often called local variables.


                               Multiple Parameters

Here is an example of a method that takes two parameters:

public static void printTime(int hour, int minute) {
    System.out.print(hour);
    System.out.print(":");
    System.out.println(minute);
}

In the parameter list, it may be tempting to write:

public static void printTime(int hour, minute) {
    ...

But that format (without the second int) is only legal for variable declarations. In
parameter lists, you need to specify the type of each variable separately.

To invoke this method, we have to provide two integers as arguments:

int hour = 11;
int minute = 59;
printTime(hour, minute);

A common error is to declare the types of the arguments, like this:

int hour = 11;
int minute = 59;
printTime(int hour, int minute);

That’s a syntax error; the compiler sees int hour and int minute as variable declarations, not expressions.
You wouldn’t declare the types of the arguments if they were simply integers:

printTime(int 11, int 59);  // syntax error


                                    Stack Diagrams

Pulling together the code fragments from the previous section, here is a complete class definition:

public class PrintTime {
    
    public static void printTime(int hour, int minute) {
        System.out.print(hour);
        System.out.print(":");
        System.out.println(minute);
    }
    
    public static void main(String[] args) {
        int hour = 11;
        int minute = 59;
        printTime(hour, minute);
    }
    
}

printTime() has two parameters, named hour and minute. And main() has two variables, also named hour and minute.
Although they have the same names, these variables are not the same. 
hour in printTime() and hour in main() refer to different storage locations, and they can have different values.
For example, you could invoke printTime() like this:

int hour = 11;
int minute = 59;
printTime(hour + 1, 0);

Before the method is invoked, Java evaluates the arguments; in this example, the
results are 12 and 0. Then it assigns those values to the parameters. Inside printTime(), the value of hour is 12, not 11, and the value of minute is 0, not 59. Furthermore, if printTime() modifies one of its parameters, that change has no effect on the variables in main.

One way to keep track of everything is to draw a stack diagram, which is a state diagram that shows method invocations. For each method there is a box called a frame that contains the method’s parameters and variables. The name of the method appears outside the frame; the variables and parameters appear inside.
As with state diagrams, stack diagrams show variables and methods at a particular point in time. Figure below is a stack diagram at the beginning of the printTime() method.



                            Writing Documentation

As you benefit from reading good documentation, you should “pay it forward” by
writing good documentation.
A nice feature of the Java language is the ability to embed documentation in your source code. That way, you can write it as you go, and as things change, it is easier to keep the documentation consistent with the code.
If you include documentation in your source code, you can extract it automatically, and generate well-formatted HTML, using a tool called Javadoc. This tool is included in standard Java development environments, and it is widely used. In fact, the online documentation of the Java libraries is generated by Javadoc.

Javadoc scans your source files looking for specially-formatted documentation comments, also known as “Javadoc comments”. They begin with /** (two stars) and end with */ (one star). Anything in between is considered part of the documentation.

Here’s a class definition with two Javadoc comments, one for the class and one for the main method:

/**
* Example program that demonstrates print vs println.
*/
public class Goodbye {

    /**
    * Prints a greeting.
    */
    public static void main(String[] args) {
        System.out.print("Goodbye, "); // note the space
        System.out.println("cruel world");
    }
}

The class comment explains the purpose of the class. The method comment explains what the method does.

Notice that this example also includes an inline comment, beginning with //. In general, inline comments are short phrases that help explain complex parts of a program.
They are intended for other programmers reading and maintaining the source code.

In contrast, Javadoc comments are longer, usually complete sentences. They explain what each method does, but they omit details about how the method works. And they are intended for people who will use the methods without looking at the source code.
Appropriate comments and documentation are essential for making source code
readable.
And remember that the person most likely to read your code in the future, and appreciate good documentation, is you.

                             Exercises

Exercise 4-1.
The point of this exercise is to practice reading code and to make sure that you
understand the flow of execution through a program with multiple methods.
  1. What is the output of the following program? Be precise about where there are spaces and where there are newlines.Hint: Start by describing in words what ping and baffle do when they are invoked. 
  2. Draw a stack diagram that shows the state of the program the first time ping is invoked.
  3. What happens if you invoke baffle(); at the end of the ping method? (We will see why in the next post.)

public static void zoop() {
    baffle();
    System.out.print("You wugga ");
    baffle();
}

public static void main(String[] args) {
    System.out.print("No, I ");
    zoop();
    System.out.print("I ");
    baffle();
}
public static void baffle() {
    System.out.print("wug");
    ping();
}

public static void ping() {
    System.out.println(".");
}

Exercise 4-2.
The point of this exercise is to make sure you understand how to write and invoke methods that take parameters.
  1. Write the first line of a method named zool that takes three parameters: an int and two Strings.
  2. Write a line of code that calls zool, passing as arguments the value 11, the name of your first pet, and the name of the street you grew up on.

Exercise 4-3.
The purpose of this exercise is to take code from a previous exercise and encapsulate it in a method that takes parameters. You should start with a working solution to Exercise 2-2.
  1. Write a method called printAmerican that takes the day, date, month and year as parameters and that displays them in American format.
  2. Test your method by invoking it from main and passing appropriate arguments. The output should look something like this (except that the date might be different): Saturday, July 22, 2015
  3. Once you have debugged printAmerican, write another method called printEuropean that displays the date in European format.

Resources