Results 1 to 1 of 1
Like Tree1Likes
  • 1 Post By Java Exam

Thread: Tutorial:Overview of Java Syntax for the Java Certification Exam

  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Overview of Java Syntax for the Java Certification Exam

    In this article, we will provide an overview of Java SE and it’s syntax. We will look at the entities in Java that are not objects—numbers and characters. This gives you all the elements of the language you need to perform numerical calculations, and you apply these in a few working examples. This is part of a larger series of articles to help you prepare for the java associate exam. The first article of the series was "Tutorial:Basics of Java for the Java Certification Exam".

    Java Syntax - Logic, Variables and Data

    In Java, a variable is a named piece of memory that you use to store information in your Java program an item of data of some description. Each named piece of memory that you define can only store data of one particular type. If you define a variable to store integers, for example, you can't use it to store a value that is a decimal fraction, such as 0.75. If you've defined a variable that you use to refer to a Hat object, you can only use it to reference an object of type Hat. Because the type of data that each variable can store is fixed, the compiler can verify that each variable you define in your program is not used in a manner or a context that is inappropriate to its type. If a method in your program is supposed to process integers, the compiler is able to detect when you inadvertently try to use the method with some other kind of data, for example, a string or a numerical value that is not integral.

    Explicit data values that appear in your program are called literals. Each literal is also of a particular type: 25, for example, is an integer literal of type int. I will go into the characteristics of the various types of literals that you can use as I discuss each variable type.

    Naming Your Variables

    The name that you choose for a variable, or indeed the name that you choose for anything in Java, is called an identifier. An identifier can be any length, but it must start with a letter, an underscore (_), or a dollar sign ($). The rest of an identifier can include any characters except those used as operators in Java (such as +, -, or *), but you are generally better off if you stick to letters, digits, and the underscore character.

    As Java is case sensitive, the names republican and Republican are not considered identical by the compiler. Subject to the restrictions you can name a variable almost anything you like except the following:
    • you can't use a keyword as a name for something
    • a name can't be anything that could be interpreted as a constant value—as a literal in other words.


    Keywords are words that are part of the Java language. You can check your Java documentation for a complete list of all keywords. The restriction on constant values is there because, although it is obvious why a name can't be 1234 or 37.5, constants can also be alphabetic, such as true and false, which are literals of the type boolean. Of course, the basic reason for these rules is that the compiler has to be able to distinguish between your variables and other things that can appear in a program. If you try to use a name for a variable that makes this impossible, then it's not a legal name.

    Variable Names and Unicode

    Even though you may be entering your Java programs in an environment that stores ASCII characters, all Java source code is in Unicode. Although the original source code that you create may be ASCII, it is converted to Unicode characters internally, before it is compiled. Although you can write any Java language statement using ASCII, the fact that Java supports Unicode provides you with immense flexibility. It means that the identifiers that you use in your source program can use any national language character set that is defined within the Unicode character set, so your programs can use French, Greek, or Russian variable names, for example, or even names in several different languages, as long as you have the means to enter them in the first place. The same applies to character data that your program defines.

    Variables and Types

    As each variable that you declare can store values only of a type consistent with the data type of that variable, you must specify the type of a particular variable by using a type name in the variable declaration. For example the statement below declares a variable that can store integers:

    Java Code: Declaration
    int numberOfCats;
    The data type in this case is int and the variable name is numberOfCats. The semicolon marks the end of the statement. The variable, numberOfCats, can only store values of type int. The int is a keyword.

    Many of your variables will be used to reference objects, but let's leave those on one side for the moment as they have some special properties. The only things in Java that are not objects are variables that correspond to one of eight basic data types, defined within the language. These fundamental types are referred to as primitive types, and they enable you to define variables for storing data that fall into one of three categories:
    • Numeric values, which can be either integer or floating-point
    • A single Unicode character
    • Logical values that can be true or false

    All of the type names for the basic variable types are keywords in Java so you must not use them for other purposes. Let's look in detail at each of the primitive data types and see how they are used.

    Integer Data Types

    There are four types of variables that you can use to store integer data. All of these are signed—that is, they can store both negative and positive values. The four integer types differ in the range of values they can store, so the choice of type for a variable depends on the range of data values you are likely to need. The four integer types in Java are shown in the table below:

    Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-javaintegertypes.jpg
    Table: Java Integer Types

    There are cases in real-world applications where you need numbers even bigger than the maximum value of long. In those cases, Java provides a class called BigInteger. A number represented by a BigInteger object can be of any size, because the BigInteger class allocates enough bytes to store a representation of any number. It's a little tricky to use and operations on BigInteger objects are slow, but it's sometimes the only way. BigInteger is not a primitive.

    Real Data Types

    Real numbers have decimal points and values after the decimal point. Even if that value is 0, and even if you didn't type a decimal point and anything after it, the decimal point and the zeros after it are there behind the scenes. They must exist so that operations on the value can compare to the full value, so the JVM (the Java Virtual Machine, which is the program that runs your programs) fills them in even if you don't.

    Java supports two real primitives, float and double. float gets its name from the idea of a floating point number. The decimal point can move, so it's said to “float.” double gets its name because it takes twice the storage space of a float. The table below shows the details of float and double.

    Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-javarealprimitives.jpg
    Table: Real Primitive

    For those cases when a float isn't large enough, Java provides a class called BigDecimal. As with BigInteger, it can be tricky to use, and operations on it are slow. But when you absolutely have to have a number bigger than a double, use BigDecimal. As with BigInteger, BigDecimal is not a primitive.

    boolean
    The boolean data type indicates whether something is true or false. In fact, those two words (true and false) are the only two values boolean data types can have.

    char
    The char data type holds two 8-bit bytes and is meant to represent characters. It's stored as an unsigned 16-bit integer with a minimum value of 0 and a maximum value of 65,535. However, you should never use a char to store a number, because that can lead to confusion. Use char variables to hold individual characters, and you'll avoid trouble.
    So why is the maximum so big when relatively few characters exist? Well, when you look at all the character sets in use all around the world, 65,535 isn't so unreasonable. In fact, it's not enough when dealing with traditional Chinese.

    String - A Primitive and an Object
    String is a type that has some of the characteristics of both a primitive and an object. Strictly speaking, it is an object; that is, a String class defines it. A String object is a sequence of characters (and Java provides utilities for turning a String object into a collection of char primitives and for making a String object from such a collection). It's often handy to work on the collection (the string) rather than on each character, so Java (and nearly all other programming languages) provides a String object.
    Java offers special support for the String class that lets String objects act a little like primitives. In particular, you can create a String object by using the equals sign (=), and you can concatenate String objects with the plus sign (+). Concatenation applies only to strings, by the way. If you use a plus symbol with the other data types, you either get an error (try adding two boolean values and you'll see it) or you get the mathematical plus operation that you usually associate with the plus symbol. This is shown in the listing below:

    Java Code: String examples
     String myString = "my string";
    String yourString = "your string"; 
    String ourString = myString + " " + yourString; 
    System.out.println(myString); 
    System.out.println(yourString); 
    System.out.println(ourString);
    The output for this listing is shown below:

    XML Code: String example output
     my string 
    your string 
    my string your string
    NoticethatthevalueofourStringconsistsoftheconcaten ationofthreevalues:myString," ",and yourString. " " is a String literal. That's another way String differs from other objects; no other object can have a literal.

    Literals
    All the primitives and the String class can have literal values. A literal is a constant value that corresponds to a particular data type. The table below provides examples for each of the primitive data types and the String class.

    Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-javaliteralexamples.jpg
    Table: Examples of Literals

    Literals pop up all over the place, often without anyone stopping to think about it. Every time we write a loop that starts at 0 and counts to some value, we use a literal. A number of other literals are common in nearly all programming languages and tasks. In set theory which informs a lot of programming and especially database programming, the only three values that matter are 0, 1, and many. Consequently, 0 and 1 appear over and over again throughout all kinds of software. The empty string, which is sometimes handy for comparing String objects and the single space, which is useful for linking String objects without inventing a new and large word in the process also appear often.

    Escaping Characters

    Variables of type char can have several special values. First, singe quotation marks ('), double quotation marks ("), and backslashes (\) all have to be marked as special (that's called escaping a character), so that the JVM knows you want one of those characters. Otherwise, it would process all your single quotations as the beginning or end of a char and all your double quotations as the beginning or end of a String object. The backslash character has to be escaped because it is the escape character. If it couldn't itself be escaped, then every backslash would indicate an escaped character, which would be a real problem. Escaped characters or escape sequences, which consist of at least two characters, the escape character and at least one other character are also used for non-graphical characters called control characters. Below is an example that can help to clarify things:

    Java Code: Examples of Escaping Characters
    // Let's start with double quotation marks 
    // The following line throws an error because meow isn't defined 
    System.out.println("My cat says, "meow.""); 
    // so the line has to be 
    System.out.println("My cat says, \"meow.\""); 
    // which will produce this output: My cat says, "meow."
    // And now single quotation marks 
    // The following line throws an error because ' never has a matching ' 
    System.out.println("' is my favorite character"); 
    // so the line has to be 
    System.out.println("\' is my favorite character");
    
    // which will produce this: ' is my favorite character 
    // (my actual favorite character is ;)
    // And now the backslash itself 
    // The following line throws an error because it's missing a closing " 
    // (The compiler takes \" as a literal " and then can't find an end to the string.) System.out.println("I want a \"); 
    // so the line has to be 
    System.out.println("I want a \\"); 
    // which will produce this: I want a \
    Java also supports several special escape sequences (all beginning with a backslash). The table shows each escape sequence and describes its effect. It begins with the three we already covered:

    Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-escapesequences.jpg
    Table: Escape Sequences

    The newline character (\n) sees a lot of use for things like creating readable error messages, separating lines in files, and other output. Tabs are less common but still sometimes used (to line up pieces of output to make things easier to read). The others are much more rarely used, because software developers hardly ever create unstructured output these days. When programmers used punch cards for input and line printers for output, programmers made extensive use of the form feed and start-of-line characters. We still produce plenty of output, of course, but it's usually HTML, XML, or some other structured format.

    In addition to being possible values for variables of type char, String objects can also contain escape sequences. Many String objects contain a newline sequence or two. The listing shows a short example:

    Java Code: String with escape sequence
     
    String errorMessage = "Who Dat? Don’t know!\nCheck the monitor.";
    System.out.println(errorMessage);
    The output produced by the code snippet is shown in the listing below:

    XML Code: Newline output
     Who Dat? Don’t know?
    Check the monitor.
    Wrapper Classes

    Each of the primitives (remember, String is an object rather than a primitive) has a corresponding class that provides several useful abilities that are otherwise unavailable to a primitive. You can think of the wrapper classes as each being a package of useful abilities wrapped around a primitive of the corresponding type. The table below shows the corresponding class for each primitive:

    Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-wrapperclasses.jpg
    Table: Wrapper Classes

    The most commonly used methods of those classes are the various parse, Value, and valueOf methods, because those methods let you turn a String into a primitive. Each class also supports toString methods to turn primitives into String objects. The listing below shows what you can do with an int primitive:

    Java Code: Integer example
    // declare an int
    int myInt = 1;
    // and a String that contains a number 
    String myString = "1";
    // turn myInt into a String 
    String myIntString = Integer.toString(myInt);
    // turn myString into an int 
    int myStringInt = Integer.parseInt(myString);
    // turn myString into an Integer 
    // be prepared for an exception if myString does not hold a number 
    Integer myStringInteger = new Integer(myString);
    // and then turn myStringInteger into an int 
    int myOtherStringInt = myStringInteger.intValue();
    // Now for more unusual things 
    // convert an int to a float (perhaps for further floating-point work) 
    float myFloat = new Integer(myInt).floatValue();
    // convert an int to a byte 
    // be prepared for an exception if the value is out of byte's range 
    byte myByte = new Integer(myInt).byteValue();
    // convert an int to a long // no need to worry about an exception this time 
    long myLong = new Integer(myInt).longValue();
    // just for fun, get the binary string representation of myInt 
    // creates a String object that holds "1" 
    String myIntBinary = Integer.toBinaryString(myInt);
    The other numeric primitives (byte, short, long, float, and double) all work in a similar way. You can convert any of them to any other, though you might have to handle an exception if the conversion can't be done with the value you provide. For example, if you have an int variable that holds a value of 300, converting it to a byte gives an error, because a byte can't hold that value. We cover this concept in greater detail in the next chapter, when discussing casting values.

    The Boolean and Character classes work a little differently. You can still convert strings to boolean or char values and vice-versa, but you can't convert boolean and char primitives into other primitives. Also, the Boolean class includes an equals method, and the Character class includes many methods for dealing with issues such as characters that are meant to be read from right to left (for example, characters from Arabic and Hebrew) and other special issues that relate only to characters. All of those operations are fairly unusual, though, so we don’t cover them. If you want to learn more about them look at the Javadoc for the Boolean and Character classes. JavaDoc is the documentation that is built into the code itself. Oracle provides extensive JavaDoc for all the standard Java libraries. You can find all the JavaDoc for Java 7 at http://download.oracle. Go to the section under com/javase/7/docs/api/. The other topics are branches of the overall API documentation.

    Arrays

    An array is a data structure that holds a group of variables under a single identifier. Java supports arrays for both primitives and objects. Square brackets after a variable's name indicate that it is an array. The listing below shows several arrays and how to manipulate them.

    Java Code: Arrays of primitives
    int[] a; // array declaration without assignment 
    a = new int[2]; // specify the length of an existing array 
    int[] b = {1, 2, 3, 4}; // array declaration with assignment 
    int bLength = b.length; // how to get the length of an array
    
    // arrays start at 0, not 1 
    b[0] = 2; // have to reassign each value in the array individually
    The first line creates an array of int primitives but doesn't assign anything to it. It is null at this point. The second line shows how to set an array to be a particular length. If a had values, its values would be replaced by the default values of the new type. In our case, it is 0. The third line shows how to create an array with a set of starting values. You can use that block assignment syntax only when creating an array, not when assigning new values to an existing array. The fourth line shows how to get the length of an array. The last line shows how to reassign one of the values in an array and shows that array addresses start at 0. This is shown in the listing below:

    Java Code: Arrays of objects
    Integer[] myIntegers = new Integer[4]; 
    for (int i = 0; i < myIntegers.length; i++) {
       myIntegers[i] = new Integer(i);
    }
    In the listing above, the syntax for creating an array of objects differs a bit from that for primitives. The part to the left of the equal sign looks the same the kind of object, the array indicator, and the name of the variable), but the part to the right of the equal sign differs by having the new keyword before the type of the item going into the array. To create a new instance of an object, we usually use the new keyword (though other ways exist), which calls a constructor for the object. However, all of the Integer class's constructors require an object (either an int or a String object that holds an integer value), so this array ends up holding four null references.

    This listing also shows how to loop through an array and, in this case, create an object for each of the null objects. Notice that we have to use the new keyword again, even though we used it when we created the array. Because we got four null references rather than actual objects from the original assignment, we have to create new ones here. In this case, we end up with four Integer objects having values of 0, 1, 2, and 3.

    Java provides a convenience class for arrays. The Arrays class consists of many static methods to do handy things such as copy and sort arrays. The listing below shows one way to sort an array of ints:

    Java Code: Using the Arrays convenience class
    int[] a = {5, 4, 3, 2}; 
    // at the top of the program, we had to import 
    // java.util.Arrays for this to work correctly 
    Arrays.sort(a); 
    for (int i = 0; i < a.length; i++) {
       System.out.println(a[i]);
    }
    The result of this listing is shown in the console is 2, 3, 4, 5.

    null - The Non Existent Type

    Java includes a value that isn't anything: null. It refers to a memory address that has not been assigned. In Java terms, that means it refers to an object or primitive that has not been created. As I mentioned in the “Arrays” section, when you create an array without specifying its values, you are creating a collection of null values. They have no memory address, no corresponding primitive or object exists for them, and so they are null. That might sound like a problem, and the whole concept of null often causes novice programmers some trouble. You can keep it straight by remembering that a null is a non-existent reference.

    The oft-maligned null has its uses. For example, we often compare an object to null to be sure that something exists before we try to use it. If the graphics library is supposed to give us an object of type Color and we get null instead, we have a problem. So we might compare that Color value to null to ensure that we are getting a Color object and do something useful such as trying another way. Also, it's common practice to create a variable in one place and assign it in another place. In between the creation and assignment, the value of that variable might be null. Sometimes it might not be null because some primitives, such as int, have default values. This technique is handy because we might want to assign different values to the variable based on some logic. For example, a series of if-else statements or a switch statement might contain code to assign the value of a variable. The listing below provides a small example:

    Java Code: Using a null value
    public getMineIcon(int x, int y) {
    
    // x and y are the position within the game grid 
       int numberOfAdjacentMines = getNumberOfAdjacentMines(x, y);
       MineIcon mineIcon = null; // here's our null
    
       if (numberOfAdjacentMines == 1) { 
          mineIcon = new MineIcon(1);
       } else if (numberOfAdjacentMines == 2) {
          mineIcon = new MineIcon(2); 
       }
          // and so on up to 8 
       return mineIcon;
    }

    In this listing, we can assume a MineIcon class exists and that its constructor will take two integer values and return an icon that shows the value of that integer argument. Because a square in a minesweeper game can have no more than eight neighboring mines, we stop at eight. We also let the method return null, to represent the case where a square has no neighboring mines. Consequently, the code that calls this method then has to know what to do with a null value. As it happens, the setIcon method that we need to use accepts a null argument as a way of saying that no icon needs to be set.

    We can use the mine icon in a different way that still uses a null reference. For now, just remember that null is just another value and that it can be used for purposes other than just checking for missing objects.

    Enumerations

    An enumeration is a data type that consists of a fixed number of constants. For example, if you are writing a game that involves navigation, you might have an enumeration to define the four cardinal directions, similar to the one shown in the listing below:

    Java Code: Enum for directions
     
    public enum Direction {
       NORTH, EAST, SOUTH, WEST;
    }
    As the listing shows, the declaration of an enumeration consists of the enum keyword, a name for the enumeration, and the values that comprise the enumeration. The values are just names and have no type of their own. That works because we need unique identifiers but don't need a type for each one.

    The value of enumerations is that they are type-safe (meaning that it can't be confused with another type—enums used to be created with integers, so confusing an enum with an integer was a real problem). Without enumerations, we'd have to set up constants in a different way. This is normally done using integers. An example of this is shown below:

    Java Code: Constants to define directions
    public static final int NORTH = 0; 
    public static final int EAST = 1; 
    public static final int SOUTH = 2; 
    public static final int WEST = 3;
    Each enum is actually a class. (You might have noticed that its declaration syntax is similar to a class.) All enum objects implicitly extend java.lang.Enum. That lets us make more meaningful enums than just lists of constants. To continue with our example, we can set the degrees for each direction, as shown in listing below:

    Java Code: Enum with more information
    public enum Direction { 
       NORTH (0), 
       EAST (90), 
       SOUTH (180),
       WEST (270);
    }
    
    private final int degrees; 
    Direction(int degrees) {
    this.degrees = degrees; 
    }
    
    public int getDegrees() {
       return degrees;
    }
    From there, we can write code to get the additional information associated with each value in the enumeration, as shown in the listing below:

    Java Code: 14. Getting details from an enum
     
    for (Direction d : Direction.values()) {
       System.out.println(d + " is " + d.degrees + "degrees.");
    }
    We can also write methods that work with the enumeration's values. For example, we can write a method that, given a direction in degrees, tells you which cardinal direction is closest. The listing shows one way to write such a method.

    Java Code: findCardinalDirection method
    public static Direction findCardinalDirection (int degrees) { 
    if (degrees < 45) {
       return NORTH; 
    } else if (degrees < 135) {
       return EAST; 
    } else if (degrees < 225) {
       return SOUTH; 
    } else if (degrees < 315) {
       return WEST; 
    } else {
       return NORTH;
    }
    You might also notice the different syntax for iterating through a for loop. That syntax is not unique to enumerations, but it is especially handy for them. We cover these alternate ways of using a for loop when we get to looping in a later chapter. As you can see, an enumeration is far more powerful than a simple list of constants. It's also safer, because no one can confuse Direction.North with 0. The listing shows the full code for the Direction enumeration:

    Java Code: Complete enumeration example
    package com.acme.examples.enumExample;
    public enum Direction { 
       NORTH (0), 
       EAST (90), 
       SOUTH (180),
       WEST (270);
    
    private final int degrees; 
       Direction(int degrees) {
          this.degrees = degrees; 
       }
    
       public int getDegrees() {
          return degrees;
       }
    
    // static because it doesn't rely on a particular direction 
    public static Direction findCardinalDirection (int degrees) {
       if (degrees < 45) { 
          return NORTH;
       } else if (degrees < 135) { 
          return EAST;
       } else if (degrees < 225) { 
          return SOUTH;
       } else if (degrees < 315) { 
          return WEST;
       } else {
          return NORTH;
       }
      }
    }
    Now that we have our completed enumeration, we need a test program to see how it works. The listing below shows a test class for enumeration:

    Java Code: 17. A test class for our enumeration
    package com.acme.examples.enumExample; 
    public class EnumExample {
    
       public static void main(String[] args) { 
          int[] compassPoints = {22, 77, 144, 288}; 
          for (int i = 0; i < compassPoints.length; i++) {
             System.out.println(compassPoints[i] + " degrees is (very roughly) " 
                 + Direction.findCardinalDirection(compassPoints[i]));
          } 
          for (Direction d : Direction.values()) {
             System.out.println(d + " is " + d.getDegrees() + " degrees.");
          }
       }
    }
    The output produced in the console for EnumExample is shown in the listing below:

    XML Code: EnumExample output
    22 degrees is (very roughly) NORTH 
    77 degrees is (very roughly) EAST 
    144 degrees is (very roughly) SOUTH 
    288 degrees is (very roughly) WEST 
    NORTH is 0 degrees.
    EAST is 90 degrees. 
    SOUTH is 180 degrees. 
    WEST is 270 degrees.
    Summary

    We reviewed the basics about the various data types available in Java. We looked at the following:
    • The size restrictions of the various numeric data types
    • How the boolean data type works
    • How char variables and String objects work and a bit about how they can interact
    • How arrays work
    • What a null is and how to use one to good effect
    • How to create and use enumerations

    You will make repeated use of all these concepts and techniques throughout your work as a Java developer. As we work more with Java, you'll do a lot with primitives, the String object, primitive and String literals, and arrays. Enumerations appear less often in most code, but they offer many advantages when you use them. We will next cover Java Arrays.
    Attached Thumbnails Attached Thumbnails Tutorial:Overview of Java Syntax for the Java Certification Exam-d2-wrapperclasses.jpg  
    Last edited by Java Exam; 05-02-2012 at 12:26 AM.
    janissmf likes this.

Similar Threads

  1. Replies: 0
    Last Post: 05-01-2012, 10:24 PM
  2. Replies: 0
    Last Post: 04-06-2012, 09:24 PM
  3. Replies: 0
    Last Post: 03-26-2012, 02:11 PM
  4. Replies: 0
    Last Post: 12-06-2011, 07:31 PM
  5. Discount Java Certification Exam Vouchers
    By mbrown36 in forum Reviews / Advertising
    Replies: 17
    Last Post: 12-15-2009, 07:10 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •