- Building Java Programs Pdf Reges Oceanfront Resort Wildwood Crest
- Example Java Programs Pdf
- Building Java Programs Pdf Reges Oceanfront Hotels
- Building Java Programs Pdf Reges Oceanfront Free
Stuart Reges is a principal lecturer at the University of Washington where he teaches computer programming, programming languages, and discrete structures. He is co-author of an introductory Java programming textbook with Marty Stepp titled Building Java Programs: A Back to Basics Approach. UW CSE’s Stuart Reges has won the 2011 University of Washington Distinguished. Authors' web site for Building Java Programs, a textbook designed for use in a first course in computer science. Building Java Programs: A Back to Basics Approach, 4th edition by Stuart Reges and Marty Stepp. Back to Basics in CS1 and CS2, presented at SIGCSE '06 by Stuart Reges. Tags: building java programs 3rd edition, building java programs 3rd edition torrent, building java programs pdf, building java programs 2nd edition pdf, building java programs 3rd edition pdf, building java programs 3rd edition reges, building java programs ebook More books to download: a-table-by-the-window-pdf-9814370.pdf graveyard-girl-pdf. Programming Write a static method named printMultiples that accepts an integer n and an integer m as parameters and that prints a complete line of output reporting the first m multiples of n. EB00K-BUILDING JAVA PROGRAMS: A Back to Basics Approach 4th Edition by Reges - $10.70. EB00K-Building Java Programs: A Back to Basics Approach 4th Edition by Reges Shipping: The eBook Will Be Instantly Delivered To YOU via ebay message and email Works on: Laptops, Desktops, Tablets, Smartphones, Kindle.
1.1 Introduction
This chapter introduces some basic terminology and discusses Java's status as aprogramming language. The chapter closes with a brief look at Java, examininghow to write simple but structured programs that produce output.
1.2 A Brief History of Programming Languages
The first major programming languages were developed in the 1950's and eversince then programmers and computer scientists have fought over which languageis best, a tradition referred to as 'the great language wars.' People becomevery passionate about what they see as the good aspects or bad aspects ofparticular programming languages.
Going back to the 1960's we find four programming languages that had greatinfluence and that are still in use today:
- FORTRAN (short for FORmula TRANslation) was developed for science and engineering applications.
- COBOL (short for COmmon Business Oriented Language) was used for business applications.
- LISP (short for LISt Processing) was the primary language for artificial intelligence research (trying to develop computer programs that reason the way people do).
- BASIC (short for Beginner's All-purpose Symbolic Instruction Code) was designed to be a simple language for novices to master.
As we moved into the 1980's it became increasingly clear that a programmingapproach known as object oriented programming would be very important. Thefirst major object oriented language was known as Smalltalk but it never gainedpopularity in industry. Many people attempted to extend or improve Pascal intothis direction with languages like Modula 2, Modula 3, Oberon, Object Pascaland Delphi, but these languages also never quite took off.
Retrieved June 26, 2015. Archived from on September 29, 2007. American eagle s fsx free. Retrieved June 26, 2015. Archived from on September 29, 2007.
The major success came from a computer scientist named Bjarne Strousstrup whodecided to leverage the popularity of C by adding object oriented features andcalling the superset language C++. C++ has been a major success in industryand continues to be a significant development language. C++ has also been apopular choice for educators.
As we moved into the 1990's the internet and the world wide web emerged as newpriorities. A researcher at Sun Microsystems named Jim Gosling was working ona language for what are known as embedded systems (systems operating onstand-alone devices like cell phones) but Sun realized that his language wouldalso be well-suited to web applications. The rest is history. Java became thelanguage of choice for developing programs known as applets that could beattached to web pages. Since then Java has expanded to become an importantlanguage both in industry and in education. Although C++ came close, Java isthe first language to achieve the nearly universal appeal that Pascal had inthe 1980's as the language of choice for introductory computer science atcolleges and universities.
While all of this has been going on a small but dedicated minority of computerscientists has been exploring ways to extend the ideas from the Lispprogramming language, a style of programming known as functional programming.All sorts of functional programming languages have been developed over theyears including ML, Haskell and Scheme. A small number of schools, inspired bythe curriculum at MIT, developed introductory computer science classes inScheme. The advocates of this approach point out that the simplified syntax ofScheme has allowed them to spend much more time on core computer scienceconcepts rather than fretting over trivial language details, but the approachhas never gained widespread popularity.
Another parallel thread that has developed over the years has been theemergence of scripting languages like Perl, JavaScript and PHP. Theselanguages have their origins in much older text processing languages likeSnobol and Icon that date back to the 1960's but they have become increasinglypopular ever since the creation of the web because they help solve the problemof managing interactive web pages. Newer languages like Python, Ruby and OCamlattempt to fill this niche with languages that are general-purpose enough to beused for many other applications as well.
A close cousin to Java was invented in the late 1990's by MicrosoftCorporation. They set about creating a modern language that would combine thebest aspects of C++ and Java. The resulting language is called C# and looks alot like Java. Since its release Sun has modified Java to give it some of thefeatures of C#. Thus, these two languages are now competing with each other,which is likely to keep them fairly similar.
1.3 Some Basic Terminology
You tell the computer what to do by writing a program.
Program A set of instructions that are to be carried out by a computer. |
The word 'code' describes program fragments ('these four lines of code') or theact of programming ('Let's code this into Java'). Once a program has beenwritten, you can execute it.
Program Execution The act of carrying out the instructions contained in a program. Sip trunk setup trix box manual. The person who originated the call keeps listening to the Music On Hold and the other party doesn’t hear a thing. |
The process of execution is often called running. It can be used as a verb,'When my program runs it does something strange. . .,' or as a noun, 'The lastrun of my program produced these results. . .' Programs collectively are knownas 'software.' The physical devices they run on are collectively known as'hardware.'
At the most basic level, computer programs are expressed as a series of numbersknown as the machine language of the computer. In the early days programmersentered numbers like these directly into the computer. Obviously this is atedious and confusing way to program a computer and we have invented all sortsof mechanisms to simplify this process.
Modern programmers write in what are known as high-level programminglanguages. All of the languages mentioned in the previous section arehigh-level languages. These programs cannot be run directly on a computer.They first have to be translated into a different form by a special programknown as a compiler.
Compiler A program that translates a computer program written in one language into an equivalent program in another language (often, but not always, translating into machine language). |
A compiler that translates directly into machine language creates a programthat can be executed directly on the computer. We refer to such a program asan executable. Most C and C++ compilers create executables. This approachworks well when you know exactly what computer you want your program to executeon. But what if you want to execute a program on many different computers?Using this approach you'd have to have a compiler for each computer and you'dhave to produce a different executable for each.
The designers of Java decided to use a different approach. They cared a lotabout being able to run on many different computers because they wanted to havea language that worked well for the web. People who write applets want thoseprograms to run on many different computers. So instead of compiling intomachine language, Java programs are compiled into what are known as Javabytecodes. These bytecodes represent an intermediate level. They aren't quiteas high-level as Java but they also aren't quite as low-level as machinelanguage. The key thing is that one set of bytecodes can execute on manydifferent machines.
To execute Java bytecodes you need a special program known as an interpreter.
Interpreter A program that dynamically executes programs written in a particular programming language. |
You'll have the right idea if you think about what happens at the UnitedNations. Suppose that someone is speaking in French and you understand onlyEnglish. We work this out by hiring an interpreter who listens to the Frenchand translates into equivalent English for you as its spoken. For Java we havea program that is known as the Java Runtime Environment that is a similar kindof interpreter. The problem is that we have a program file that contains Javabytecodes and a computer that doesn't understand Java bytecodes. So we need aprogram that plays the role of interpreter, reading the bytecodes and givinginstructions to the computer that are equivalent to the bytecodes.
It seems odd to have both a compiler and an interpreter. For example, why havethe interpreter work with Java bytecodes? Why not have it work with theoriginal Java programs? This is one of those goldilocks situations where we'researching for a middle ground that is 'just right.' Java itself is too highlevel but machine code is too low-level. Java bytecodes are in the middle and,therefore, just right.
Remember that the Java designers had as one of their major goals that Javawould run on many different computers. If we compile all the way down to aparticular machine language, then the resulting program will run on just thatcomputer. That's why machine language is too low level. But if we don'tcompile at all, then we have to write a series of interpreters for eachdifferent computer and those interpreters will have to deal with the fullcomplexity of Java. That would discourage people from running Java on theircomputers because they'd have to write complex interpreters that might not runvery quickly.
The goldilocks middle ground is to compile down to Java bytecodes. Thesebytecodes are similar to machine language. In fact, they are the machinelanguage of a theoretical computer known as the Java Virtual Machine or JVM.
Java Virtual Machine (JVM) A theoretical computer whose machine language is the set of Java bytecodes. |
This isn't an actual machine but it's similar to actual machines. By compilingdown to this level, there isn't much work left for the interpreter. That meansthat it becomes a fairly simple matter for people to write a differentinterpreter for every different computer.
Microsoft made a similar choice when they redesigned Windows in the late 1990's(creating a system they refer to as the '.NET framework'). All of the .NETlanguages (including Visual Basic and C#) are compiled into an intermediatestate known as IL (short for 'Intermediate Language') which represents themachine language of a virtual machine. These IL files are very similar to thefiles of Java bytecodes produced by the Java compiler. But instead of using aninterpreter to execute these on specific computers, they write a secondcompiler that converts IL into machine language just before it is executed.These are known as 'Just In Time' or JIT compilers.
1.4 The Programming Environment
You must become familiar with your computer setup before you start programming.Each computer provides a different environment for program development, butthere are some common elements that deserve comment.
The basic unit of storage on most computers is a file. You will create fileswhose contents are Java programs. The standard convention is to use theextension '.java' for these files. The simplest way to create a Java file isto use a simple text editor (e.g., using NotePad on Windows or emacs on unix).Once created, you compile the program to generate Java bytecodes. For example,if have created a program file called Fun.java and you are using the Suncompiler on unix or Windows, you would give a command like the following tocompile it:
The 'javac' command is short for 'Java Compiler.' The compiler creates fileswith the extension '.class' that contain the corresponding Java bytecodes. Inthe example above, if the compiler is able to translate Fun.java intobytecodes, it stores them in a file called Fun.class. You'll find that thisfile isn't in a human readable format, but if you're curious, you can ask thecomputer to show you the bytecodes in a more convenient format. For example,after compiling Fun.java, you can give this command to see it in bytecode formif you are using the Sun tools:
It isn't very easy to read even in this form, but it gives you a sense of whatthe Java bytecodes are all about.
To actually execute your Java program, you have to fire up the Javainterpreter. With the Sun tools, you would say:
This is going to execute the contents of Fun.class, but you don't say the'.class' part when you give this command.
Often programmers use what are known as Integrated Development Environments orIDEs that provide an all-in-one environment for creating, editing, compilingand executing program files. There are many popular commercial IDEs includingVisual Studio, Eclipse, CodeWarrior and JBuilder. There are also IDEsdeveloped specifically for computer science instruction including BlueJ andDrJava. And there are many free IDEs floating around like JCreator and JEdit.Your instructor will tell you what environment you should be using.
Most of the sample programs in this book involve what is called console orterminal interaction. By default, output goes to a particular window known asthe console window and you can also read information from the console, in whichcase the computer will pause and wait for the user to type something before itproceeds with execution. This is an old-fashioned style of interaction, but itis simple. Console programs allow us to have simple interaction, which allowsus to focus our attention and effort on other aspects of the program.
Java was not intended for console programs. It was intended for programs witha modern Graphical User Interface (GUI) that takes advantage of advancedgraphics for drawing and the mouse for user input. Java has extensivelibraries known as AWT and Swing that provide support for GUI programming. Wewill look at a few elements from these libraries, but for the most part wewon't explore GUIs or graphics in this book.
1.5 Some Problem-Solving Terminology
Brian Kernighan, one of the creators of the C programming language, has saidthat, 'Controlling complexity is the essence of computer programming.' Peoplehave only a modest capacity for detail. We can't solve complex problems all atonce. Instead, we structure our problem-solving by dividing the problem intomanageable pieces and conquering each piece individually. We often use theterm 'decomposition' to describe this principle as applied to programming.
Decomposition A separation into discernible parts, each of which is simpler than the whole. |
With older programming languages like Kernighan's C, decomposition involvesdividing a complex task into a set of subtasks. This is very verb or actionoriented, dividing up the overall action into a series of smaller actions.This technique is called procedural decomposition.
Java was designed for a different kind of decomposition that is more noun orobject oriented. Instead of thinking of the problem as a series of actions tobe performed, we think of it as a collection of objects that have to interact.
Building Java Programs Pdf Reges Oceanfront Resort Wildwood Crest
As a computer scientist you should be familiar with both types of problemsolving. This book begins with procedural decomposition and devotes manychapters to mastering various aspects of the procedural approach. Only afteryou have thoroughly practiced procedural programming will we turn our attentionback to object decomposition and object oriented programming.
As an example of procedural decomposition, consider the problem of baking acake. You can divide this problem into the following subproblems.
Each of these four tasks has details associated with it. To make the batter,for example, you:
Thus, you divide the overall task into subtasks and further divide thesesubtasks into smaller subtasks. Eventually, you reach descriptions that are sosimple they require no further explanation (i.e., primitives).
A diagram of this partial solution would look like this:
'Make Cake' is the highest-level operation of all. It is defined in terms offour lower-level operations called 'Make Batter,' 'Bake,' 'Make Frosting,' and'Frost Cake.' The 'Make Batter' operation is defined in terms of evenlower-level operations. I use diagrams like this throughout the book. Theyare called structure diagrams, and are intended to show how a problem is brokendown into subproblems. In this diagram, you can also tell in what orderoperations are performed by reading left to right. That will not be true ofmost structure diagrams. To determine the actual order that sub-programs areperformed, you will usually have to refer to the program itself.
A related set of terms is bottom-up and top-down. To make a cake, you mightstart at the top and reason, 'I can make a cake by first making batter, thenbaking it, then making frosting, and finally putting the frosting on the cake.I could make the batter by first . . .' This is a top-down solution; itstarts at the highest level and proceeds downward. A bottom-up solutioninvolves reasoning like, 'What can I do now? I could put together dryingredients. If I then creamed the butter and sugar, and then beat in eggs,and then mixed in dry ingredients, I'd have some batter. If I then baked thatbatter, I'd have an unfrosted cake. If I then . . .' This is a bottom-upsolution because it starts with low-level operations and puts them together toform higher-level operations.
One final problem solving term has to do with the process of programming.Professional programmers develop programs in stages. Instead of trying toproduce a complete working program all at once, they choose some piece of theproblem to implement first. Then another piece is added and another andanother. The overall program is built up slowly, piece by piece. This processis known as iterative enhancement or stepwise refinement.
Iterative Enhancement The process of producing a program in stages, adding new functionality at each stage. |
1.6 Some Java Terminology
The designers of Java described the language in a report known as the Javawhite paper. They begin by describing the language with a set of buzzwords, as'A simple, object-oriented, network-savvy, interpreted, robust, secure,architecture neutral, portable, high-performance, multithreaded, dynamiclanguage.' Each of these buzzwords represents a design goal for the originallanguage. You can find the complete white paper online if you want to explorethis detail, but I will briefly review some of these terms that are relevant towhat we'll be covering in this book.
Several of these terms relate to the overall goal of allowing Java to run onmany different computers. Section 1.3 describes how being an interpretedlanguage furthers that goal. Keeping it architecture neutral meant that itcould run well on all computers. Keeping it portable meant that programmerswouldn't waste time on machine specific details. The vision was for a languagethat would allow programmers to 'Write once, run everywhere.' Of course, thereality didn't always match the vision and programmers often complained,particularly in the early years, that Java was a 'Write once, debug everywhere'language.
Several other terms involved the goal of having Java work well with the web.That meant it needed to be network-savvy to provide programmers with the toolsthey would need to write web applications. People wouldn't be willing to runweb programs if they couldn't be trusted, so it became important for Java to berobust and secure.
Java was presented as an alternative to C++ and the designers felt it wasimportant to keep the language as simple as possible because C++ was a highlycomplex language. They wanted it to be multithreaded by design versus thesingle-threaded model of C and C++. At the same time, they wanted it to behigh-performance so that people didn't sacrifice performance to get the otherbenefits of Java. Again, the reality didn't always match the vision asprogrammers found that Java had performance problems. It was often very slow.In recent years, though, Java's underlying performance has improved greatly tothe point where Java programs run almost as fast as equivalent C and C++programs.The two final terms from this list are object oriented and dynamic. These arethe terms that we will spend the most time exploring in this book. We will seethat Java programs involve the dynamic interaction of many different kinds ofobjects. It was possible in older languages like C++ to create such programs,but it was clear that objects were an add-on and that you would have to go to agreat deal of trouble to get objects to work well. In Java objects are kingand the designers of the language have made all sorts of choices to make iteasier to create and manipulate objects.
The various objects in a Java program fall into different categories that wecall classes. A class represents a family of similar objects.
Class A category or type of object. |
The various objects of a particular class are known as the instances of thatclass.
Instance An object that belongs to a particular class (an instance of a class). |
This is similar to the way that biologists talk about a species. They look atthe variety of plants and animals that exist in the world and divide them upinto different categories. One category is for humans. There is one categoryto represent the entire species of humans even though there are billions ofindividual members of that one category.
In a similar way, each Java class describes a particular kind of object ofwhich there might be many existing members. For example, Java has a classcalled String that defines a family of objects that store textual information.It is possible to have many String objects in a program. In fact often thereare thousands of String objects interacting in a single program. But there isonly one String class. The various String objects are known as the instancesof the String class.
When we as Java programmers want to request that a certain action be performed,we call what are known as 'methods.'
Method A program unit that represents a particular action or computation. |
Each object has various methods that itcan perform. Other programming languages have referred to these as functionsor procedures. The Smalltalk language referred to them as 'messages' that yousend to objects.
To keep track of particular values and particular objects we will use what areknown as variables. As their name implies, variables can change value as theprogram executes. For example, if we were writing a game playing program wemight have variables to keep track of how many games the user had played andhow many of those games the user had won.
Sometimes we want to use values that we know aren't going to change, in whichcase we use what are called constants instead. Java has a predefined constantcalled Math.PI that represents the value of the mathematical quantity calledpi.
1.7 And Now--Java
It's time to look at a complete Java program. Brian Kernighan and DennisRitchie started a tradition in computer science that when you describe a newprogramming language, you should start with a program that produces a singleline of output with the words 'Hello world.' They included this in a 1978 bookdescribing what was then a fairly new programming language they had createdcalled C. Kernighan and Ritchie and their book 'The C Programming Language'have both been affectionately referred to as 'K&R' ever since.
The hello world tradition has been broken by many authors of Java books becausethe program turns out not to be short and simple when written in Java.
The keyword 'public' indicates that this class is available to anyone to use.The curly braces are used as a grouping mechanism to say that 'everythingdefined inside these braces is part of the public class called Hello.' It mayseem odd to have the opening curly brace at the end of the first line ratherthan on a line by itself. Some people would use this style of indentation forthe program instead:
Inside the Hello class you will find the main method.
Later in this chapter we will examine methods in greater detail, but for nowyou just need to know that every executable Java program needs to have a methodwith this general form:
Most people memorize this as a kind of magical incantation. You want to openthe door to Ali Baba's cave? You say, 'Open sesame.' You want to create anexecutable Java program? You say, 'public static void main(String[] args).' Agroup of Java teachers makes fun of this with a web site calledwww.publicstaticvoidmain.com. Memorizing magical incantations is neversatisfying, especially for computer scientists who like to know everything thatis going on in their programs, but this is a place where Java shows its uglyside and we just have to live with it. Fortunately, by the time you finishthis book, you'll understand every part of this incantation.
Notice that the main method has a set of curly braces of its own. They areagain used for grouping, saying that everything that appears between the bracesis part of the main method. The lines in between the curly braces specify theseries of actions to perform in executing the program. In this case there isjust a single command to produce a line of output with 'Hello world' on it, butconsider the following variation that has three lines of code to be executed inthe main method.
Statement An executable snippet of code that represents a complete command. |
The statements in these programs are all calls on a method known as println.Method calls are just one kind of Java statement.
Now that we have seen an overview, let's examine some of the details of Javaprograms in greater detail.
1.7.1 Identifiers and Keywords
The words used in a Java program are called identifiers. Identifiers muststart with a letter and can then be followed by any number of letters anddigits. The following are legal identifiers.
The following are illegal identifiers.
The Java language specification defines the set of letters to include theunderscore and dollar-sign characters ('_' and '$'), which means that thefollowing are legal identifiers as well.
Java has conventions for capitalization that are followed fairly consistentlyin the Java class libraries. All class names should begin with a capitalletter, as with the Hello, Hello2 and Hello3 classes in the previous section.The names of methods and variables should begin with lowercase letters, as inmethod main. Constant values appear in all uppercase letters, as in theconstant PI that is defined in the Math class. When putting several wordstogether, we capitalize the first letter of each word. This technique does notwork for constants, however, because all letters are supposed to be uppercase.In the case of constants we use underscore characters to separate words.
For example, suppose that you were going to put together the words 'all mychildren' into an identifier. Depending upon what the identifier is used for,you'd turn this into:
- AllMyChildren for a class name (starts with a capital, capitalizes remaining words)
- allMyChildren for a variable or method name (starts with a lowercase letter, capitalizes remaining words)
- ALL_MY_CHILDREN for a constant name (all uppercase separated by underscores)
Example Java Programs Pdf
Don't hesitate to use long identifiers. The more descriptive your names, theeasier it will be for people (including yourself) to read your programs. Longidentifiers are worth the time they take to type. Java's String class, forexample, has a method called compareToIgnoreCase and Java's JButton classincludes constants with names like HORIZONTAL_TEXT_POSITION_CHANGED_PROPERTY.
Java has a set of predefined identifiers called keywords that are reserved fora particular use. As you read this book, you will learn many of these keywordsand what they are used for. You can only use keywords for their intendedpurpose. You must be careful to avoid using these words for definitions thatyou make. For example, if you name a variable or method 'short' or 'try,' thiswill cause a problem, because short and try are reserved keywords. Here is thecomplete list of reserved keywords.
1.7.2 String Literals and Escape Sequences
Suppose that Joe says to Mary, 'Please say your name.' How is she supposed torespond? We expect her to say 'Mary', but she might also say 'Your name.' Thesecond response makes sense if Joe is asking her to literally say the words'your name' versus asking her what her name is.
You will make this distinction often in your Java programs. When you want toinclude some literal text, you put quotation marks around it to form what wecall a string literal, as in the example below. We call this a string becauseyou are stringing together a series of characters.
You use double quotation marks, not single quotation marks. The following isnot a string literal.
But the following is a string literal.
String literals must not span more than one line of a program. The followingis not a string literal.
You can, however, embed what are known as 'escape sequences' in a stringliteral. These are two-character sequences that are used to represent specialcharacters. They all begin with the backslash character ('). For example,you wouldn't normally be able to include the quotation mark itself inside astring, so there is an escape sequence for this. The table below lists some ofthe more common escape sequences.
Sequence | Represents |
---|---|
t | tab character |
n | newline character |
' | quotation mark |
backslash character | |
f | formfeed (go to top of new page) |
Keep in mind that each of these two character sequences actually stands forjust a single character. For example, if you were to execute the followingstatement:
You would get the following output:
The string literal in the println has three escape sequences that are each twocharacters long, but they each produce a single character of output.
Notice that even though you can't have string literals that span multiplelines, you can use the 'n' escape sequence to embed newline characters in astring. This leads to the odd situation where a single println can producemore than one line of output.
For example, if you execute this statement:You will get the following output:This is another programming habit that tends to vary according to taste. Somepeople (including me) find it hard to read string literals that have 'n' inthem, but other people prefer to write fewer lines of code. Once again, youshould make up your own mind about when to use the newline escape sequence.
1.7.3 System.out.println
As you have seen, the main method of a Java program contains a series ofstatements for the computer to carry out. One of the simplest and most commonstatements is to make a call on System.out.println to produce a line of output.This is another magical incantation that people tend to just memorize as if itwere one word. Google lists over 180 thousand web pages that mentionSystem.out.println. But it's worth exploring where the name comes from.
Java uses the dot notation as a way to open up something, as in opening up afolder to see what is inside it. So you might say something likeearth.usa.texas.dallas as a way to say 'start with earth, go inside it to findthe usa, go inside that to find texas and go inside that to find dallas.' Thephrase 'System.out.println' begins with 'System.' What's that? It begins witha capital letter, so it's the name of a class. In Java the System classcontains several useful general-purpose tools. One of those is a variablecalled 'out' which refers to the standard output stream. For interactiveprograms, standard output goes to the console.
To recap, System is the name of a class and System.out is a variable inside theSystem class. So what about the println part? That's a method. The variableSystem.out refers to an object that has a method called println. You'll learnto spot methods because they always have parentheses after them. Theparentheses are used to indicate any arguments being passed to the method. Thesimplest form of the println has no arguments and produces a blank line ofoutput:
You need to include the parentheses even if you don't have anything to putinside them. Notice the semicolon at the end of the line. All statements inJava must be terminated with a semicolon.
More often you use a call on println to produce a line of text:
This statement commands the computer to produce the following line of output.
Each println statement produces a different line of output. These threestatements
will produce these three lines of output:
1.7.4 Punctuation and Simple Program Structure
Consider this program:
Here is a more complicated program example. Notice that it uses two emptyprintln statements to produce blank lines.
1.8 Static Methods
Java is designed for objects and programming in Java usually involvesdecomposing a problem into various objects, each with methods that performparticular tasks. We will see how this works eventually, but for now, we aregoing to explore procedural decomposition. This will allow us to postpone someof Java's details while we learn about programming in general.
The first decomposition construct we will study is known as a static method.
Static Method A unit of procedural decomposition. We typically break a class into several static methods, each of which solve some piece of the overall problem. |
They are called static because they don't require an object. Whenever you seethe keyword 'Static' in Java you know that you are dealing with something thatis associated with the class rather than the instances of the class.
Static Associated with a class rather than the instances of a class. |
It is cumbersome and confusing to have to include the keyword 'static' for eachof these methods, but remember that Java was designed for object orientedprogramming. Without the 'static' keyword, Java assumes that a method isintended for objects. We will see how to define and use object methods laterin the book. For now we will limit ourselves to static methods because eventhough they require a bit more work to declare, they are much easier tounderstand in terms of how they work. To become an effective Java programmeryou should be familiar with both kinds of methods, so it makes sense to startwith the one that is simpler to understand.
You have already seen a static method in the programs we have written calledmain. Recall that the main method has the following form:
After the header you see a series of println statements that make up the bodyof this static method. As in method main, the statements of this method areexecuted in order from first to last when the method is called. Consider thissample program.
Here is a structure diagram that shows which static methods main calls andwhich static methods are called by each of them:
As you can see, this program has three levels of structure, two levels ofdecomposition. The overall task is split into three subtasks. And each ofthose subtasks has two subtasks.
A program with methods has a more complex flow of control than one withoutthem. The rules are still fairly simple, however. When a method is called,the computer executes the statements in the body of that method; then, controlproceeds to the statement after the method call. The main method ofDrawFigures2 first executes the body of method drawDiamond, which executesmethods drawCone and drawV (in that order). When drawDiamond finishesexecuting, control shifts to the next statement in the body of the mainprogram, the call on method drawX.
A complete breakdown of the flow of control from static method to static methodin DrawFigures2 follows.
The order in which you define methods does not have to parallel the order inwhich they are executed. The order of execution is determined by the body ofmethod main and by the bodies of methods called from main. A static methoddeclaration is like a dictionary entry--it defines a word, but it does notspecify how the word will be used. The body of this main says to first executedrawDiamond, then drawX, then drawRocket. This is the order of execution,regardless of the order they were defined in.
Java allows you to define methods in any order you like. I started with mainat the top and worked my way down to lower and lower level methods. This is apopular approach to take, but many people prefer the opposite, having the lowlevel methods first and having main at the end. Java doesn't care what orderyou use, so you can decide for yourself and do what you think is best.
Method structure adds to program readability. A well-structured solution iseasier to comprehend, and the methods themselves become a means of explaining aprogram. Also, programs with methods are more flexible, more easily adapted toa similar but different task. For example, you can take the six methodsdefined in DrawFigures2 and write the following new program to produce a largerand more complex output file. Building static methods to create new commandsincreases your flexibility without adding unnecessary complication.
1.9 Comments and Readability
While static methods address some of the need for explaining how a programworks, they are not enough. The layout of a program can also enhance itsreadability. Java is a free-format language. This means you can put in asmany or as few spaces and blank lines as you like, as long as you put at leastone space or other punctuation mark between words. The following program islegal, but hard to read.
- Put method headers on lines by themselves.
- Put no more than one statement on each line.
- Indent statements inside curly braces by a consistent number of spaces (a common choice is 4 spaces)
- Use blank lines to separate parts of the program (e.g., methods)
Well-written Java programs are often quite readable, but there will still betimes when you will want to include some explanations that are not part of theprogram itself. You can annotate programs by putting comments in them.
There are two comment forms in Java. In the first form you open the commentwith a slash followed by a star and you close it by a star followed by aslash:
You must not put spaces between the slashes and the asterisks:
You can put almost any text you like, including carriage returns inside thecomment characters.
The only thing you aren't allowed to put inside a comment is the comment endcharacter(s). The following is not legal.
You must be very careful to close all of your comments. Consider thefollowing.
This is not a program; it is one long comment. Because the comment on thefirst line is not closed, the entire program is swallowed up.
Java provides a second comment form that helps you to avoid such mistakes. Youcan use two slashes in a row to indicate that everything from that point untilthe end of the line is a comment. For example, you can put a comment after astatement:
Or you can create a one-line comment:
You can also create blocks of such comments:
Some people prefer to use the other comment form in a case like this when youknow you will have multiple lines of text in the comment, but it is safer touse the form above because you don't have to remember to close the comment.Plus, it makes the comment stand out. Again, this is a place where you willhave to decide for yourself which style you prefer.
Don't confuse comments with the text of the println statements. The text ofyour comments will not be displayed as output when the program executes. Thecomments are to help examine and understand the program.
It is a good idea to include comments at the beginning of each class file toindicate what the class does. You might also want to include information aboutwho you are and who your grader is. You should also comment each method toindicate what it does.
Java has a particular style of comments known as Javadoc comments. They have amore complex format to them but they have the advantage that you can use aprogram to extract the comments to make html files suitable for reading with aweb browser.
1.10 Program Errors
In 1949 Maurice Wilkes, an early pioneer of computing, expressed a sentimentthat still rings true today.
As soon as we started programming, we found out to our surprise that it wasn'tas easy to get programs right as we had thought. Debugging had to bediscovered. I can remember the exact instant when I realized that a large partof my life from then on was going to be spent in finding mistakes in my ownprograms.--Maurice Wilkes
You will also have to face this reality as you learn to program. You're goingto make mistakes just like every other programmer in history and you're goingto need strategies for eliminating those mistakes. Fortunately the computeritself can help you with some of the work.Little errors are called bugs. Computer programmers use words like bug-riddenand buggy to describe poorly written programs. The term dates back to an oldstory about a group of programmers couldn't figure out what was wrong withtheir programs, until they opened up the computer and found a moth trappedinside. The process of finding and eliminating bugs from programs is calleddebugging.
Many errors will be caught by the compiler as it attempts to translate yourprogram from Java into bytecodes. Java has rules that determine its syntax orgrammar and the compiler will tell you if you break these rules. Human beingstend to be fairly forgiving. For example, we might find it odd but wegenerally understand Master Yoda when he says, 'Unfortunate that you rushed toface him..that incomplete was your training. Not ready for the burden wereyou.'
The Java compiler will be far less forgiving. If you misplace a singlesemicolon in your program, you can send the compiler into a tail spin ofconfusion. And once confused, the compiler might get very confused. A goodrule of thumb to follow is that the first error reported by the compiler is themost important one to pay attention to. The rest might be the result of thatfirst error. Many programmers don't even bother to look at errors beyond thefirst.
A program that generates compilation errors cannot be executed. If you submityour program to the compiler and have errors reported, you must fix the errorsand resubmit the program to the compiler. You will not be able to proceeduntil your program is free of compilation errors.
The Java compiler will also catch some other minor errors. For example, Javamakes sure that all variables are initialized before they are used. This helpsto achieve the goals of being robust and secure. If Java determines that somevariable might not be initialized, it will tell you about it and will refuse totranslate your program into bytecodes until you fix it.
Once your program compiles properly, it generates a file of Java bytecodes thatcan be executed by the interpreter. This does not mean it is free of errors.You might still have logic errors in your code. A logic error or bug occurswhen you say one thing when you really meant something else. Every programmermakes logic errors, so you will have to learn to deal with them.
Building Java Programs Pdf Reges Oceanfront Hotels
The form that a bug takes will vary a lot. Sometimes your program will make arequest that is clearly illegal, which leads to an execution or runtime error.For example, you are likely to get a 'null pointer exception' when you executesome of your programs. This happens when you tell Java to ask an object to dosomething when there isn't an object to ask. Java is unable to continueexecuting your program, so it generates the exception. The word 'exception' isjust another word for 'error.' In a later chapter we will see how exceptionswork in Java.
There are many other ways that a bug can manifest itself. Your program mightgo into what we call an infinite loop or it might simply behave incorrectly.
1.11 Programming Problems
- Write a program to spell out MISSISSIPPI using block letters like the following:
- Write a program that produces several letters. You should create low-level static methods that write out individual paragraphs and then write high-level static methods that produce letters by combining paragraphs.
- Write a program that produces as output a song. Use static methods for each verse and the refrain.
- Write a program that produces as output the words of 'The Twelve Days of Christmas.' (hint: static methods simplify this task.)