FANDOM


This trail discusses the basics in learning the Java Language. Take more time to master this section. As this might be helpful in your future studies.

VariablesEdit

You've already learned that objects store their state in fields. However, Java language also uses the term "variable" as well.

Concept of Variables in JavaEdit

As you learned in the previous lesson, an object stores its state in fields. For example, 

   int cadence = 0;
   int speed = 0;
   int gear = 1;

In the Java language, the terms "field" and "variable" are both used; this is a common source of confusion among newbie developers, since both often seem to refer to the same thing in general.

Variables are defined as below:

Types of Variables
Type Definition
Instance Variables (Non-static Fields) Objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Parameters You've already seen examples of parameters, both in the Bicycle class and in the main method of the DIY application you created before. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables", not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in other trails.

Fields and variables have almost the same meaning in general. A field can be defined as a variable. As below:

  • If we refer to a normal field, Instance and Class variables are suitable.
  • If we refer to a variable, all of the 4 types of variables are included.
  • If we refer to a specific item, then that item is suitable.
  • Member refers to a collection of a type's fields, methods, and nested types.

The Rules in Declaring a VariableEdit

Beginning A VariableEdit

  • Variable names are case-sensitive.
  • A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".
  • Always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it.
  • A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged.
  • White space is not permitted.

Subsequent Characters in A VariableEdit

  • Subsequent characters may be letters, digits, dollar signs, or underscore characters.
  • Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as c, s, and g.
  • The name you choose must not be a keyword or reserved word.
  • If the name you choose consists of only one word, spell that word in all lowercase letters.
  • If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are examples of this convention.
  • If your variable stores a constant value(static variables), such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character.
  • By convention, the underscore character is never used elsewhere.

Primitive Data TypesEdit

All variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:

int gear = 1;

Doing so tells your program that a field named "gear" exists, it holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. Other than int, Java language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java language are:

Eight Primitive Data Types in Java
Type Explanation
byte The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
short The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
int The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
long The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
float The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this trail, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specifications trail. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. The Numbers & Strings trail covers BigDecimal term and other useful classes provided by the Java platform.
double The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this trail, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specifications trail. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
boolean The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
char The char data type is a single 16-bit Unicode character. It has a minimum value of \u0000 (representing 0) and a maximum value of \uffff (representing 65,535 inclusive).
  • In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.
  • Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";.
  • String objects are immutable, which means that once created, their values cannot be changed.
  • The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in the Numbers & Strings trail.

Concept of Default ValuesEdit

Default values refers to a field which is declared but not initialized. Default value are known as zero or null, depending on the data type. It is not practical to leave the data types as default values, instead use real integers or "values" to define each type. The following table shows the default values of each primitive data type.

Default Values
Data Type Default Values
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char \u0000
boolean false
String (or any object) null

Note that accessing an uninitialized local variable will result in a compile-time error.

Concept of LiteralsEdit

Literals are something numerical or in words used to represent fixed variables(or static variables). For example:

boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;

General Explanation:

  • The variable result of data type boolean is represented by the literal true.
  • The variable capitalC of data type char is represented by the literal C. The single quotes are only to show that the value is in words.
  • The others are almost the same as the previous explanations.
  • The general formula for static variables is:
   datatype variablename = literal;

Literal ConventionsEdit

Integral Literals

  • General Data Type: int, long(if ends with letter L)
  • Number Systems: Decimal(Base 10), Hexadecimal(Base 16) and Binary(Base 2)
  • Syntax: Decimal - None, Hexadecimal - 0x, Binary - 0b
  • Examples:
   // The number 26, in decimal system
   int decVal = 26;
   //  The number 26, in hexadecimal system
   int hexVal = 0x1a;
   // The number 26, in binary system
   int binVal = 0b11010;

Floating-point Literals

  • General Data Type: double, float(if ends with letter F), both can also end with letter E.
  • Examples:
   double d1 = 123.4;
   // same value as d1, but in scientific notation
   double d2 = 1.234e2;
   float f1  = 123.4f;

Character and String Literals

  • General Data Type: char, String, both contains any Unicode (UTF-16) characters.
  • Amount of Quotes: char - Single, String - Double.
  • Examples:
   '\u0108'

Class Literals

  • Formed by taking a type name and appending ".class".
  • Examples:
   String.class
  • Explanation: The object (of type Class) that represents the type itself.

Underscore Characters (Integral Literals)

  • May appear between digits to distinguish its position. It is not a must to put underscores.
  • Examples:
   long creditCardNumber = 1234_5678_9012_3456L;
   long socialSecurityNumber = 999_99_9999L;
   float pi =  3.14_15F;
   long hexBytes = 0xFF_EC_DE_5E;
   long hexWords = 0xCAFE_BABE;
   long maxLong = 0x7fff_ffff_ffff_ffffL;
   byte nybbles = 0b0010_0101;
   long bytes = 0b11010010_01101001_10010100_10010010;
  • Rules in using Underscore Characters:
  1. Cannot put at the beginning or end of a number.
  2. Cannot put adjacent to a decimal point in a floating-point literal.
  3. Cannot put beside any F and L suffix.

ArraysEdit

An array is a container object that holds a fixed number of values of a single type. After creation, its length or magnitude is fixed(final).

Objects-tenElementArray

A picture showing the structure of an array.

  • Each item in an array is called an element.
  • An element is accessed by an index that lies on that position. For example, the 9th element in an array of magnitude 10 is accessed by the index 8.




Creating an Array of any MagnitudeEdit

The codes that are involved in creating an array are shown below:

Arrays
Part of Code Explanation
int[] anArray; This declares an array.
anArray = new int[10]; The declared array have a magnitude of 10. It allocates memory for 10 integers.
anArray[0] = 100; The first element is accessed by index 100.
anArray[A] = B; The general formula for declaring an element in an array. This means that the Ath element is accessed by the index B.
System.out.println("+ anArray[A]); This tells the system the index of the Ath position in the array.

A complete example of a class declaring an array:

class ArrayDemo {
    public static void main(String[] args) {
        // declares an array of integers
        int[] anArray;

        // have a magnitude of 10
        anArray = new int[10];
           
        // the first element
        anArray[0] = 100;
        // the second element
        anArray[1] = 200;
        anArray[2] = 300;
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;

        // tells system the output of each index of an element
        System.out.println("Element at index 0: "
                           + anArray[0]);
        System.out.println("Element at index 1: "
                           + anArray[1]);
        System.out.println("Element at index 2: "
                           + anArray[2]);
        System.out.println("Element at index 3: "
                           + anArray[3]);
        System.out.println("Element at index 4: "
                           + anArray[4]);
        System.out.println("Element at index 5: "
                           + anArray[5]);
        System.out.println("Element at index 6: "
                           + anArray[6]);
        System.out.println("Element at index 7: "
                           + anArray[7]);
        System.out.println("Element at index 8: "
                           + anArray[8]);
        System.out.println("Element at index 9: "
                           + anArray[9]);
    }
}

Declaring a Variable to Refer to an ArrayEdit

To declare an array, we'd use:

int[] anArray;

Similar to variable declaration, the declaration of an array is made up of two componenets: the array's type followed by the array's name.

  • Array types are represented by a primitive data type as learned before and two brackets. The brackets indicates that the variable holds an array. The size of an array are not of its type, that explains why the brackets are empty. Arrays of other types are shown below:
   byte[] anArrayOfBytes;
   short[] anArrayOfShorts;
   long[] anArrayOfLongs;
   float[] anArrayOfFloats;
   double[] anArrayOfDoubles;
   boolean[] anArrayOfBooleans;
   char[] anArrayOfChars;
   String[] anArrayOfStrings;
  • The name of the array must follow the naming conventions of a variable.
  • This statement does not really create an array, it just declares it(Tells compiler that this variable holds an array).

Multidimensional ArraysEdit

Multidimensional arrays refer to an array of arrays. There are many types of combinations in a multidimensional array. The syntax for creating such arrays is:

String[][] arrayName = {
   // elements of array 1
   {"Element 1", "Element 2"},
   // elements of array 2
   {"Element 1", "Element 2"},
};

The managing of the outputs of a multidimensional array:

// (element 1 of array 1) + (element 1 of array 2)
System.out.println(arrayName[0][0]) + arrayName [1][0]);

