Java – Jump Statements

break statement

In several instances, such as an error or incorrect input from the user, it may be necessary for the flow of control to exit from a loop statement. To accomplish this, Java provides a jump statement called break statement.

The break statement forces the control to come out from a switch statement, a while loop, a do-while loop or a for loop. After the control moves out of a switch statement or any loop statement, it moves to the statement after the loop or switch statement.

SYNTAX:

break;

The break statement is written as break; without any expression.

Example

Consider a program that prints the value stored in a variable until the specified condition is false. The program ends when the value becomes equal to the value stored in another variable.

'break' statement example

The break statement has been used to enable the program to end when the value in the i variable becoes equal to the value in the num variable. If the value in the i variable is less than 10, the flow of control enters the for loop. When the code is executed, the program displays the numbers from 0 to 3.

Labelled Brake statement

In a nested loop, the break statement used in an inner loop transfers the flow of control to the immediate outer loop. In certain situations, you may also want the flow of control to exit the outer loop. In this case, you use the break statement with the label identifier.

SYNTAX:

break label_name;

The label identifier is used to group a loop statement that contains another loop statement or a switch statement and to specify the name for the group. The label identifier is specified just before a loop statement without any expression like ‘label_name: ‘.

Example

label1:

For example, to name the loop statement label1, you write label1: in the line preceding the loop statement.

When the brake statement is used with the label_name, the flow of control is transferred to the statement after the labeled loop.

Labelled Brake Statement - Example

Consider the code displayed above. that displays the value stored in variable ‘i’ until the condition specified in either of the for loops becomes false. The program terminates if the value of ‘i’ becomes equal to that of ‘num’. In the code shown above, a label statement, ‘label1:’ has been used to group the two for loops.

When the value of the ‘i’ variable becomes equal to the value of the ‘num’ variable, the program executes the labeled brake statement. This transfers the flow of control outside label1. Therefore, the print statement outside the nested for statement is not executed.

HINT: You cannot use the break statement without a switch statement or a loop statement.

Java – Iterative Flow Control

While Statement

Java provides certain loop statements, which you can use to perform an action repeatedly. These statements are called Iterative Statements. One of the loop statements is the while statement.

SYNTAX:

while (condition) {
loopbody
}

The ‘while’ statement contains a condition and a loopbody. The condition is enclosed within parentheses. All the variables used in the condition of the while statement must be initialized before the while loop. The values of the variables used in the condition must be changed in the loopbody. Otherwise, the condition may always remain true and the loop may never end. You change the values of the variables by performing various operations on the variables. You can write a single statement or multiple statements in the loopbody. Multiple statements should be enclosed within braces. Otherwise, the code may generate an unexpected output.

How ‘While’ Works

How While Statement works

Before the loopbody is executed, the condition of the while statement is evaluated. The loopbody is executed only when the condition evaluates to true. Therefore, the while loop is also called a top tested loop. After the loopbody is executed, the while condition is evaluated again. The sequence of the evaluating the condition and executing the loopbody continues until the while condition becomes false.

Example

Lets see a example program that stores two numbers in the variables [Lets say num and n]. The output should display the numbers from 0 to the number stored in the num variable.

In the code displayed below, the while statement specifies the condition that the value of n should be less than or equal to the value of num. Line 1 and Line 5 contain the opening and closing braces of the while loop. In Line 3, the value of n is printed on the screen. In Line 4, the value of n is incremented by 1.

When the program is executed, it displays the numbers from 0 to 5.

In Line 1, the condition is that the value of n should be less than or equal to the value of the variable num. The value of the variable num is 5. The initial value of n is 0, which is less than the value of num. Therefore, the condition is true and the flow of control moves inside the while loop. Inside the loop, the value of the variable n is displayed in the first row. This value is 0. Next, the flow control executes Line 4. As a result, the value of the variable n becomes 1. The flow of control moves back to Line 1, where the value of the variable n is again compared with the value of num. The value of the variable n is 1. Therefore, it is still less than the value of num, which is 5. The condition in Line 1 evaluates again to true, and the flow of control again moves inside the while loop. The value of the variable n is printed in Line 3. This looping continues until the value of n becomes 6. The flow of control moves out of the while loop, and the program terminates.

