This forum is in archive mode. You will not be able to post new content.

Author Topic: Multi Part Java Course  (Read 3568 times)

0 Members and 1 Guest are viewing this topic.

SoulSaber1

  • Guest
Multi Part Java Course
« on: October 31, 2011, 10:21:14 PM »
 I take no credit for the creation of this. Up to date (mostly). All credit to Alan Young, and wherever he got his sources. Enjoy.
Chapter 1: The Way of the program   The goal of this class, is to teach you to think like a computer scientist. I like the way computer scientists think because they combine some of the best features of Mathematics, Engineering, and Natural Science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.
 The single most important skill for a computer scientist is problem-solving. By that I mean the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. That’s why this chapter is called “The way of the program.”
 On one level, you will be learning to program, which is a useful skill by itself. On another level you will use programming as a means to an end. As we go along, that end will become clearer.  1.1 What is a programming language?  The programming language you will be learning is Java, which is relatively new (Sun released the first version in May, 1995). Java is an example of a high-level language; other high-level languages you might have heard of are Pascal, C, C++ and FORTRAN.
 As you might infer from the name “high-level language,” there are also low-level languages, sometimes referred to as machine language or assembly lan- guage. Loosely-speaking, computers can only execute programs written in low-level languages. Thus, programs written in a high-level language have to be translated before they can run. This translation takes some time, which is a small disadvantage of high-level languages.
 But the advantages are enormous. First, it is much easier to program in a high-level language; by “easier” I mean that the program takes less time to write, it’s shorter and easier to read, and it’s more likely to be correct. Secondly, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can only run on one kind of computer, and have to be rewritten to run on another.
 Due to these advantages, almost all programs are written in high-level languages. Low-level languages are only used for a few special applications.
 There are two ways to translate a program; interpreting or compiling. An interpreter is a program that reads a high-level program and does what it says. In effect, it translates the program line-by-line, alternately reading lines and carrying out commands.
A compiler is a program that reads a high-level program and translates it all at once, before executing any of the commands. Often you compile the program as a separate step, and then execute the compiled code later. In this case, the high-level program is called the source code, and the translated program is called the object code or the executable.
 As an example, suppose you write a program in JAVA. You might use a text editor to write the program (a text editor is a simple word processor). When the program is finished, you might save it in a file named program.java, where “program” is an arbitrary name you make up, and the suffix .java is a convention that indicates that the file contains JAVA source code.
 The Java language is unusual because it is both compiled and interpreted. Instead of translating Java programs into machine language, the Java compiler generates Java byte code. Byte code is easy (and fast) to interpret, like machine language, but it is also portable, like a high-level language. Thus, it is possible to compile a Java program on one machine, transfer the byte code to another machine over a network, and then interpret the byte code on the other machine. This ability is one of the advantages of Java over many other high-level languages.
Although this process may seem complicated, in most programming environments (sometimes called development environments), these steps are automated for you. Usually you will only have to write a program and press a button or type a single command to compile and run it. On the other hand, it is useful to know what the steps are that are happening in the background, so that if something goes wrong you can figure out what it is.
  1.2 What is a program?  A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, like solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, like searching and replacing text in a document or (strangely enough) compiling a program.
 The instructions, which we will call statements, look different in different programming languages, but there are a few basic operations most languages can perform:
  input: Get data from the keyboard, or a file, or some other device.
 output: Display data on the screen or send data to a file or other device.
 math: Perform basic mathematical operations like addition and multiplication.
 testing: Check for certain conditions and execute the appropriate sequence of statements.
 repetition: Perform some action repeatedly, usually with some variation.
   That’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of statements that perform these operations. Thus, one way to describe programming is the process of breaking a large, complex task up into smaller and smaller subtasks until eventually the subtasks are simple enough to be performed with one of these basic operations.
  1.3 What is debugging?  Programming is a complex process, and since it is done by human beings, it often leads to errors. For whimsical reasons, programming errors are called bugs and the process of tracking them down and correcting them is called debugging.
 There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly.
 1.3.1 Compile-time errors  The compiler can only translate a program if the program is syntactically correct; otherwise, the compilation fails and you will not be able to run your program. Syntax refers to the structure of your program and the rules about that structure.
 For example, in English, a sentence must begin with a capital letter and end with a period. this sentence contains a syntax error. So does this one
 For most readers, a few syntax errors are not a significant problem, which is why we can read the poetry of e e cummings without spewing error messages.
 Compilers are not so forgiving. If there is a single syntax error anywhere in your program, the compiler will print an error message and quit, and you will not be able to run your program.
 To make matters worse, there are more syntax rules in Java than there are in English, and the error messages you get from the compiler are often not very helpful. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though, you will make fewer errors and find them faster.
 1.3.2 Run-time errors  The second type of error is a run-time error, so-called because the error does not appear until you run the program. In Java, run-time errors occur when the interpreter is running the byte code and something goes wrong.
 The good news for now is that Java tends to be a safe language, which means that run-time errors are rare, especially for the simple sorts of programs we will be writing for the next few weeks.
 Later on in the semester, you will probably start to see more run-time errors, especially when we start talking about objects and references (Chapter 8). In Java, run-time errors are called exceptions, and in most environments they appear as windows or dialog boxes that contain information about what happened and what the program was doing when it happened. This information is useful for debugging.
 1.3.3 Logic errors and semantics  The third type of error is the logical or semantic error. If there is a logical error in your program, it will compile and run successfully, in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.
 The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying logical errors can be tricky, since it requires you to work backwards by looking at the output of the program and trying to figure out what it is doing.
 1.3.4 Experimental debugging  One of the most important skills you will acquire in this class is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.
 In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that lead to the results you see.
 Debugging is also like an experimental science. Once you have an idea what is going wrong, you modify your program and try again. If your hypothesis was correct, then you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, “When you have eliminated the impossible, whatever remains, however improbable, must be the truth.” (from A. Conan Doyle’s The Sign of Four).
 For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should always start with a working program that does something, and make small modifications, debugging them as you go, so that you always have a working program. For example, Linux is an operating system that contains thousands of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, “One of Linus’s earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux” (from The Linux Users’ Guide Beta Version 1).
 In later chapters I will make more suggestions about debugging and other programming practices.
  1.4 Formal and natural languages  Natural languages are the languages that people speak, like English, Spanish, and French. They were not designed by people (although people try to impose some order on them); they evolved naturally.
 Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly:
 Programming languages are formal languages that have been designed to express computations.   As I mentioned before, formal languages tend to have strict rules about syntax. For example, 3 + 3 = 6 is a syntactically correct mathematical statement, but 3 = +6$ is not.
 Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, like words and numbers and chemical elements. One of the problems with 3=+6$ is that $ is not a legal token in mathematics (at least as far as I know).
 The second type of syntax rule pertains to the structure of a statement; that is, the way the tokens are arranged. The statement 3=+6$ is structurally illegal, because you can’t have a plus sign immediately after an equals sign. Similarly, molecular formulas have to have subscripts after the element name, not before.
 When you read a sentence in English or a statement in a formal language, you have to figure out what the structure of the sentence is (although in a natural language you do this unconsciously). This process is called parsing.
 For example, when you hear the sentence, “The other shoe fell,” you understand that “the other shoe” is the subject and “fell” is the verb. Once you have parsed a sentence, you can figure out what it means, that is, the semantics of the sentence. Assuming that you know what a shoe is, and what it means to fall, you will understand the general implication of this sentence.
 Although formal and natural languages have many features in common—tokens, structure, syntax and semantics—there are many differences.
  ambiguity: Natural languages are full of ambiguity, which people deal with by using contextual clues and other information. Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context.

redundancy: In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.

literalness: Natural languages are full of idiom and metaphor. If I say, "The other shoe fell," there is probably no shoe and nothing falling. Formal languages mean exactly what they say.   People who grow up speaking a natural language (everyone) often have a hard time adjusting to formal languages. In some ways the difference between formal and natural language is like the difference between poetry and prose, but more so:
  Poetry: Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate.

Prose: The literal meaning of words is more important and the structure contributes more meaning. Prose is more amenable to analysis than poetry, but still often ambiguous.

Programs: The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.   Here are some suggestions for reading programs (and other formal languages). First, remember that formal languages are much more dense than natural languages, so it takes longer to read them. Also, the structure is very important, so it is usually not a good idea to read from top to bottom, left to right. Instead, learn to parse the program in your head, identifying the tokens and interpreting the structure. Finally, remember that the details matter. Little things like spelling errors and bad punctuation, which you can get away with in natural languages, can make a big difference in a formal language.  1.5 The first program  Traditionally the first program people write in a new language is called “Hello, World.” because all it does is display the words “Hello, World.” In Java, this program looks like this:
  ?
123456class Hello {    // main: generate some simple output    public static void main (String[] args) {        System.out.println ("Hello, world.");    }}
*double click anywhere in the code box to select all the code for copying.   Some people judge the quality of a programming language by the simplicity of the “Hello, World.” program. By this standard, Java does not do very well. Even the simplest program contains a number of features that are hard to explain to beginning programmers. We are going to ignore a lot of them for now, but I will explain a few.
 The class name in the example is Hello. In the third line, you should ignore the words public static void for now, but notice the word main. main is a special name that indicates the place in the program where execution begins. When the program runs, it starts by executing the first statement in main and it continues, in order, until it gets to the last statement, and then it quits.
 There is no limit to the number of statements that can be in main, but the example contains only one. It is a print statement, meaning that it prints a message on the screen. It is a bit confusing that “print” sometimes means “display something on the screen,” and sometimes means “send something to the printer.” In this book I won’t say much about sending things to the printer; we’ll do all our printing on the screen.
 The statement that prints things on the screen is System.out.println, and the thing between the parentheses is what will get printed. At the end of the statement there is a semi-colon (;), which is required at the end of every statement.
 There are a few other things you should notice about the syntax of this program. First, Java uses squiggly-braces ({ and }) to group things together. The outermost squiggly-braces (lines 1 and 6) contain the class definition, and the inner braces (lines 3 and 5) contain the definition of main.
 Also, notice that line 2 begins with //. This indicates that this line contains a comment, which is a bit of English text that you can put in the middle of a program, usually to explain what the program does. When the compiler sees a //, it ignores everything from there until the end of the line.

Part 2 to follow soon (hopefully!).
 
« Last Edit: October 31, 2011, 11:09:17 PM by Kulverstukas »

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: Multi Part Java Course
« Reply #1 on: October 31, 2011, 11:10:22 PM »
Nice. Maybe you could format it a bit and make it readable?
Also don't use the images from that Dodea website. Prompts for a log in every time you load this page.

SoulSaber1

  • Guest
Re: Multi Part Java Course
« Reply #2 on: November 01, 2011, 07:23:10 AM »
duely noted. sorry about that  :P  will get the next segment up in a few hours (in the proper formating lol)

Offline theellimist

  • Knight
  • **
  • Posts: 371
  • Cookies: 17
    • View Profile
    • TheEllimist's Game
Re: Multi Part Java Course
« Reply #3 on: November 01, 2011, 08:15:47 AM »
Yeah break it up into chunks or paragraphs or something, make it a little easier to read. Btw, nice profile picture :)

SoulSaber1

  • Guest
Re: Multi Part Java Course
« Reply #4 on: November 01, 2011, 11:09:27 AM »
Hows this? And thanks. (sorry if its off, i'm posting this fast in class. im not supposed to be on this site ;) Part 3 to follow
 
Chapter 2: Variables and operators
2.1 More printing
As I mentioned in the last chapter, you can put as many  statements as you want in main. For example, to print more than one line:

1 class Hello {
2   // main: generate some simple output
3    public static void main (String[] args) {
4        System.out.println ("Hello, world.");       //print one line
5        System.out.println ("How are you?");        //print another
6    }
7 }

The result is:

1  Hello, world.
2  How are you?

Also, as you can see, it is legal to put comments at the end of a line, as well as on a line by themselves.
The phrases that appear in quotation marks are called strings, because they are made up of a sequence (string) of letters. Actually, strings can contain any combination of letters, numbers, punctuation marks, and other special characters.
println is short for "print line," because after each line it adds a special character, called a newline, that causes the cursor to move to the next line of the display. The next time println is invoked, the new text appears on the next line.
Often it is useful to display the output from multiple print statements all on one line. You can do this with the print command, which does not advance the cursor to the next line after it runs:

1 class Hello {
2    // main: generate some simple output
3    public static void main (String[] args) {
4        System.out.print ("Goodbye, ");
5        System.out.println ("cruel world!");
6    }
7 }
 
The result is:
     1  Goodbye, cruel world!

In this case the output appears on a single line. Notice that there is a space between the word "Goodbye" and the second quotation mark. This space appears in the output, so it affects the behavior of the program.

2.2 Variables
One of the most powerful features of a programming language is the ability to manipulate  variables. A variable is a named location that stores a  value. Values are things that can be printed and stored and (as we'll see later) operated on. The strings we have been printing ("Hello, World.", "Goodbye, ", etc.) are values.
In order to store a value, you have to create a variable. Since the values we want to store are strings, we will declare that the new variable is a string:

1 ...
2String fred;
3 ...

This statement is a  declaration, because it declares that the variable named fred has the  type String. There is an expected style in naming variables which is covered in the style section of this chapter. Each variable has a type that determines what kind of values it can store. For example, the int type can store integers, and it will probably come as no surprise that the String type can store strings.
You will notice that some types begin with a capital letter and some with lowercase. We will learn the significance of this distinction later, but for now you should take care to get it right. There is no such type as Int or string, and the compiler will object if you try to make one up.
To create an integer variable, the syntax is int bob;, where bob is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:

1  ...
2 String  firstName;
3 String  lastName;
4 int     hour, minute;
5 ...

you could probably make a good guess at what values would be stored in them. This example also demonstrates the syntax for declaring multiple variables with the same type: hour and second are both integers (int type).

2.3 Assignment
Now that we have created some variables, we would like to store values in them. We do that with an  assignment statement.

1 ...
2 fred    = "Hello.";     // give fred the value "Hello."
3 hour    = 11;           // assign the value 11 to hour
4 minute  = 59;           // set minute to 59
5 ...

This example shows three assignments, and the comments show three different ways people sometimes talk about assignment statements. The vocabulary can be confusing here, but the idea is straightforward:
 
 
  • When you declare a variable, you create a named storage location.
  • When you make an assignment to a variable, you give it a value.
As a general rule, a variable has to have the same type as the value you assign it. You cannot store a string in minute or an integer in fred.
On the other hand, that rule can be confusing, because there are many ways that you can convert values from one type to another, and Java sometimes converts things automatically. So for now you should remember the general rule, and we'll talk about special cases later.
Another source of confusion is that some strings look like integers, but they are not. For example, fred can contain the string "123", which is made up of the characters 1, 2 and 3, but that is not the same thing as the number 123.

1 ...
2 fred = "123";       // legal
3 fred = 123;         // not legal
4 ...

2.4 Printing variables
You can print the value of a variable using the same commands we used to print Strings.
     
1 class Hello {
2    public static void main (String[] args) {
3        String firstLine;
4        firstLine = "Hello, again!";
5        System.out.println (firstLine);
6    }
7 }

The result is:

     1  Hello, again!

This program creates a variable named firstLine on line 3, assigns it the value "Hello, again!" on line 4 and then prints that value on line 5. When we talk about "printing a variable," we mean printing the value of the variable. To print the name of a variable, you have to put it in quotes. For example: System.out.println ("firstLine");
If you want to get a little tricky, you could write
 
1  ...
2 String firstLine;
3 firstLine = "Hello, again!";
4 System.out.print ("The value of firstLine is ");
5 System.out.println (firstLine);
6 ...

Output:

     1  The value of firstLine is Hello, again!

I am pleased to report that the syntax for printing a variable is the same regardless of the variable's type.
1 ...
2 int hour, minute;
3 hour    = 11;
4 minute  = 59;
5 System.out.print ("The current time is ");
6 System.out.print (hour);
7 System.out.print (":");
8 System.out.print (minute);
9 System.out.println (".");
10 ...

The output of this program is

     1  The current time is 11:59.

WARNING: It is common practice to use several print commands followed by a println, in order to put multiple values on the same line. But you have to be careful to remember the println at the end. In many environments, the output from print is stored without being displayed until the println command is invoked, at which point the entire line is displayed at once. If you omit println, the program may terminate without ever displaying the stored output!

2.5 Keywords
A few sections ago, I said that you can make up any name you want for your variables, but that's not quite true. There are certain words that are reserved in Java because they are used by the compiler to parse the structure of your program, and if you use them as variable names, it will get confused. These words, called  keywords, include public, class, void, int, and many more.

The complete list:
     abstract  default  if  private  this   boolean  do  implements  protected  throw   break  double  import  public  throws   byte  else  instanceOf  return  transient   case  extends  int  short  try   catch  final  interface  static  void   char  finally  long  strictfp  volatile   class  float  native  super  while   const  for  new  switch    continue  goto  package  synchronized

Rather than memorize the list, I would suggest that you take advantage of a feature provided in many Java development environments: code highlighting. As you type, different parts of your program should appear in different colors. For example, keywords might be blue, strings red, and other code black. If you type a variable name and it turns blue, watch out! You might get some strange behavior from the compiler.

2.6 Operators
  Operators are special symbols that are used to represent simple computations like addition and multiplication. Most of the operators in Java do exactly what you would expect them to do, because they are common mathematical symbols. For example, the operator for adding two integers is +. The following are all legal Java  expressions whose meaning is more or less obvious:

1+1     hour-1     hour*60 + minute     minute/60

Expressions can contain both variable names and numbers. In each case the name of the variable is replaced with its value before the computation is performed.
Addition, subtraction and multiplication all do what you expect, but you might be surprised by division. For example, the following program:

1 ...
2 int hour, minute;
3 hour    = 11;
4 minute  = 59;
5 System.out.print ("Number of minutes since midnight: ");
6 System.out.println (hour*60 + minute);
7 System.out.print ("Fraction of the hour that has passed: ");
8 System.out.println (minute/60);
9 ...

The output of this program is

1 Number of minutes since midnight: 719
2 Fraction of the hour that has passed: 0

The first line is what we expected, but the second line is odd. The value of the variable minute is 59, and 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is that Java is performing integer division.
When both of the  operands are integers (operands are the things operators operate on), the result must also be an integer, and by convention integer division always rounds down, even in cases like this where the next integer is so close.
A possible alternative in this case is to calculate a percentage rather than a fraction:
 
1  ...
2 System.out.print ("Percentage of the hour that has passed: ");
3 System.out.println (minute*100/60);
4 ...

The result is:

     1  Percentage of the hour that has passed: 98

Again the result is rounded down, but at least now the answer is approximately correct. In order to get an even more accurate answer, we could use a different type of variable, called floating-point, that is capable of storing fractional values. We'll get to that in the next chapter.

2.7 Order of operators
When more than one operator appears in an expression the order of evaluation depends on the rules of  precedence. A complete explanation of precedence can get complicated, but just to get you started:
 
 
  • Multiplication and division take precedence (happen before) addition and subtraction. So 2*3-1 yields 5, not 4, and 2/3-1 yields -1, not 1 (remember that in integer division 2/3 is 0).
  • If the operators have the same precedence they are evaluated from left to right. So in the expression minute*100/60, the multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had gone from right to left, the result would be 59*1 which is 59, which is wrong.
  • Any time you want to override the rules of precedence (or you are not sure what they are) you can use parentheses. Expressions in parentheses are evaluated first, so 2 * (3-1) is 4. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it doesn't change the result.
2.8 Operators for Strings
In general you cannot perform mathematical operations on Strings, even if the strings look like numbers. The following are illegal (if we know that fred has type String)
fred - 1     "Hello"/123     fred * "Hello"
By the way, can you tell by looking at those expressions whether fred is an integer or a string? Nope. The only way to tell the type of a variable is to look at the place where it is declared.
Interestingly, the + operator does work with Strings, although it does not do exactly what you might expect. For Strings, the + operator represents  concatenation, which means joining up the two operands by linking them end-to-end. So "Hello, " + "world." yields the string "Hello, world." and fred + "ism" adds the suffix ism to the end of whatever fred is, which is often handy for naming new forms of bigotry.

1  ...
2 String firstName;           //variable declaration
3 firstName = "Jason";        //variable assignment
4 System.out.println ("Hello, again " + firstName + "!");
5 System.out.println ();      //this prints a blank line
6 System.out.println ("This is your computer speaking");
7 ...
 
The result is:
 
1 Hello, again Jason!
2
3 This is your computer speaking

2.9 Composition
So far we have looked at the elements of a programming language-variables, expressions, and statements-in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, we know how to multiply numbers and we know how to print; it turns out we can do both at the same time:

1 ...
2 System.out.println (17 * 3);
3 ...
 
Actually, I shouldn't say "at the same time," since in reality the multiplication has to happen before the printing, but the point is that any expression, involving numbers, strings, and variables, can be used inside a print statement. We've already seen one example:

1 ...
2 System.out.println (hour*60 + minute);
3 ...
 
But you can also put arbitrary expressions on the right-hand side of an assignment statement:

1  ...
2 int percentage;
3 percentage = (minute * 100) / 60;
4 ...
 
This ability may not seem so impressive now, but we will see other examples where  composition makes it possible to express complex computations neatly and concisely.
WARNING: There are limits on where you can use certain expressions; most notably, the left-hand side of an assignment statement has to be a variable name, not an expression. That's because the left side indicates the storage location where the result will go. Expressions do not represent storage locations, only values. So the following is illegal: minute+1 = hour;.

2.10 Code style
At the end of each chapter, I will go over the specific code styles presented in the chapter. It is important that you adhere to the styles presented because you WILL be graded on them. Coding in a specific style increases its readability, which is important when I try to grade your assignments.

     3. Class names start with a capital letter with each additional word capitalized.        class Hello {
class PointFactory {    Common practice in the Java development community and also the type naming convention used by Sun for the Java core packages.
 
     4. Variable names must start with lower case letter with each additional word capitalized. Variable names should quickly identify what type and value is stored.   
     line, audioSystem, lastName, phoneNumber    Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line;
 
     24. Abbreviations in names should be avoided.        classAverage;               // NOT: classAvg;    Reduces confusion
 
     34. File content must be kept within 80 columns.    In NetBeans, the 80 column suggested limit is represented with the vertical red line. 80 columns is the common dimension for editors, terminal emulators, printers and debuggers, and files that are shared between several developers should keep within these constraints. It improves readability when unintentional line breaks are avoided when passing a file between programmers.
 
     61. Basic indentation should be 4.        public static void main (String[] args) {
    String firstLine;    Indentation is used to emphasize the logical structure of the code. Sun recommendation on this point is 4 spaces (Default in NetBeans).
 
     62. Block layout should be as illustrated        
    public static void main (String[] args) {
    String firstName = "Gary";
    System.out.println(firstName);
}
 
     73.
- Operators should be surrounded by a space character.
- Java reserved words should be followed by a space character.
- Commas should be followed by a space character.
- Colons should be surrounded by space character.
- Semicolons in for statements should be followed by a space character.
   
     a = (b + c) * d;                // NOT: a=(b+c)*d
 
while (true) {                  // NOT: while(true){
    ...
 
doSomething(a, b, c, d);        // NOT: doSomething(a,b,c,d);
 
case 100 :                      // NOT: case 100:
 
for (i = 0; i < 10; i++) {      // NOT: for(i=0;i<10;i++){
    ...    Enhances readability. The variables are easier to spot from the types by alignment.
 
     77. Variables in declarations should be aligned left.     
     TextFile    file;
int         nPoints;
double      x, y;    Enhances readability. The variables are easier to spot from the types by alignment.
 
     82. There should be a space after the comment identifier.     
     // This is a comment    NOT: //This is a comment
 
/**                     NOT: /**
 * This is a javadoc          *This is a javadoc
 * comment                    *comment
 */                           */    Improves readability by making the text stand out.
 
     83. Use // for all non-JavaDoc comments, including multi-line comments.    
     // Comment spanning
// more than one line.    Since multilevel Java commenting is not supported, using // comments ensure that it is always possible to comment out entire sections of a file using /* */ for debugging purposes etc.
 
     84. Comments should be indented relative to their position in the code if they are not at the end of a statements line     
     public static void main (String[] args) {
    //comment is aligned with the statement below
    String firstName = "Gary";    This is to avoid that the comments break the logical structure of the program.
« Last Edit: November 01, 2011, 11:20:00 AM by SoulSaber1 »

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: Multi Part Java Course
« Reply #5 on: November 02, 2011, 09:23:06 AM »
I see that you are not here anymore, SoulSaber1. But I still have to say, that your formatting (also in the second chapter) defeats the purpose of a lot of examples shown there. Have you even read it?

Example:
Quote
62. Block layout should be as illustrated        
    public static void main (String[] args) {
    String firstName = "Gary";
    System.out.println(firstName);
}
Quote
61. Basic indentation should be 4.        public static void main (String[] args) {
    String firstLine;    Indentation is used to emphasize the logical structure of the code. Sun recommendation on this point is 4 spaces (Default in NetBeans).

The next thing is (i don't know whose fault this is) that a lot of the conventions stated in the last post are not used in the examples.

In my opinion your way of presenting the course doesn't show much respect to the author.

The course is educationally well done, which earns my respect. But it has inaccuracies that should be corrected. Since the author isn't here to correct it, it wouldn't make much sense to list them, I guess.

Edit: I just read that you are still here under a different name.
« Last Edit: November 02, 2011, 09:35:07 AM by Deque »

Offline Live Wire

  • Knight
  • **
  • Posts: 189
  • Cookies: 4
  • Up on your Net
    • View Profile
Re: Multi Part Java Course
« Reply #6 on: November 02, 2011, 01:09:29 PM »
Yeah sorry. I only have access to this from school, and only for a certain period of time. I'm trying to clean it up as much as possible without having my teacher get suspicious, but I guess I will have to check more :( sorry. Once it gets through indentation though, and into actual coding, it will get much better. Part 3 soon. Thanks for the advice
"There is no right or wrong, there is only fun and boring."

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: Multi Part Java Course
« Reply #7 on: November 02, 2011, 02:31:05 PM »
Yeah sorry. I only have access to this from school, and only for a certain period of time. I'm trying to clean it up as much as possible without having my teacher get suspicious, but I guess I will have to check more :( sorry. Once it gets through indentation though, and into actual coding, it will get much better. Part 3 soon. Thanks for the advice
Why are you worried that your teacher will see it? lol not like she/he would get here... and if it did, what would she/he do? :D
NOTHING. I host material I get from school on my website - so what.

Offline Live Wire

  • Knight
  • **
  • Posts: 189
  • Cookies: 4
  • Up on your Net
    • View Profile
Re: Multi Part Java Course
« Reply #8 on: November 02, 2011, 05:58:11 PM »
Lets just say I already have a history with this teacher. Same one who ratted me out for using a proxy server to access classified files my freshman year. For some reason I got detention, threatened suspension, and my comp right suspended for a week. Maybe they take it more seriously cause im at a US army installation overseas. anyway, she has always watched me more closely, and the school admin hates me for making a botnet last year, so if they see me on any hacking site, im screwed :) part three coming soon!
"There is no right or wrong, there is only fun and boring."

Offline Live Wire

  • Knight
  • **
  • Posts: 189
  • Cookies: 4
  • Up on your Net
    • View Profile
Re: Multi Part Java Course
« Reply #9 on: November 03, 2011, 11:12:33 AM »
Part 3 section 1. I take no credit, I only pass on knowledge. All credit to Allan Young, Brian Barnes, and their sources. Sorry if indentation is incorrect, thats my fault :(

Chapter 3: Methods
3.1 Floating-point

In the last chapter we had some problems dealing with numbers that were not integers. We worked around the problem by measuring percentages instead of fractions, but a more general solution is to use  floating-point numbers, which can represent fractions as well as integers. In Java, the floating-point type is called double.
You can create floating-point variables and assign values to them using the same syntax we used for the other types. For example:

1...
2double pi;
3pi = 3.14159;
4...
   
It is also legal to declare a variable and assign a value to it at the same time:

1...
2 int x        = 1;
3 String empty = "";
4 double pi    = 3.14159;
5...   

In fact, this syntax is quite common. A combined declaration and assignment is sometimes called an  initialization.
Although floating-point numbers are useful, they are often a source of confusion because there seems to be an overlap between integers and floating-point numbers. For example, if you have the value 1, is that an integer, a floating-point number, or both?
Strictly speaking, Java distinguishes the integer value 1 from the floating-point value 1.0, even though they seem to be the same number. They belong to different types, and strictly speaking, you are not allowed to make assignments between types. We will reference the following code in the next few paragraphs.
1 ...
2 int x    = 1.1;         //illegal expression
3 double y = 1;           //y = 1.0 technically legal
4 double y = 1 / 3;       //y = 0.0 technically legal with unexpected

 results
 
double y = 1.0 / 3.0;   //y = 0.33333 legal with expected results

Line 2 is illegal because the variable on the left is an int and the value on the right is a double. But it is easy to forget this rule, especially because there are places where Java will automatically convert from one type to another.
For example, line 3 should technically not be legal, but Java allows it by converting the int to a double automatically. This leniency is convenient, but it can cause problems; take line 4 for example. You might expect the variable y to be given the value 0.333333, which is a legal floating-point value, but in fact it will get the value 0.0. The reason is that the expression on the right appears to be the ratio of two integers, so Java does integer division, which yields the integer value 0. Converted to floating-point, the result is 0.0.
One way to solve this problem (once you figure out what it is) is to make the right-hand side a floating-point expression as we did in line 5. This sets y to 0.333333, as expected.
All the operations we have seen so far-addition, subtraction, multiplication, and division-also work on floating-point values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floating-point operations.

3.1.1 Exponential Notation
Floating-point numbers can also be written in exponential notation, which is similar to scientific notation and is commonly used to express both very large and very small values in compact form. The following examples illustrate how numbers with decimals can be expressed in exponential and scientific notation.
     Decimal notation  Exponential notation  Scientific notation    1625.  1.625E3  1.625 x 103   63421.  6.3421E4  6.3421 x 104   0.00731  7.31E-3  7.31 x 10-3   0.000625  6.25E-4  6.25 x 10-4      In exponential notation, the letter E stands for the exponent. The number following the E represents a power of 10 and indicates the number of places the decimal point should be moved to obtain the standard decimal value. The decimal point is moved to the right if the number after the E is positive or moved to the left if the number after the E is negative.

3.2 Converting from double to int
As I mentioned, Java converts ints to doubles automatically if necessary, because no information is lost in the translation. On the other hand, going from a double to an int requires rounding off. Java doesn't perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number.
The simplest way to convert a floating-point value to an integer is to use a  typecast. Typecasting is so called because it allows you to take a value that belongs to one type and "cast" it into another type (in the sense of molding or reforming, not throwing).
Unfortunately, the syntax for typecasting is ugly: you put the name of the type in parentheses and use it as an operator. For example,
?

1  ...
2 int x    = (int) 3.14159;              //x = 3
3 double y = (int) 3.14159 * 20.0;       //y = 60.0
4...
   
The (int) operator has the effect of converting what follows into an integer, so x gets the value 3. Typecasting takes precedence over arithmetic operations, so in line 3, the value of PI gets converted to an integer first, and the result is 60.0, not 62.0.
Converting to an integer always rounds down, even if the fraction part is 0.99999999. These two properties (precedence and rounding) can make typecasting error-prone.

3.3 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). First, you evaluate the expression in parentheses, which is called the argument of the function. For example, π/2 is approximately 1.571, and 1/x is 0.1 (assuming that x is 10).
Then you can evaluate the function itself, either by looking it up in a table or by performing various computations. The sin of 1.571 is 1, and the log of 0.1 is -1 (assuming that log indicates the logarithm base 10).
This process can be applied repeatedly to evaluate more complicated expressions like log(1/ sin(π/2)). First we evaluate the argument of the innermost function, then evaluate the function, and so on.
Java provides a set of built-in functions that includes most of the mathematical operations you can think of. These functions are called  methods. Most math methods operate on doubles.
The math methods are invoked using a syntax that is similar to the print and println commands we have already seen:
?

1  ...
2 double root   = Math.sqrt (17.0);   //root = 4.1231...
3 double angle  = 1.5;
4 double height = Math.sin (angle);   //height = 0.99749...
5 ...
   
The first example sets root to the square root of 17. The second example finds the sine of 1.5, which is the value of the variable angle. Java assumes that the values you use with sin and the other trigonometric functions (cos, tan) are in radians. To convert from degrees to radians, you can divide by 360 and multiply by 2π. Conveniently, Java provides π as a built-in value:

1 ...
2 double degrees = 90;
3 double angle   = degrees * 2 * Math.PI / 60.0;       //angle= .5707...
4 int x          = Math.round (float)(Math.PI * 20.0);  //x = 63
5 ...

 Notice that PI is in all capital letters. Java does not recognize Pi, pi, or pie. Another useful method in the Math  class is round, which rounds a floating-point value off to the nearest integer and returns an int.
In line 3, the multiplication happens first, before the method is invoked. The result is 63 (rounded up from 62.8319).
For additional information and methods in the math class google "Java math class".

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

1 ...
2 angle    = 1.5707
3 double x = Math.cos (angle + Math.PI/2);    //x = -0.99999...
4 double y = Math.exp (Math.log (10.0));      //y = 10.00000...
5...
 
Line 3 takes the value Math.PI, divides it by two and adds the result to the value of the variable angle. The sum is then passed as an argument to the cos method. (Notice that PI is the name of a variable, not a method, so there are no arguments, not even the empty argument ()).
You can also take the result of one method and pass it as an argument to another like in line 4.
In Java, the log function 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 y. The log function in Java would be equivalent to the natural log on your calculator.
To view the rest of the methods available to you in the Java Math class visit Math Class' API

3.5 Formating output with printf
With the introduction of floating-point numbers, an issue of how we format output comes into play. Formating your output is a little tough to get used to but once you become comfortable with it, it will become as easy as println. For example when you run the code to solve for square root of 17 and output it, you will find the ouput to be less than desirable. Do you really need 15 decimal places in your ouput?
Earlier you saw the use of the print and println methods for printing strings to standard output (System.out). Since all numbers can be converted to strings, you can use these methods to print out an arbitrary mixture of strings and numbers. The Java programming language has other methods, however, that allow you to exercise much more control over your print output when numbers are included.
The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println. The method we will focus on in this course is printf method. The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out. Thus, you can use printf anywhere in your code where you have previously been using print or println. The syntax for the printf method is as follows:

     1  public PrintStream printf(String format, Object... args)  where printf is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. A simple example would be
1  ...
2 double floatVar  = 3.14159;
3 int intVar       = 15;
4 String stringVar = "sample string";
5 System.out.printf("The value of the float variable is %f, " +
6    "while the value of the integer variable is %d, and the " +
7    "string is %s", floatVar, intVar, stringVar);
8...   

The first parameter, printf, is a format string specifying how the objects in the second parameter, args, are to be formatted. The format string contains plain text as well as format specifiers, which are special characters that format the arguments of Object... args. (The notation Object... args is called varargs, which means that the number of arguments may vary.)
Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There are many converters, flags, and specifiers, which are documented in java.util.Formatter or here
Here is a basic example:

1 int i = 461012;
2 System.out.format("The value of i is: %d%n", i);
3 System.out.println("That wasn't so bad");   

 Would output:
 
1
2  The value of i is: 461012
3 That wasn't so bad

  printf Commands
     Type  Representation  Explaination    Converter  d  an integer   Converter  f  a decimal number   Converter  s  a string   Converter  n  A new line character appropriate to the platform running the application   Precision  .X  Where X>0, number of places after the decimal point. The value is right-truncated if necessary    Width  X  Where X>0, the minimum width of the formatted value; the value is padded if necessary. By default the value is left-padded with blanks.    Flag  +  Includes sign, whether positive or negative.    Flag  ,  Includes locale-specific grouping characters.   Flag  -  Left-justified.   Flag  0  Indicates 0 is the padding character     

The following program shows some of the formatting that you can do with printf. The output is shown within double quotes in the embedded comments:

1    public class TestFormat {
2  public static void main(String[] args) {
3       int n = 461012;
4        System.out.printf("%d%n", n);         //  -->  "461012"
5        System.out.printf("%08d%n", n);       //  -->  "00461012"
6        System.out.printf("%+8d%n", n);       //  -->  " +461012"
7       System.out.printf("%,8d%n", n);       //  -->  " 461,012"
8        System.out.printf("%+,8d%n%n", n);    //  -->  "+461,012"
9
10        double pi = Math.PI;
11       System.out.printf("%.3f%n", pi);      //  -->  "3.142"
12       System.out.printf("%10.3f%n", pi);    //  -->  "     3.142"
13       System.out.printf("%-10.3f%n", pi);   //  -->  "3.142     "
14
15        String name = "Joe";
16        System.out.printf("Name: %s%n", name);   // --> "Joe"
17        System.out.printf("Name: %5s%n", name);  // --> "  Joe"
18        System.out.printf("Name: %-5s%n", name); // --> "Joe  "
19    }
10}

  3.6 Adding new methods
So far we have only been using the methods that are built into Java, but it is also possible to add new methods. Actually, we have already seen one method definition: main. The method named main is special in that it indicates where the execution of the program begins, but the syntax for main is the same as for other method definitions:

 ...
/**
 * What does the method do?
 * can span more than one line keeping within the 80 character limit
 *
 * @param #1       brief description of expected input for param #1 
 * @param #2       brief description of expected input for param #2
 * @param etc...   etc
 */
public static void NAME ( LIST OF PARAMETERS ) {
    STATEMENTS
}
...   

The first thing you notice in the above code is the long line of *'s. This is how you will be expected to comment each of your methods. The first few lines of text document what the method's purpose is followed by a list of the parameters and a brief explanation of what their expected inputs are.
You can make up any name you want for your method, except that you can't call it main or any other Java keyword. Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples:

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

  The list of  parameters specifies what information, if any, you have to provide in order to use (or  invoke) the new function.
The single parameter for main is String[] args, which indicates that whoever invokes main has to provide an array of Strings (we'll get to arrays in Chapter 10). The first couple of methods we are going to write have no parameters, so the syntax looks like this:
  ...
public static void newLine () {
    System.out.println ("");
}
... 
 
This method is named newLine, and the empty parentheses indicate that it takes no parameters. The method above contains only a single statement, which prints an empty String, indicated by "". Printing a String with no letters in it may not seem all that useful, except remember that println skips to the next line after it prints, so this statement has the effect of skipping to the next line.
In main we can invoke this new method using syntax that is similar to the way we invoke the built-in Java commands:

 ...
public static void main (String[] args) {
    System.out.println ("First line.");
    newLine ();
    System.out.println ("Second line.");
}
... 
 
The output of this program is
 
 First line.
 
Second line.
  Notice the extra space between the two lines. What if we wanted more space between the lines? 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, named threeLine, that prints three new lines:

  ...
public static void main (String[] args) {
    System.out.println ("First line.");
    threeLine ();
    System.out.println ("Second line.");
}
 
public static void threeLine () {
    newLine ();
    newLine ();
    newLine ();
}
...   
You should notice a few things about this program:
 
 
  • You can invoke the same procedure repeatedly. In fact, it is quite common and useful to do so.
  • You can have one method invoke another method. In this case, main invokes threeLine and threeLine invokes newLine. Again, this is common and useful.
So far, it may not be clear why it is worth the trouble to create all these new methods. Actually, there are a lot of reasons, but this example only demonstrates two:
   
  • Creating a new method gives you an opportunity to give a name to a group of statements. Methods can simplify a program by hiding a complex computation behind a single command, and by using English words in place of arcane code. Which is clearer, newLine () or System.out.println ("")?
  • Creating a new method can make a program smaller by eliminating repetitive code. For example, how would you print nine consecutive new lines? You could just invoke threeLine three times.
3.7 Classes and methods
Pulling together all the code fragments from the previous section, the whole class definition looks like this:

   class NewLine {
    public static void main (String[] args) {
        System.out.println ("First line.");
        threeLine ();
        System.out.println ("Second line.");
    }
    public static void newLine () {
        System.out.println ("");
    }
    public static void threeLine () {
        newLine ();
        newLine ();
        newLine ();
    }
}   
The first line indicates that this is the class definition for a new class called NewLine. A  class is a collection of related methods. In this case, the class named NewLine contains three methods, named newLine, threeLine, and main.
The other class we've seen is the Math class. It contains methods named sqrt, sin, and many others. When we invoke a mathematical function, we have to specify the name of the class (Math) and the name of the function. That's why the syntax is slightly different for built-in methods and the methods that we write:

  ...
double x;
x = Math.pow (2.0, 10.0);           //legal Math class call
newLine ();                         //legal in class function
//only legal if the method pow exists in the YOUR class
pow (2.0, 10.0);
...

  The first statement invokes the pow method in the Math class (which raises the first argument to the power of the second argument). The second statement invokes the newLine method, which Java assumes exists inside your current class (in this case NewLine which is what we are writing).
If you try to invoke a method from the wrong class, the compiler will generate an error. For example, line 5, the compiler will say something like, "Can't find a method named pow in class NewLine." If you have seen this message, you might have wondered why it was looking for pow in your class definition. Now you know.

3.8 Programs with multiple methods
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 order of execution of the program.
Execution always begins at the first statement of main, regardless of where it is in the program. Statements are executed one at a time, in order, until you reach a method invocation. Method invocations are like a detour in the flow of execution. Instead of going to the next statement, you go to the first line of the invoked method, execute all the statements there, and then come back and pick up again where you left off.
That sounds simple enough, except that you have to remember that one method can invoke another. Thus, while we are in the middle of main, we might have to go off and execute the statements in threeLine. But while we are executing threeLine, we get interrupted three times to go off and execute newLine.
For its part, newLine invokes the built-in method println, which causes yet another detour. Fortunately, Java is quite adept at keeping track of where it is, so when println completes, it picks up where it left off in newLine, and then gets back to threeLine, and then finally gets back to main so the program can terminate.
Actually, technically, the program does not terminate at the end of main. Instead, execution picks up where it left off in the program that invoked main, which is the Java interpreter. The Java interpreter takes care of things like deleting windows and general cleanup, and then the program terminates.
What's the moral of this sordid tale? When you read a program, don't read from top to bottom. Instead, follow the flow of execution.

3.9 Parameters and arguments
Some of the built-in methods we have used have  parameters, which are values that you provide to let the method do its job. For example, if you want to find the sine of a number, you have to indicate what the number is. Thus, Math.sin takes a double value as a parameter. To print a string, you have to provide the string, which is why println takes a String as a parameter.
Some methods take more than one parameter, like Math.pow, which takes two doubles, the base and the exponent.
Notice that in each of these cases we have to specify not only how many parameters there are, but also what type they are. So it shouldn't surprise you that when you write a class definition, the parameter list indicates the type of each parameter. For example:

    ...
public static void printTwice (String string) {
    System.out.println (string);
    System.out.println (string);
}
...

  This method takes a single parameter, named string, that has type String. Whatever that parameter is (and at this point we have no idea what it is), it gets printed twice. Anytime you create a method that takes in a generic parameter, the variable should have the same name as it's type. Now, if the parameter is specific, than the naming convention follows that of standard variable declarations seen in last chapter.
In order to invoke this method, we have to provide a String. For example, we might have a main method like this:

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

The string you provide is called an  argument, and we say that the argument is passed to the method. In this case we are creating a string value that contains the text "Don't make me say this twice!" and passing that string as an argument to printTwice where, contrary to its wishes, it will get printed twice.
Alternatively, if we had a String variable, we could use it as an argument instead:

  ...
public static void main (String[] args) {
    String simpleSaying = "Never say never.";
    printTwice (simpleSaying);
}
...

 Notice something very important here: the name of the variable we pass as an argument (simpleSaying) has nothing to do with the name of the parameter (string). Let me say that again:
The name of the variable we pass as an argument has nothing
to do with the name of the parameter.

 
They can be the same or they can be different, but it is important to realize that they are not the same thing, except that they happen to have the same value (in this case the string "Never say never.").
The value you provide as an argument must have the same type as the parameter of the method you invoke. This rule is very important, but it often gets complicated in Java for two reasons:
 
 
  • There are some methods that can accept arguments with many different types. For example, you can send any type to print and println, and it will do the right thing no matter what. This sort of thing is an exception, though.
  • If you violate this rule, the compiler often generates a confusing error message. Instead of saying something like, "You are passing the wrong kind of argument to this method," it will probably say something to the effect that it could not find a method with that name that would accept an argument with that type. Once you have seen this error message a few times, though, you will figure out how to interpret it.
3.10 Variable Scope
With having variables in multiple places in your program, we have to introduce the concept of  scope. Scope is basically where a variable can be referenced from and still contain the value you expect it to have. When you declare variables inside a particular method, that variable only has value inside that method. Later on in computer science, you will be exposed to class-level variables which can be used any where in that class. Here is an example of variable scope

  ...
public static void main (String[] args) {
    int x = 2;
    System.out.println("the value of x is: " + x);  //x = 2
    sqrIt (x);
    System.out.println("the value of x is: " + x);  //x = 2
}
public static void sqrIt (int someInt) {
    int x = 3
    System.out.println("the value squared is: " + someInt * someInt);
    System.out.println("the value of x is: " + x);  //x = 3
}

  Notice when we declare and use x inside the method sqrIt it does not contain any reference to the x declared in main and vice versa. Make sure you do NOT reference variables outside of their scope or you will encounter an error.

3.11 Methods with multiple parameters
The syntax for declaring and invoking methods with multiple parameters is a common source of errors. First, remember that you have to declare the type of every parameter. For example

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

It might be tempting to write (int hour, minute) on line 2, but that format is only legal for variable declarations, not for parameters.

3.12 Methods with results
You might have noticed by now that some of the methods we are using, like the Math methods, yield results. Other methods, like println and newLine, perform some action but they don't return a value. That raises some questions:
 
 
  • What happens if you invoke a method and you don't do anything with the result (i.e. you don't assign it to a variable or use it as part of a larger expression)?
  • What happens if you use a print method as part of an expression, like System.out.println ("boo!") + 7;
  • Can we write methods that yield results, or are we stuck with things like newLine and printTwice?
The answer to the third question is "yes, you can write methods that return values," and we'll do it in a couple of chapters. I will leave it up to you to answer the other two questions by trying them out. In fact, any time you have a question about what is legal or illegal in Java, a good way to find out is to ask the compiler.
3.13 Code style
     6. Names representing methods must be verbs and written in mixed case starting with lower case.
     
     getName(), computeTotalWidth()    Common practice in the Java development community and also the naming convention used by Sun for the Java core packages. This is identical to variable names, but methods in Java are already distinguishable from variables by their specific form.   
     9. Generic variables should have the same name as their type.
     
     void setTopic(Topic topic) // NOT: void setTopic(Topic value)
                           // NOT: void setTopic(Topic aTopic)
                           // NOT: void setTopic(Topic t)
 
void connect(Database database) // NOT: void connect(Database db)
                                // NOT: void connect(Database oracleDB)    Reduce complexity by reducing the number of terms and names used. Also makes it easy to deduce the type given a variable name only. If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen.
Non-generic variables have a role. These variables can often be named by combining role and type:
 

     Point  startingPoint, centerPoint;
Name   loginName; 

     15. The term compute can be used in methods where something is computed.
     
     computeAverage(), computeInverse()    Give the reader the immediate clue that this is a potential time consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.   

     16. The term find can be used in methods where something is looked up.    
     findNearestVertex();
findSmallestElement();
findShortestPath(Node destinationNode);    Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability.   

     42. Type conversions must always be done explicitly. Never rely on implicit type conversion.    
     floatValue = (int) intValue;      // NOT: floatValue = intValue;    By this, the programmer indicates that he is aware of the different types involved and that the mix is intentional.   

     58. Floating point constants should always be written with decimal point and at least one decimal.    
     double total = 0.0;    // NOT:  double total = 0;
double speed = 3.0e8;  // NOT:  double speed = 3e8;
double sum;
sum = (a + b) * 10.0;  // NOT: (a + b) * 10    This emphasize the different nature of integer and floating point numbers. Mathematically the two model completely different and non-compatible concepts.
Also, as in the last example above, it emphasize the type of the assigned variable sum at a point in the code where this might not be evident. 
 
     59. Floating point constants should always be written with a digit before the decimal point.    
     double total = 0.5;  // NOT:  double total = .5;    The number and expression system in Java is borrowed from mathematics and one should adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more readable than .5; There is no way it can be mixed with the integer 5.
 
     74. Method names can be followed by a white space when it is followed by another name.    
     doSomething (currentFile);
doSomethingElse();    Makes the individual names stand out. Enhances readability. When no name follows, the space can be omitted since there is no doubt about the name in this case.   

     76. Methods should be separated by three blank lines.    By making the space larger than space within a method, the methods will stand out within the class.   
     81. Javadoc comments should have the following form:    
     /**
 * Return lateral location of the specified position.
 * If the position is unset, NaN is returned.
 *
 * @param x    X coordinate of position.
 * @param y    Y coordinate of position.
 * @param zone Zone of position.
 * @return     Lateral location.
 */
public double computeLocation(double x, double y, int zone) {    A readable form is important because this type of documentation is typically read more often inside the code than it is as processed text.
Note in particular:
 
 
  • The opening /** on a separate line
  • Subsequent * is aligned with the first one
  • Space after each *
  • Empty line between description and parameter section.
  • Alignment of parameter descriptions.
  • Punctuation behind each parameter description.
  • No blank line bewteen the documentation block and the method/class.
 
     86. All public classes and public and protected functions within public classes should be documented using the Java documentation (javadoc) conventions.    This makes it easy to keep up-to-date online code documentation.   
« Last Edit: November 03, 2011, 11:26:07 AM by Live Wire »
"There is no right or wrong, there is only fun and boring."

 



Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.