To print the outputs of a multidimensional array:

// in this case, array length is 2
System.out.println(arrayName.length);

A complete example of a multidimensional array is shown below:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        };
        // Mr. Smith
        System.out.println(names[0][0] + names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] + names[1][1]);
    }
}

General Explanation:

  • A multidimensional array named as "names" is created and declared.
  • The elements of array 1 is Mr., Mrs. and Ms..
  • The elements of array 2 is Smith and Jones.
  • The first output asks for the combination of the first element in array 1 and the first element in array 2.
  • The second output asks for the combination of the third element in array 1 and the second element in array 2.

Copying ArraysEdit

A class in the API called System class have a method of arraycopy. You can make use of this method to copy data from one array into another. As shown below is the arraycopy method found in the System class.

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
  • Object src means the array name to copy from.
  • Object dest means the array name to copy to.
  • int srcPos means the starting position of the copied elements.
  • int destPos means the starting position of the copied elements to be pasted from in the new array.
  • int length refers to the number of elements in the copied array starting from the srcPos.

A example of copying an array is shown by the code:

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
			    'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

General Explanation:

  • The elements of the source array(copyFrom) is declared.
  • The magnitude of the second array(copyTo) is set as 7.
  • The preceeding code copies the elements c, a, f, f, e, i, n(starting position - 3rd and number of elements - 7) from the source array into the new array.
  • The output is caffein.

OperatorsEdit

A variable is created and declared, but how to use it? To use it, special symbols or methods called the operators are initialized. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

Precedency of an OperatorEdit

In your Mathematics lesson, the BODMAS rule defines which operation must be solved first before the other. In terms of operators, precedency determines which will be evaluated first before the other. The table below shows the precedency of various operators. 