Infinite While Loops

If a semicolon is added after the condition in the while statement in a program, the program may result in an infinite loop. This is because the control never comes out of the while statement.

For Example:

If we modify the Line 1 of example program like this

while (n <= num); {

the program will result in an infinite loop.

do-while statement

The do-while statement is a loop statement similar to the while statement provided by Java. It is used to perform certain repetitive actions depending on a condition.

SYNTAX:

do {
loopbody
} while (condition);

The do-while statement begins with the ‘do’ keyword followed by the loopbody. In the loopbody, you can write a single statement or multiple statements enclosed within braces. The while statement is written after the closing brace. The while statement contains the condition enclosed in parentheses. In the do-while statement, you add a semicolon after the condition. The semicolon indicates the end of the do-while loop.

How ‘do-while’ Works

The major difference between the do-while statement and the while statement is that in the while statement, the loopbody is executed only when the condition stated in the statement is true. In contrast, the do-while statement in the loopbody is executed at least once, regardless of the condition evaluating to true or false.

'do-while' flow

After the loopbody is executed once, the condition in the do-while statement is checked. If the condition evaluates to true, the loopbody is executed until the condition becomes false. Therefore do-while loop is also called a bottom-tested loop.

You can use the do-while loop in situations where an action must be performed at least once without evaluating the condition.

Example

Consider a program that stores a number in a variable. The program displays all the numbers in descending order starting from the number stored in the variable until it encounters the number 0.

do-while example

The program shown above displays the do keyword and further decrements the value of the count variable that is added. After the count variable is decremented, we specify the condition to check whether the value is equal to 0 like this [while (count != 0);]. The closing brace of the main function and the class declaration is added.

Upon compilation and execution, the output displays all the number from 1 to 4 in descending order.

For Statement

Java provides the for statement to manage iterative actions as an efficient alternative to the while statement. The for statement creates a loop in which a set of statements is repeatedly executed until the specified condition becomes false.

SYNTAX:

for (initialization expressions; test condition; update expressions) {
loopbody;
}

The for statement starts with the ‘for’ keyword. This statement has three elements enclosed within parentheses. The first element of the for statement consists of initialization expressions. This element is an assignment statement. The assignment is done only once before the for statement begins execution. The second element, test condition, is evaluated before each iteration of the for statement. This element determines whether the execution of the for loop should continue or terminate. The third element in the for statement consists of the update expressions. These expressions change the values of the variables used in the test condition. Update expressions are executed at the end of each iteration after the loopbody is executed. The elements of a for statement are seperated by semicolons. You can use multiple statements in the initialization and update expressions of the for statement by seperating them with the comma operator. The multiple statements are evaluated from left to right.

EXAMPLE: Multiple initialization and update expression

for (x = 1, y = 2; test condition; x++, y++) {
loopbody;
}

Another Form

In the for statement, you can omit the initialization expressions and update expressions elements but you must provide two semicolons in the parentheses.

If you are not including the initialization and update expressions elements in the for statement, you must specify the initialization expressions element before the for statement. The update expressions element must then be specified inside the for loop.

SYNTAX:

initialization expressions;

for (; test condition;) {
update expressions;
loopbody;
}

Infinite For Loop

The test condition must be provided in the for statement. If you omit the test condition from the for statement, the program results in an infinite loop when executed. The program will also result in an infinite loop if none of the expressions is specified in the for loop.

SYNTAX:


for (initialization expressions; ; update expressions) {
loopbody;
}

for (;;) {
loopbody;
}

How ‘For’ Works

for (j = 2; j <= 10; j++) {
System.out.println(j);
}

How 'For' Works

In the for loop, the variable j is initialized to 2. Next, the value of j is compared with 10. If the test condition is true, the value of j is displayed on the screen. Next, the value of j is incremented by one. After the value of j is incremented, the test condition is evaluated again. If the test condition evaluates to true, the print function is executed again. If the test condition evaluates to false, the flow of control comes out of the for loop. The for statement creates a loop that is identical in function to the while statement. For loops are more useful when you have a fixed number of iterations and you need a counter. The for loop is also more compact. You can use the for statement to reduce the size of code.

HowTo: Personal Folders in Outlook Express

Outlook Personal Folders can be used to provide additional storage for emails, in order to free up space in your Exchange mailbox on the server.

Remember that the Personal Folders file is stored on your hard disk, so it is your responsibility to back it up regularly, in the same way that you would back up any other file on your computer. They can get very large, so you will probably need to backup to CD.

Installing the Java Development Kit

Java – Conditional Flow Control

If Statement

In certain solutions, it may be necessary to write code to perform various actions based on a user’s inout or certain criteria. To perform these actions, Java provides certain decision-making statements such as the if statement.

You may want to write a program to accept numbers from 0 through 9 from a user. If the number typed is from 0 through 9, it is to be displayed on the screen. Otherwise, a message stating that the typed number is invalid is to be displayed. To perform these actions, you use the if statement.

SYNTAX:

if (expression) {
if_body;
}

The if statement is used to enable the selective execution of statements in a program. The if statement has three forms: the simple if form, the if-else form.

The execution of the if statement involves the evaluation of the specified condition. The evaluated result of the condition is a boolean expression. If the condition evaluates to true, the if_body part of the if statement is executed.

If you want more than one statements to be executed in the if_body part of the if satement, enclose the statements within the braces. You should always use braces on conditional statements even when there is only a single statement. If you use multiple statements in the if_body part without braces, the intented output is not generated. The compiler treats the first statement as the if_body part. The remaining statements are not executed as a part of the if statement.

if (expression); {
statement;
}

Placing a semicolon on the if statement, terminates the statement. The line following the if statement will not be included in the if statement when this is done. Therefore, even if the condition is false, the statement after the if statement will still be executed.

If-else Construct

The simple form of the if statement is inefficient when actions are performed depeneding on whether the result of an expression is true or false. This is why two if statements are needed to handle the two states. In such situations, you use the if-else construct in the code.

SYNTAX:

if (expression) {
if_body;
} else {
else_body;
}

The if-else construct is another form of the if statement. This form can handle both the true and false values of an expression. The syntax of the if-else construct is displayed on the screen. If the expression in the syntax evaluates to true, the if_body part of the statement is executed, otherwise the else_body part is executed.

Fig: Flowdiagram


The flow diagram displayed above illustrates the flow of control in an if-else statement. If the expression evaluates to true, the control executes the if_body. If the expression evaluates to false, the control executes the else_body.

The if-else construct is more efficient than the simple if statement. In the if-else construct, only the if_body part or the else_body part of the code is executed at a time. Both parts are never executed together.

Within the if-else construct, you can use other if statements. The if statements contained within other statements are called nested statements. You can use nested if-else statements to perform actions based on multiple conditions at one time.

Using many nested if-else statement complicates nesting of if statements and can make code difficult to follow. In addition, you should always use braces even when only a single statement is contained in the if clause. This reduces bugs and makes code easier to read.

If-else-if Construct

To perform various actions based on multiple conditions at one time you can use the if-else-if construct. This construct is another form of the if statement.

SYNTAX:

if (expression1) {
body1;
} else if (expression2) {
body2;

….

} else {
bodyN;
}

The body1 and body2 parts of the if-else-if construct indicate the statements that will be executed if the respective conditions evaluate to true. If neither of the conditions evaluates to true, the bodyN part of the if-else-if construct will be executed.

Conditional Operator

The Java language provides an operator to handle situations, where different actions are performed, based on the evaluation of a condition. The conditional operator is used for this task. It is also called the ternary operator, and it is represented by the question mark sign (?) and the colon sign (:). This operator is an efficient alternative to a simple if-else construct.

SYNTAX:

expression1 ? expression2 : expression3;

The expression1 must be a boolean expression. If this condition is true, the expression to the right of the question mark, expression2 is evaluated. If the condition is false, the expression to the right of the colon, expression3 is evaluated.

EXAMPLE:

x=(a>b)?a:b;

Equivalent If-else Construct

if (a>b) {
x = a;
} else {
x = b;
}

switch statement

The switch statement is a conditional statement that branches to various alternative actions. You can use this statement to perform various actions based on the evaluation of a single expression. The switch statement can be used instead of the if-else-if construct if the condition evaluates to an integer value. This integer value must evaluate one of the 32-bit or smaller integer types, such as byte, char, short or int.

SYNTAX:

switch (expression) {
case value 1:
statement1;
break;

case value 2:
statement2;
break;

case value N:
statementN;
break;

default:
statement1;
break;
}

Java Operators

Operator define the actions to be performed on the operands in an expression. Depending on the number of operands on which an operator acts, operators are classified as unary, binary, and ternary operators.

Unary operator act on a single operand. Binary and ternary operators act on two and three operands respectively.

Unary Operator

They are of three types: minus, increment and decrement.

Then minus operator is represented by the minus (-) symbol. It acts on a variable or constant that follows the operator. The minus operator indicated that the value of the operand on which the operator acts is negated. A variable containing a negated value becomes a postive.

Example: -(-6) would be 6.

The increment operator is represented by two plus(++) signs. It causes the value of its operand to be increased by the value 1. The increment operator can be placed before or after the operand. If the increment operator precedes an operand, then the value of the operand will be increased by the value 1 before a statement in a program uses the operand. This type of increment is called prefix increment. [Refer Fig 1.1]

Fig 1.1-Prefix Increment

If the increment operator follows an operand, then the value of the operand is altered after the operand is utilized in a specifix statement in a program. This type of increment operator is called a postfix increment operator. [Refer Fig 1.2]

Fig 1.2-Postfix Increment

The decrement operator is represented by two minus(–) signs. The decrement operator causes an operand to be decreased by the value 1. It can be placed before or after an operand to perform a prefix or postfix decrement operation. The operation of the decrement operator is similar to the increment operator. However, the effect of the decrement operator is to decrease the value of the operand on which it acts.

Arithmetic Operators

To perform arithmetic operations or calculations in a program, you use the arithmetic operators in expressions. The expressions that contain these operators are called arithmetic expressions. There are five arithmetic operators: the slash mark (/), the asterisk (*), the percent sign (%), the plus sign (+), and the minus sign (-). These operators represent division, multiplication, remainder, addition, and subtraction operations respectively.

The operands with which arithmetic operators work must have numeric values. Therefore, operands, or their values can be integers or real numbers.

Arithmetic operators have a specific order of evaluation. This order of evaluation is called precedence. The division, multiplication, and remainder operators belong to one precedence group. The addition and subtraction operators belong to another precedence group. The group of the division, multiplication and remainder operators has precedence over the group of addition and subtraction operators.

When evaluating arithmetic expressions, the order in which consecutive operations occur within the same precedence group is called associativity.

Within each precedence group, the associativity of arithmetic operators is from left to right. The consecutive division, multiplication, and remainder operations are carried out from left to right in the order of their occurrence.

EXAMPLE

12/4*2 = 6
Division is performed first and then multiplication.

15+6-3=18
Both operators + and – belong to the same precedence group, and their associativity is from left to right. In the example, addition is performed first. Next, subtraction is performed.

You can alter the precedence of arithmetic operators by using parentheses. Parentheses have precedence over all arithmetic operators. You can also have nested parentheses in an expression. The innermost parentheses have precedence over the outer parentheses.

EXAMPLE

(8*(x+y))
Here the addition of x and y is carried out first and the sum is then multiplied by the value 8.

HINT:
Operator Precedence = BEDMAS Rule
B – > Brackets [Parentheses]
E – > Exponential
D – > Division
M – > Multiplication
A – > Addition
S – > Subtraction

Assignment Operators

To assign a value to a variable, an assignment operator is used.

SYNTAX:
var = expression

The assignment operator is represented by the equal to symbol (=). A statement that contains the assignment operator is written as var=expression. The variable var stores the value of the expression.

EXAMPLE:
age = 25
total = a + b

In the statement total=a+b, the sum of a and b is assigned to total. Such assignments are called single assignments.

In addition to a single assignment, multiple assignments are also possible in Java. This means that two or more variables can be assigned the same value by using the assignment operator.

EXAMPLE:
var1=var2=10
Assigns the value 10 to the variables var1 and var2.

In addition to the assignment operator, Java has compound assignment operators. These are +=,-=,*=,/= and %=.

Compound assignment operators enable you to write shorthand notation expressions.

EXAMPLE
var1+=var2;
This is equivalent to var1 = var1 + var2;

var1 -= exp ====> Equivalent to var1 = var1 – exp
var1 *= exp ====> Equivalent to var1 = var1 * exp
var1 /= exp ====> Equivalent to var1 = var1 / exp
var1 %= exp ====> Equivalent to var1 = var1 % exp

Assignment operators have right to left associativity. This indicates that in the expressions that contain assignment operators, the expression is evaluated from right to left.

Relational Operators

Relational operators are used for comparing values and taking appropriate actions based on the comparison. For example, a program calculates the levels of the employees in a department by comparing their salaries with different values.

The result of the expression containing a relational operator is either true or false. Relational operators accept two operands.

There are six relational operators in java: greater than (>), less than (<), less than or equal to (<=), greater than or equal to (>=), equal to (==), and not equal to (!=).

EXAMPLE

if (salary < 50000) {
Level = B
}

if (salary >= 50000) {
Level = A
}

If the salary is below $50000 a year, an employee is categorized as a level B employee. If the salary is $50000 or above in a year, the employee is categorized as a level A employee. To determine the level of an employee, the salary of the employee has to be compared with the value 50000.

If the salary of an employee is $50000 and is stored in the variable empSal, the expression empSal<50000 compares the value of empSal with 50000 by using a relational operator.

The equal to and not equal to operators are also called equality operators.

Relational operators have a precedence that determines the order in which they are evaluated in a multiple-operator expression. The operators greater than (>), less than (<), less than or equal to (<=), and greater than or equal to (>=) fall into one precedence group. The equality operators equal to (==) and not equal to (!=) fall into another precedence group. The equality operators have a lower precedence than other relational operators.

The associativity of relational operators is from left to right. Therefore, in an expression that contains more than one relational operator from the same precedence group, the expression is evaluated from left to right.

Logical Operators

Logical operators enable you to combine and compare two conditions

EXAMPLE:

If basePay is below $2000 and above $1000, allowance is 10% of basePay.

This means that an employee receives the allowance only when both these conditions are satisfied. The result of an expression that contains a logical operator is either true or false.

There are six boolean logical operators.

  • Boolean Logical AND – &
  • Boolean Logical OR – |
  • Boolean Logical XOR – ^
  • Conditional AND – &&
  • Conditional OR – ||
  • Boolean Logical NOT – !

In Java, there are two short-circuit logical operators. These are Conditional AND (&&) and Conditional OR (||). Java does not evaluate the operand on the right when the result can be determined by the operand on the left only. This can be important when there are side affects from the operand on the right.

The &&,||,&,| and ^ are binary operators. The ! operator is a unary operator.

Associativity relates to precedence and resolves any ambiguity over the grouping of operators with the same precedence. The associativity of the &&,||,&,|, and ^ operators is from left to right.

The && operator evaluates two subexpressions, Op1 and Op2, and generates the value true only if both the subexpressions individually evaluate to true. The result of the expression that combines the expressions oP1 and oP2 by using the && operator is false if either oP1 or oP2 evaluates to false.

If two expressions, op1 and op2 are combined using the || operator, the result of the combined expression is true if either op1 or op2 evaluates to true.

The ! operator negates the value of an expression. This indicates if the value of an expression op1 is true initially, the ! operator alters its value to false. If the value of an experssion, op1 is originally false, the ! operator alters the value to true.

The & operator works the same as the && operator, except that the operand on the right is always evaluated. The expression evaluates to true only if both of the operands are true.

The | operator works the same as the || operator, except that the operand on the right is always evaluated. The expression evaluates to true if either of the operands are true.

The ^ operator is the exclusive OR (XOR) operator. The expression evaluates to true if only one of the operands is true. If both operands are false or both operands are true, the expression will evaluate to false.

Bitwise Operators

It enables you to calculate the result of an expression by using the individual bits of the operands in the expression. There are four bitwise operators in Java: AND, OR, XOR, and NOT. These operators are represented by the symbols &, |, ^, and ~ respectively. The AND, OR, and XOR operators are binary operators. The NOT operator is a unary operator.

The AND operator evaluates the binary equivalent of the two operands, op1 and op2 and generates 1 if the value of both the operands is 1. If the value of any of the operands is 0, the result is 0.

The OR operator results in the value 0 when the value of both the bits is 0. Otherwise, the result of the OR operation is the value 1.

The XOR operator is an exclusive OR operator. This operator results in the value 1 if the two operand bits are different. Otherwise, the result of the XOR operation is the value 0.

In addition to the bitwise operators, some shortcut assignment operators perform bitwise operations. These assignment operators are &=, |=, ^=.

The &= shortcut assignment operator works the same as & operator and the results are assigned to op1. If the value of the corresponding bits in both operands is 1, then the operator generates a result of 1, otherwise the result is 0.

The |= shortcut assignment operator works the same as | operator and results are assigned to op1. If the value of the either, or both of the corresponding bits in both operands is 1, then the operator generates a result of 1, otherwise the result is 0.

The ^= shortcut assignment operator works the same as ^ operator and the results are assigned to op1. If the value of only one of the corresponding bits in both operands is 1, then the operator generates a result of 1. If both of the corresponding bits are 0 or 1, the result is 0.

Related Posts: Introduction to Java | Classes, Methods & Objects | Objects and Variables | Datatypes | Conditional Flow Control | Iterative Flow Control | Jump Statements

Introduction to Java

Java is the key to developing platform-independant programs. Therefore, it is the ideal option when diverse hardware platforms and OSs need to be supported.

GOSSIP:
Java was designed at Sun Microsystems, Inc in 1991 and was initially called Oak. It was renamed Java in 1995.

Java was designed to be compatible with different platforms used by computers connected to the Internet. The compiled code of a Java Program can be executed on different platforms without any changes. This is possible because of bytecode that is generated during the compilation of source code. Bytecode is a highly optimized set of instructions that is executed by the Java run-time system called Java Virtual Machine (JVM). The JVM acts as an interpreter for bytecode.

Java Source Files


Fig 1.1 – Java Source Files

A Java source file contains three sections. The first setion is the package section that contains a single line of code that specifies the package to while the source file belongs. The package statement may be omitted, in which case the default package will be assumed.

The second section is the import section. This section includes import statements that tell the compiler which packages to include. The import section may be omitted. The compiler will automatically import the java.lang.package that includes the most commonly used Java classes and interfaces.

The third section includes the class or interface definition. This is where all of the remaining Java code for the source file will be placed. There can only be one top-level public class or a single public interface defined in a source file.

A Java source file must be named with the same name as the top-level class or interface, if that top level class or interface is defined as public. The extension .java is appended to the name to form the source file name. In our example, it would be HelloWorld.java

Java Compiler ignores extra white spaces. So you can use..hell lots of space to make your code more readable.

Comments are used to annotate the code. The compiler will strip the comments from the code during compilation. It is a good idea to use comments to explain code that may be confusing. Comments are also used for producing Javadoc documentation such as the Java API reference.

There are two types of comments that can be coded into a Java source file.

Type 1: Multiple line comments

Syntax:
/* blah blah blag */

Example:
/*
Blah
Blah
*/

Type 2: End-of-line comment

Syntax:
// Blah

Hello World Program

Java Keywords

Related Post: Classes, Methods & Objects | Objects and Variables | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

DataTypes and Variables

Data Types

Integer Data Type

Floating Point Data Type

Java provides two floating-point data types as specified by the IEEE-754 standard. These are the float and double data types. The float type represents single-precision numbers while the double type is used for double-precision numbers.

You suffix the value assinged to a float variable with the character f. This is done because the decimal value assigned to a variable is taken as a double data type value by default.

Character Data Type

Useful for storing alpha numeric characters. 16-bit type. It does not accept negative values. A Character literal is assigned to a variable by using single quotation marks.

Syntax: char blahVar;

Range: 0 to 65,535.

Boolean Data Type

A variable of the boolean data type can store only two possible logical values, true and false. It is defined using the boolean keyword.

Syntax: boolean blahVar;

Boolean values are returned when the relational operators are evaluated. The boolean data type is also used to direct the conditional expressions that govern control statements.

HINT: What are control Statements?
They are used in a Java Program to guide the flow of execution to advance and branch depending on the changes made to the data values that are used in the conditional expressions.

String Data Type

Syntax: String blahVar;

A String can contain any combination of 0 or more characters and may also be null. The variable can also store characters such as the slash sign (/). the parentheses signs ( () ), the colon sign (:), and the semicolon sign (;)

Java implements strings as objects of the String data type instead of as character arrays. String objects are immutable. When an object of the String data type is created, you cannot change the characters that are part of that string.

Whenever you change an existing string, a new String object is created that contains the modifications to the existing string. In specific cases where a modifiable string is essential, there is a companion class attached to the String class called StringBuffer. StringBuffer objects represent strings that can be modified after they are created.

A String constant enclosed within double quotation marks can be assigned to a String variable. You cannot perform mathematical calculations on a String object because it does not support operators. An exception to this rule is the addition operator (+). It is used to concatenate two strings and to generate a String object as the result.

HINT: (+) Operator is the best example for polymorphism.

Variables

Declaring Variables

Syntax:

datatype variableName;

Example:

int sum;

Variable Initialization

Before using a variable in a Java program, you must assign a valid initial value to the variable. This process is called initialization. A variable must be declared and initialized before it can be used in a Java program.

Syntax:
variable_name = value;

Example:
int x=13;
float y=23.4f;
z = 92 + 123;

You can also simultaneously declare and initialize a variable.

Syntax:
datatype variableName = value;

Related Posts: Introduction to Java | Classes, Methods & Objects | Objects and Variables | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

OOP Concept – Encapsulation

Overview

Encapsulation allows an object to separate its interface from its implementation. The data and the implementation code for the object are hidden behind its interface.

Encapsulation hides internal implementation details from users.

Example:
A Customer may issue a check and now know how it is processed. The internal processing is hidden from the customer. Similary, the inessential attributes of a class are hidden from users by using encapsulation. The hidden attributes of a class are called protected attributes.

It ensures that an object supplies only the requested information to another object and hides inessential information.

Example: When a user selects a command from a menu in an application, the code used to perform the actions of that command is hidden from the user.

Encapsulation packages the data and method of an object and provides protection from external tampering by users. It implies that there is visibility to the functionalities offered by an object, and no visibility to its data. The best application of encapsulation is making the data fields private and using public accessor methods.

However, you cannot hide an entire object. To use an object, a part of it needs to be accessed by users. To provide this access, abstraction is used. Abstraction provides access to a specific part of data while encapsulation hides the data. Therefore, abstraction and encapsulation compliment each other.

In OOP, abstraction defines the conceptual boundaries of an object. These boundaries distinguish an object from another objects.

Example: When a user designs an application by using existing templates, the complexity of the template is hidden from the user, but the essential features for creating the application are provided to the user. Abstraction enables an object to display these essential features to develop an application.

Encapsulation and Inheritance are two key concepts in OOP that serve different purposes. While encapsulation hides inessential information, inheritance allows the object of a class to adopt the attributes of another class.

When you implement inheritance in an application, the classes in the application are arranged in a strict hierarchy. The classes at the lower levels inherit the attributes of the classes at the higher levels.

In addition to inheriting the characteristics of the parent class, a class may have its own attributes. This feature implies that the code and characteristics of a class are reusable and extensible. However, inheritance compromises encapsulation because a subclass can directly access the parent’s protected attributes without using operations.

Related Post: Introduction to OOP | Inheritance | Polymorphism

OOP Concept – Polymorphism

Overview

Polymorphism means one entity existing in multiple forms. It provides flexibility to application systems. It simplifies coding and reduces the rework involved in modifying and developing an application. It refers to the ability of an object to take on different forms depending upon the situation.

According to the polymorphism design principle, the same message sent to different objects results in different behavior. The behavior depends on the type of object that receives the message.

Example:
Every key of a keyboard performs a specific action when a keystroke message is generated for that key. However, by using polymorphism, the same code with a small change can be used by different keys of the keyboard to trigger specific actions.

Polymorphism and Classes

In Java, type polymorphism may be implemented using class inheritance, interface implementation, or both. When using class inheritance to implement polymorphism, a class instance may take the form of itself, or any of its superclasses.

Fig 1.1

[Refer above Fig 1.1] When an instance of a class is created, it may always be referenced using its own type. Although this seems obvious, it is important because it is one of the forms that the object instance may take. In addition, since every class in Java has the class Object as a base class, the instance may also always be referenced as an Object.

When a class has a superclass, an instance of the class may also be referenced as if it is the superclass. For example, if a class Car is derived from the class Vehicle, an instance of Car may be referenced as a Vehicle. The possible type references for an instance of the Car class are shown below [Refer Fig 1.2].

Fig 1.2


Fig 1.3

[Refer Fig 1.3] A class instance can be referenced as any of the superclass types regardless of the depth of the inheritance

Example:
The class Mustang, which derives from Car, which derives from Vehicle. Here an Instance of the Mustang class may be referenced as any of its superclasses.

An instance of a class is also considered an instance of its superclass. The ‘instanceof’ operator can be used to show this relationship. When an object is an instance of a class, it is called an is-a relationship. The below example shows that the instance of the Mustang class, is also an instance of all of its superclasses. [Refer Fig 1.4,1.4a]

Fig 1.4

Fig 1.4a

Polymorphism and Interfaces

Fig 2.1

When an instance of a class is created, it may always be referenced using its own type. Refer Fig 2.1

If a class implements an interface, it may be referenced as the interface type. For example, a class CDPlayer implements MusicPlayer interface.[Refer Fig 2.2]

Fig 2.2

A class may implement as many interfaces as necessary. The example [Refer Fig 2,3] shows a new interface called MusicRecorder. The class CDPlayerRecorder implements the MusicPlayer and MusicRecorder interfaces.

Fig 2.3

When a class implements multiple interfaces, an instance of the class is considered an instance of the interfaces that it implements. Therefore, the class can be referenced as if it is any of its implemented interfaces.[Refer Fig 2.4]

Fig 2.4

An interface may extend other interfaces. When an interface extends other interfaces, a class that implements the interface also implements the extended interfaces. An instance of the class may be referenced using any of the interfaces, including the extended interfaces.[Refer Fig 2.5]

Fig 2.5

If a class has a superclass that implements an interface, an instance of the class may be referenced using the interface type.

Example: We have a CDPlayer class that implements the MusicPlayer interface. If we have a class CustomCDPlayer that derives from the CDPlayer class, the instance of the CustomCDPlayer may be referenced as a MusicPlayer. [Refer Fig 2.6]

Fig 2.6

Since a class may have superclasses as well as implemented interfaces, it therefore may be referenced both as superclass types and interface types.

Example: [Refer Fig 2.6] a CustomCDPlayer instance may be referenced using both the superclass CDPlayer, and the interface MusicPlayer.

Valid Variable Assignments

Java allows you to assign variables of a derived class with the instances of the base class and vice versa.

Upcasting:

When a derived class extends a base class, the derived class inherits all the members of the base class. It may also contain some additional methods and fields. In Java, you can assign an instance of the derived class to a variable type of base class.

Example: [Refer Fig 3.1]
Consider a class Wind that extends class Instrument. In this case, the class Wind inherits the methods of the class Instrument. In this case, the Wind derived class is a superset of the base class Instrument. It might contain more methods than the base class.

Fig 3.1

Downcasting:

Fig 3.2

It refers to assigning a variable of a base class to an instance of a derived class. This implies that the variables of the base class can be initialized to the base class or to one of the derived classes. [Refer Fig 3.2] If class Wind extends Instrument, you can initialize the variables of class Instrument to the instances of class Wind or class Instrument.

When downcasting, you should explicitly indicate a variable of type Brass to one of the variables of type Instrument. A faulty cast construct can cause a run-time error. If a base class is assigned to a derived class without a cast construct, it can lead to a compilation error. [Refer Fig 3.3]

Fig 3.3

Related Post: Introduction to OOP | Inheritance | Encapsulation