Precedence Table of Operators
Operator Groups Symbols & Precedency
postfix expr++, expr--
unary ++expr,  --expr,  +expr,  -expr,  ~,  !
multiplicative * or %
additive +,  -
shift <<,  >>,  >>>
relational <,  >,  <=,  >=,  instanceof
equality ==,  !=
bitwise AND &
bitwise Exclusive OR ^
bitwise Inclusive OR ((
logical AND &&
logical OR ((
ternary ?,  :
assignment =,  +=,  -=,  *=,  /=,  %=,  &=,  ^=,  (=,  <<=,  >>=,  >>>=
  • ( represent the symbol |.
  • The precedence of operator symbols from the same group is from left to right.

Assignment, Arithmetic and Unary OperatorsEdit

The Simple Assignment OperatorEdit

One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

int cadence = 0;
int speed = 0;
int gear = 1;

The Arithmetic OperatorsEdit

Arithmetic involves addition, subtraction, multiplication and division. Four basic arithmetic symbols is discussed in your basic Mathematics lesson. The % symbol is the remainder operator. Interpret these codes so you can get a clear picture of arithmetic operators.

class ArithmeticDemo {
    public static void main (String[] args){
        // result is 3
        int result = 1 + 2;
        System.out.println(result);

        // result is 2
        result = result - 1;
        System.out.println(result);
        // result is 4
        result = result * 2;
        System.out.println(result);
        // result is 2
        result = result / 2;
        System.out.println(result);
        // result is 10
        result = result + 8;
        // result is 3
        result = result % 7;
        System.out.println(result);
    }
}

The simple assignment operator = can be added to turn it into an equation to be solved.

x+=1, x=x+1

The + operator can be used to concatenate(combine) two strings together, much like the conjunction and.

class ConcateDemo {
    public static void main(String[] args){
        // first sentence
        String firstString = "This is";
        // second sentence
        String secondString = " a concatenated string.";
        // concatenating the two sentences
        String thirdString = firstString+secondString;
        // to form the third sentence
        // "This is a concatenated string" as the output
        System.out.println(thirdString);
    }
}

The Unary OperatorsEdit

Unary operators show the state of a number, adding and subtracting it by 1.

The Unary Operators
Operator Symbol Function
+, Unary Plus Operator Indicates positive value of numbers. Not important as numbers are positive on their own.
-, Unary Minus Operator Indicates negative value of numbers.
++, Increment Operator Add 1.
--, Decrement Operator Subtract 1.
!, Logical Complement Operator Inverts the value of a boolean type.

An example of the usage of unary operators is shown below:

class UnaryDemo {
    public static void main(String[] args){
        // result is 1
        int result = +1;
        System.out.println(result);

        // result is 0
        result--;
        System.out.println(result);
        // result is 1 
        result++;
        System.out.println(result);
        // result is -1
        result = -result;
        System.out.println(result);

        // success is false
        boolean success = false;
        System.out.println(success);
        // success is true
        System.out.println(!success);
    }
}

A special convention for increment and decrement operators:

  • result++(postfix) evaluates on the result. 1++ = 1+1 = 2.
  • ++result(prefix) evaluates on the incremented value. ++1 = 1+1 = 2.
  • Both will have the same answer in the end.

The following example follows this convention for increment operators:

class PrePostDemo {
    public static void main(String[] args){
        int i = 3;

        // initialize a method that increments i
        // using postfix
        i++;
        // 3+1 = 4
        System.out.println(i);

        // initialize a method that increments i
        // using prefix
        ++i;
        // 1+4 = 5
        System.out.println(i);

        // 1+5 = 6
        System.out.println(++i);
        // 5+1 = 6
        System.out.println(i++);
        // this output must be based off the
        // last method, not the operated
        // method
        System.out.println(i);
    }
}

Equality, Relational and Conditional OperatorsEdit

Equality/Relational OperatorsEdit

In basic Mathematics, inequalities represent the equality of two numbers. In Java, equality or relational operators determine the relationship of two variables with respective primitive data type. These operators are also known as comparison operators.

Comparison Operators
Operator Symbol Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

The example below shows the usage of equality or relational operators:

class ComparisonDemo {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;

        if(value1 == value2)
            System.out.println("value1 == value2");
        if(value1 != value2)
            System.out.println("value1 != value2");
        if(value1 > value2)
            System.out.println("value1 > value2");
        if(value1 < value2)
            System.out.println("value1 < value2");
        if(value1 <= value2)
            System.out.println("value1 <= value2");
    }
}

Output:

  • value1 != value2
  • value1 < value2
  • value1 <= value2

Conditional OperatorsEdit

The operators && and (( perform the logical operations and and or. The following example illustrates the usage of these two common conditional operators.

class ConditionalDemo1 {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;

        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section). This operator is also known as the ternary operator because it uses three operands. In the following example, the instance variable result should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

class ConditionalDemo2 {
    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;

        boolean someCondition = true;
        result = someCondition ? value1 : value2;
        System.out.println(result);
    }
}

General Explanation:

  • The variable value1 and value2 is represented by the literal 1 and 2 respectively.
  • The variable result is kept aside for later. (Instance Variable)
  • The variable someCondition is true.
  • If the variable someCondition is true, assign the value of the variable value1 to the result. Otherwise, assign the value of value2 to the result.
  • The final output is 1(value1).

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following code defines a superclass (named Parent), a simple interface (named MyInterface), and a subclass (named Child) that inherits from the superclass and implements the interface. You will learn more about parts of this code in the later trails.

class InstanceofDemo {
    public static void main(String[] args) {
        Parent obj1 = new Parent();
        Parent obj2 = new Child();

        System.out.println("obj1 instanceof Parent: "
            + (obj1 instanceof Parent));
        System.out.println("obj1 instanceof Child: "
            + (obj1 instanceof Child));
        System.out.println("obj1 instanceof MyInterface: "
            + (obj1 instanceof MyInterface));
        System.out.println("obj2 instanceof Parent: "
            + (obj2 instanceof Parent));
        System.out.println("obj2 instanceof Child: "
            + (obj2 instanceof Child));
        System.out.println("obj2 instanceof MyInterface: "
            + (obj2 instanceof MyInterface));
    }
}​

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {}

Output:

  • obj1 instanceof Parent: true
  • obj1 instanceof Child: false
  • obj1 instanceof MyInterface: false
  • obj2 instanceof Parent: true
  • obj2 instanceof Child: true
  • obj2 instanceof MyInterface: true

Null is not an instance of anything.

Expressions, Statements & BlocksEdit

Operators are used to compute values. Expressions is the combination of variables, operators and methods, like algebraic expressions itself.

ExpressionsEdit

Expressions evaluate to single values. Examples of expressions is shown in bold.

int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3
if (value1 == value2) 
    System.out.println("value1 == value2");

An expression is considered ambigous if its value can have two or more possible values. Like below:

x + y / 100  // can be (x+y)/100 or x+(y/100), ambigous expression

To make the previous expression unambigous, add in brackets ( or ) to differentiate between each operation.

(x + y) / 100  // unambigous expression
x + (y / 100)  // unambigous expression

StatementsEdit

Statements are generally similar to that of normal sentences. A statement forms a complete unit of execution, which it makes an item understandable. There are four main types of statements, each ended with a semicolon character (;).

  • Assignment expressions (assignment statements)
  • Any use of increment and decrement operators (increment/decrement statements)
  • Methods (method invocation statements)
  • Object creation expressions (object creation statements)

An assignment statement are expressions which is made up of a static variable and a literal.

// assignment statement
aValue = 8933.234;

// increment statement
aValue++;

// method invocation statement
System.out.println("statements");

// object creation statement
Bicycle myBike = new Bicycle();

Declaration statements declare a variable. For example, 

double aValue = 8933.234;  // datatype variable = literal;

BlocksEdit

Blocks are groups of statements that are usually the end of related methods. For example, 

class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;

          if (condition) {  // beginning of block 1
               System.out.println("Condition is true.");
          }                 // end of block 1

          else {            // beginning of block 2
               System.out.println("Condition is false.");
          }                 // end of block 2
     }
}

Control Flow StatementsEdit

Control flow statements control statements. Like the common grammar, it limits the code so that the system can conditionally manage/execute these codes.

If-then and if-then-else StatementsEdit

If-then statements are the most basic of all control flow statements. Its meaning can directly be read from its statement. It tells the system to execute this code only if a particular test returns a true value.

void applyBrakes() {
    // if the bicycle is moving,
    if (isMoving){ 
        // then decrease the current speed of the bicycle
        // in other words, apply the brakes
        currentSpeed--;
    }
}

Notes:

  • If the bicycle is not moving(the test returns a false value), then the system will skip this part of code.
  • The braces within the if statement is not a must, meaning those braces can be ommited. As below:
void applyBrakes() {
    if (isMoving)
        currentSpeed--;
}
  • The braces can be ommited as long as only one "then" statement is present.

If-then-else statements is a more precise code of the if-then statement, that is it can execute an opposite method to the "then" if a particular test returns a false value.

void applyBrakes() {
    if (isMoving) {
        currentSpeed--;

    // if the bicycle is not moving
    // then the system simply prints
    // a message that the bicycle has stopped
} else {
       System.err.println("The bicycle has " + "already stopped!");
   }
}

A more precise example is as shown:

class IfElseDemo {
    public static void main(String[] args) {
        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

General Explanation:

  • The testscore of a student is 76. The grade of the student is kept aside for later.
  • If the testscore is more than or equals to 90, A will be assigned to grade.
  • If it returns false for the previous logical test, then if the testscore is more than or equals to 80, B will be assigned to grade.
  • The grades C and D have almost the same meaning as the previous explanation.
  • If all of the previous logical test returns a false value, F will be assigned to grade.
  • The final output is the variable grade with a character literal.

While and Do-While StatementsEdit

The While statement continually executes a block of statements if a particular test returns a true value.

// general syntax
while (expression) {
     statement(s)
}

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. An example is shown below:

class WhileDemo {
    public static void main(String[] args){
        int count = 1;

        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

General Explanation:

  • The count variable is defined as 1.
  • If the count is less than 11, the system prints the output of the value of the current variable. The system also increments each value of the current variable.
  • The while statement continues to operate until the variable count is 11 or more.

A do-while statement evaluates its expression at the bottom of the code, instead at the top like the while statement.

do {
     statement(s)
} while (expression);

An example is shown below:

class DoWhileDemo {
    public static void main(String[] args){
        int count = 1;

        do {
            System.out.println("Count is: " + count);
            count++;
        } while (count < 11);
    }
}

Note:

  • The do-while statement includes the number 11. So the expression becomes count <= 11.

Branching StatementsEdit

Break StatementEdit

Break statements breaks a group of control flow statements. If a logical test returns a true value, the break statement stops the preceeding logical tests that are about to perform.

class BreakDemo {
    public static void main(String[] args) {

        int[] arrayOfInts = 
            { 32, 87, 3, 589,
              12, 1076, 2000,
              8, 622, 127 };
        int searchfor = 12;

        int i;
        boolean foundIt = false;

        for (i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at index " + i);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

Note:

  • If the for statement returns a true value, the break stops the system from performing other tests on that item.
  • You will learn more about the for and break statements in the Java Language Specifications area.

Continue StatementEdit

Continue Statements join an if statement with a method.

class ContinueDemo {
    public static void main(String[] args) {
        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

Note:

  • If a "p" is found, the system increments the numPs++ variable.
  • You will learn more about the continue statements in the Classes & Objects trail.

Return StatementEdit

Return Statements exit the flow of execution in a code and returns to where the method was declared. There are two forms of return statements:

  • One that really returns a value.
return ++count;  // General syntax: return valueorexpression;
  • One that doesn't return any value.
return;  // The general syntax
public void count {  // The alternative, appears on the method declaration

Summary of Language Basics TrailEdit

VariablesEdit

  • Four Types of Variables
  1. Instance Variables (Non-static)
  2. Class Variables (Static)
  3. Local Variables
  4. Parameters
  • Variable Declarations
  1. Naming Conventions
  2. Primitive Data Types and Default Values
  3. Literal and Literal Conventions
  • Arrays
  1. Array Structure
  2. Creating Arrays
  3. Array Declarations
  4. Multidimensional Arrays
  5. Copying Arrays

OperatorsEdit

  • Precedence Table of Operators
  1. Precedency of Operators
  • Types of Operators and their Usage
  1. Simple Assignment Operator
  2. Arithmetic Operators
  3. Unary Operators
  4. Equality or Relational Operators
  5. Conditional Operators

Expressions, Statements and BlocksEdit

  • Expressions
  1. Ambigous and Unambigous Expressions
  • Statements
  1. Assignment Statements
  2. Increment/Decrement Statements
  3. Method Invocation Statements
  4. Object Creation Statements
  • Blocks
  1. Identification

Control Flow StatementsEdit

  • If-then and If-then-else Statements and their Usage
  • While and While-do Statements and their Usage
  • Branching Statements
  1. Break Statements
  2. Continue Statements
  3. Return Statements

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.