Author Archives: IDYN

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

OOP Concept – Inheritance

Basics

Different kinds of objects often have a certain amount in common with each other. Tiger & Cow, for example share the characteristics of Animal; Yet each also defines additional features that make them different. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

Inheritance provides a way to extend existing classes to make a new classes with specialized behavior. Inheritance creates a hierarchy of classes and helps you reuse the code of a parent class in a child class.

A Class inherits the attributes and behavior of its parent class or superclass. The attributes and behavior of the superclass need to be public or protected. Members of the superclass can be inherited with some restrictions.

Subclasses inherit the superclass members that are declared with no access modifiers, if the subclasses are in the same package as the superclass.

Example:

Tiger and Cow are the subclasses of the Animal class. Animal class contains all common behaviors and states that belong to animals [tiger or cow] however Tiger / Cow has distinct behaviors too. These are defined in their respective classes. Tiger & Cow classes are called subclasses because they are derived from the Animal class – the super class. They inherit the attributes and behavior of the Animal class. The subclasses may also define more attributes and behavior.

Syntax:
<<Access modifiers>> class <subclass name> extends <superclass name>

<<Access modifiers>> – default access [nothing] or public access [public keyword]

There are two types of inheritance, single inheritance and multiple inheritance.

Single Inheritance: A subclass inherits from a single class.
Multiple Inheritance: A class inherits from more than one immediate superclass.

HINT: Java classes cannot extend multiple classes. In Java, Only interfaces are allowed to extend multiple interfaces. Also, classes can implement multiple interfaces.

Although a subclass inherits all the members of its superclass, it cannot access the private member variables of the superclass. The public and protected member variables of the superclasses are accessible to a subclass. If the subclass is in the same package as the superclass, default members are also accessible.

Method Overridding

A subclass inherits members and methods from its superclass. However, a subclass can change the functionality of an inherited method by overriding the method.

Encapsulation allows an object to supply requested information to another object.
Overriding is the ability of a subclass to modify the behavior that it inherits from the superclass. By overriding a method, the developer is free to charge the implementations of the method in the subclass.

In Java terminology, the method in the subclass that has the same name and signature as a method in the superclass is called the overridding method. The method in the superclass is called the overridden method.

Example: Consider the class Employee that contains a method named calculateSalary. Consider Manager and Engineer subclasses that extend Employee Class. The process for calculating salary for Manager and Engineer are different from each other. And So, to solve this problem, you can override calculateSalary method of Employee class and provide different implementations in Manager and Engineer class seperately.

Guidelines for Overriding a Method

  • The overriding and overridden methods should have the same return type, method name, and the number, type, and order of arguments.
  • The overriding method should have equal or greater access than an overridden method.

‘Super’ Keyword

The ‘super’ keyword is used when a subclass needs to refer to its immediate superclass.

Constructor Overriding

Constructors contain code that initializes an object during instance creation. The object should be properly initialized. This is to ensure that the object is not in an invalid state and is usable.

A subclass calls a constructor defined by its superclass by using the ‘super’ keyword.

Syntax: super(arg 1, arg 2, ..);

In the displayed syntax, the super keyword specifies any arguments required by the constructors in the superclass. An implicit call to the zero argument is made, if the method does not appear on the first line of the subclasses constructor. The super method needs to be the first statement in a subclass constructor. These constructors run regardless of whether the super method exists. If the super method is not used, the default constructor of each superclass is automatically executed.

Final Classes

A Class than cannot have subclasses and the member variables of which cannot be overridden is called final class.
Similarly, methods and variables that cannot be overridden are called final methods and final variables, respectively.

When a class is declared as final, the class cannot be extended. Therefore, a final class cannot have subclasses. This provides security because other application developers cannot create subclasses for this final class or modify its behavior.

Example: String class in java.lang.String package. This class is declared as a final class because the authors of the class did not want anyone to extend it.

Syntax for Class: final class <Class Name>
Syntax for Method: final <return type> <method name>

Features of a Final Class In Short:

  • Restricts a class from being extended.
  • Prevents its methods from being overridden
  • Restricts the declaration of abstract methods.
  • Cannot be simultaneously declared as final and abstract.

HINT: Why Final class cannot have abstract methods?
This is because final classes cannot be extended and abstract methods need to be implemented in nonabstract subclasses.

Method lookup

Method lookup is the process that a Java program uses to identify the appropriate method to be invoked. The method lookup process in Java is derived from the inheritance hierarchy. Inheritance in Java is implemented by using the extends keyword.

Example:
class B extends A {…}
To denote that class B inherits from class A, you declare class B using the above syntax.

The method lookup process searches for the method in the class of the receiver object. If a matching method definition is not found, method lookup continues to look for the method in the superclass.

Java allows a subclass to access the methods and fields in the superclass by using the super keyword.

Fig 1.1
Fig 1.1
Let consider an example [Refer fig 1.1], class Vehicle is the base class that defines a variable wheels and a method displayDetails. Class Truck inherits from class Vehicle, and class Tanker inherits from class Truck. Although class Truck and class Tanker inherit from class Vehicle, the variable wheels declared in class Truck and class Tanker is local variable and does not refer to the variable wheels in the class Vehicle. Therefore, any reference to the variable wheels within a method of class Truck will refer only its local value.

To refer to wheels in Truck from within Tanker, you use the syntax super.wheels. Java casts this reference to the super type. Super.wheels is shorthand for ((Truck) this).wheels. However, you cannot use super to discover the value of wheels in Vehicle from within Tanker. To refer to the wheels in Vehicle from within Tanker, you use the syntax ((Vehicle)this).wheels from within Tanker.

The super keyword can be used to bypass the overridden version of a method in a subclass and run the version in the superclass. The super keyword can also be used to bypass a member variable in a subclass for accessing a member variable that has the same name in a superclass.

Suppose class Tanker contains the call super.displayDetails, this call actually invokes the method displayDetails in class Truck because Tanker has inherited it from Truck. If you use the syntax ((Vehicle) this).displayDetails(), it results in the execution of method displayDetails from Vehicle.

Related Post:
Introduction to OOP | Polymorphism | Encapsulation

Objects And Variables

Instantiating an Object

An Object is an instance of a Class. After creating an Object, you can access the member variables and methods of the object and assign values to them. An Object is declared in the same way that a variable of a primitive type is declared.

String sampleStr; //This code is used to define an object name of String type.

You can define a variable that will be used to refer to an object or an instance of a class.

When you create an object, you need to assign memory to the object. This is done using the new operator. The new operator is followed by the class name and parentheses. The syntax for creating an object is displayed below:

class_name variable_name = new class_name();
Example: Test aTest = new Test();

This code is used to create an instance of the Test class. The variable aTest is decleared. Notice that this is an arbitary variable name. This variable is used to refer to the instance of the Test class. You can also state that the name of this particular Test instance is aTest.

When multiple instances are created, each instance maintains a seperate copy of the member variables of the class.

Member Access – Dot Notation

The member variables declared in a class are accessed to assign values or manipulate the values stored in them. The public member variables may be accessed from any object using dot notation. In addition, member variables that are declared without a modifier are considered to have package scope. These variables may be accessed using dot notation from any object defined in the same package. Whereas private members cannot be accessed using dot notations. We need to define public methods [Getters] to access the private members and Setters for assigning values to private member variables

HINT:: Getters and Setters
A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property.

Variable Scope

A scope defines the logical boundary for accessing a variable.

HINT: Java allows you to use the same identifier for multiple variables as long as they are declared in a different scope.

Member Scope
A variable is in the member scope if it is accessible to the methods of the class. This variable is declared as the member variable of the class (i.e) Variables declared directly after class declarations.

Local Scope
A variable is considered to be in the local scope if it is declared within any block of code or if its declared inside a loop condition. A block is a group of statements that are enclosed within braces.

HINT: How Compiler handles?
The Java compiler refers to the variable definitions in a sequence to distinguish the current value of the variable. If first checks the variable in the current block. The current scope depends on the current statement being executed. If the compiler is unable to find the variable in the current block, it searches the variable in the current class. Finally, the compiler searches in the superclasses of the current class.

Variable Access – ‘this’ Keyword

The ‘this’ keyword can be used to access the member variables of the current object. These member variables of an object are also known as instance variables.

HINT
What is Instance Variables?
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.

What is Class Variables?
Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Benefits of Static Variables

  • They are initialized once for all instances of the class.
  • They can be accessed directly using the class name, without a reference to an instance of the class.
  • They are used to store a single value for all instances of a class.
  • Related Posts: Introduction to Java | Classes, Methods & Objects | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

    OOP – Introduction

    Advantages of OOP

    OOP provides advantages over traditional structural programming languages. OOP facilitates writing applications by turning real-world objects into code components. OOP enables users to model real-world objects. Modeling means representing real-world objects as components in Java. Object-Oriented Programming allows programmers and customers to use the same terminology to explain the business domain and the program.

     

    In Summary:

    • Enables the use of real-world modeling

    • Promotes the reuse of code

    • Provides flexibility in the modification of an existing application

    • Helps with the maintainability of code.

    Let’s go in detail with the advantages…

    Enables the use of real-world modeling

    Consider an example. A car is an object that has specific attributes, such as an engine and wheels. Using OOP principles, you would model the car as a car object in Java that would have the same properties.

    Creating applications that model the real world closely enables developers to understand an application faster than any other applications. Therefore, an application that implements OOP concepts effectively is implemented and used.

    Promotes the reuse of code

    Another advantage of OOP is that it promotes the reuse of code. The code used to define an object can be shared by several objects of an application. For E.g.: the code used to design a type of car can be used for designing different types of cars. This saves you from rewriting code for various types of cars. A benefit of code reuse is that it reduces the amount of code to write, debug, test, and possibly upgrade in the future.

     

    Provides flexibility in the modification of an existing application

     

    OOP promotes flexibility in the design and implementation of a solution. Maintenance and upgrades are seen as further cycles in application development. By using OOP practices, applications become easier to extend.

    Consider an example of XYZ Corporation. The application used by the production department of this organization is currently designated to create two types of chairs, plastic and metal. To meet the demands of its customers, the organization decides to produce wooden chairs as well. To meet the change in the requirement, the XYZ

    corp. needs to incorporate changes into its current application system. If the current system was built using OOP best practices, extensions to the system may be simplified. For Eg: the new chair type would be able to share or reuse some of the other chair types’ code.

     

    Helps with the maintenance of Code

     

    Finally, OOP helps in the maintenance of code. By using OOP, you can create separate components for different requirements. In OOP, a component is known as a class. For example, to design a payroll system of an organization, you could create classes such as Employee and Payroll. By creating the Employee and the Payroll classes, information related to each class can be segregated. An internal change in one of these classes should not affect the functionality of the other class. Therefore, the maintenance of a system is simplified by reducing dependencies in between classes.

     

    OOP Design Principles

    An application that implements Object-Oriented Programming (OOP) concepts is distinguished by four design principles. The four design principles are encapsulation, abstraction, inheritance, and polymorphism.

    Encapsulation

    Encapsulation hides the inner workings of an object from outside users of the object. This protects outside users from making internal changes or optimizations to such objects. The object needs only to maintain its external functionality to support its clients. Internal details, such as data representation, should not be accessible externally.

     

    Abstraction

    The principle of abstraction is modeling real-world objects as objects in Java. However, these objects are only modeled at a certain level of detail. Only the behavior and data that is needed by your application will be included in your model.

    The abstraction design principle focuses on the essential characteristics of an object. In OOP, abstraction defines the conceptual boundaries of an object. These boundaries distinguish one type of object from another

    Inheritance

    The inheritance design principle allows a class to inherit the characteristics of another class. When inheritance is used in an application, the application consists of classes that are arranged in hierarchies. The classes defined at the lower levels of a hierarchy inherit from the classes higher up in the hierarchy.

    By creating a hierarchy of classes, the characteristics and code of a class are made reusable. A class can inherit characteristics from other classes and provide additional features. The new class has its own attributes and the attributes of the existing class. This feature provides extensibility and reusability in classes.

     

    Polymorphism

    Polymorphism refers to the ability of an object to take on different forms depending upon the situation. Consider an example of a class Sedan that inherits from the class Car that inherits from the class Vehicle. An instance of the Sedan class can be referred to as a Sedan, a Car, or a Vehicle.

    Polymorphism provides flexibility to an application based on requirements. It simplifies coding and reduces the rework involved in developing and modifying an application. This is because different types of objects can react to the same type of stimulus.

    Related Post:
    Inheritance | Polymorphism | Encapsulation

    Classes, Methods and Objects

    Classes and Objects

    The idea of Object-Oriented Programming (OOP) is to place data and methods together in a single entity. The single entity holding the data and methods is called a class. An Object is an instance of a class.
    To create a Java application, you organize programming structures by creating classes that consist of reusable code. You can create a class in Java to perform simple tasks, such as declaring the member variables of the class and perhaps initializing the member variables by using the methods of the class.

    An instance of a class is declared the same way that a primitive data type is declared. A class defines both data and methods. You can reuse the same class in several applications without rewriting it. You can create as many instances or objects of a class as needed. When multiple objects are created, each object maintains a separate copy of the member variables defined by the class.

    Creating a Class

    1. Specify the class name.

    2. Declare data members.

    3. Declare methods.

    4. Define the processing.

    In order to define a class, you must specify the class name, declare the member variables, and declare the methods of the class.
    There are certain naming conventions that should be followed when naming a class. First, class names should be nouns. The first character of the class name should be upper case, and each internal word of the name should be upper case. The rest of the characters in the name should be lower case. The words in the name should be whole words. Acronyms and abbreviates should be avoided.

    In addition, you must define the processing that is required for the method. For example, operations such as addition or subtraction on member variables can be specified in the methods. The contents of the class definition are enclosed within braces.

    public class Rectangle {
     //class name and Body begins now... 
      int length=10; 
      int width=5; 
      String color; 
    
    
      void calculateArea() { //method declartion 
        int totArea = length * width;//processing 
        System.out.println("The total area " + totArea); 
      } 
    }//end class body

    Consider the Rectangle class shown above. It consists of the class keyword followed by the class name. The class body begins with an opening brace. The class body consists of member variables and a method. In the method declaration, the member variables are accessed and processed. To end the class declaration you use a closing brace.

    A class declared in Java usually contains an access modifier. The access modifier determines the type of access other classes and objects can have to a specific class and the fields and methods that it defines. In our example, Rectangle class is declared using “public” access modifier meaning it can be accessed by anyone.

    Access Modifiers for Class
    The access modifiers that can be used while declaring a class are public, private, and protected. When the class is declared without an access modifier, the class is accessible by the other classes in the current package. When a class is declared with the public access modifier, the class is accessible by all the other classes.
    The private and protected access modifiers may only be used on inner classes. They cannot be used for top-level classes. When a class is declared with the private access modifier, the class is not accessible by any other classes. When a class is declared with the protected access modifier, the class is accessible by subclasses of the class.

    In addition to the access modifiers, the modifiers final, abstract, and strictfp may be specified.

    If the final modifier is specified, the class represents a complete class and cannot be overridden by a subclass.

    The abstract modifier is used to declare that a class is considered incomplete. An abstract class may have abstract methods that are not implemented within the class. The final modifier cannot be used with the abstract modifier.

    The strictfp modifier is used to force the code within the entire class to use strict floating-point logic. This applies to all float and double values that are used within the class.

     

    Declaring Methods

    A class is defined by its state and behavior. The member variables of the class define the state of the class. The methods of a class define the behavior of the class.
    Consider an example, To add the values stored in the member variables of a class, you declare a method that operates on these member variables to compute their sum. The result can be displayed by another method that calls the computed method.

    The six basic components of a method include the access modifier, other modifiers, the return type of the method, the name of the method, a list of the arguments passed to the method, and the body of the method.

    <access modifiers> <other method modifiers>
    <return type> methodName(arg1, arg2, ...)
     { //method body }

    Access Modifier for Methods
    It is a Subset of the method modifier group. This specifies the type of access granted to other objects for that method. You can declare a method public, private, or protected. If no access modifier is specified, the method is accessible to all classes in the current package. A public method may be accessed from any class. A protected method may be accessed from any subclass of the class in which the method is defined. A private method may only be accessed from within the class in which it is declared.

    void myPackageMethod() { 
    // This method may be accessed from any 
    // class declared in the same package 
    }
    public void myPublicMethod() { 
      //This method may be accessed from any class 
    }
    private void myPrivateMethod() {
       // This method cannot be 
       // accessed from other classes.
    }
    protected void myProtectedMethod() { 
      // This method may be accessed from any 
      // subclass of the class that declares it. 
    } 
    public final void myFinalMethod() { 
      // This method cannot be overridden or hidden 
    } 
    public abstract void myAbstractMethod();
    //This method must be overridden 
     // to create a concrete class
    
    
    
    
    public static void myStaticMethod() {
      //Do Work 
    } 
    public native void someExternalMethod(String name); 
    public strictfp void myStrictFpMethod() {
      // All float and doubles 
      // use strict floating point logic. 
    } 
    public syncrhornized void mySynchronizedMethod() { 
      //Multiple threads will not be able to 
      //access this method at the same time. 
    }

    Other Method modifiers
    In addition to the access modifiers, the modifiers static, final, abstract, native, strictfp, and synchronized may be specified.

    Static methods are scoped to the class and not to the instance of the object. These methods may be called without an instance of the class being created. These methods may be called without an instance of the class being created. They may access static variables, but do not have direct access to member variables.

    If the final modifier is specified, the method cannot be overridden or hidden by a subclass. The abstract modifier is used to declare that a method is not implemented in a class. In this case, the method must be implemented by a subclass in order to create a class that can be instantiated. This final modifier cannot be used with the abstract modifier.

    The native modifier is used to define a class that is implemented in code external to the Java Code. This is typically used to allow a Java application to call code in languages such as C++.

    The strictfp modifier is used to force the code within the method to use strict floating-point logic. This applies to all float and double values that are used within the method.

    The synchronized modifier is used when access to the method needs to be synchronized in order to prevent multiple threads from accessing it at the same time. This can be used to keep multiple threads from modifying variables or accessing resources at the same time.

    Return Type
    The return type of the method indicates the return type of the method. The return type of the method indicates the type of value that the method provides to a calling method. The return type is specified by a primitive or object data type, such as void, int, char, String, or Date. The return type is always followed by the method name.

    Method Name
    A method name that follows the int data type would signify that the method returns a type integer when its is involved. Note if the method does not return any type, the method name is preceded by the void return type.

    The method name is user-defined and should be meaningful. According to Java variable naming conventions, if a name consists of two or more words, you join the words to form a single word and capitalize the first letter of each word, except for the first word.

    The name of the method must not be a Java Keyword, such as int, package, or void. In addition, the method name should not begin with a digit and must not contain embedded spaces or periods. For example, findFile is a valid method name.

    If a method defines a return type, then the return keyword is used to return the value. The keyword is followed by the value that is to be returned by the method. Note that this keyword is not required if the method does not return a value because its return type is void.

    Method Arguments
    This is a comma separated list of variable declarations that are defined within enclosing parentheses. Arguments are optional. The parentheses are mandatory.

    Method Body
    The body contains statements and expressions that run when the method is invoked. The body of the method can have conditions and loops, and it can send messages to other instances or to other objects.

    Method Overloading

    Programming languages like C require unique names for different methods in the same program. In Java, you can declare methods with the same name. This process is called method overloading.
    In C, a program contains many methods that perform different tasks. Therefore, it is difficult for an application developer to remember the function and name of each method.

    In Java, you can declare methods with the same name. However, these methods must accept different arguments. This process of declaring methods with the same name is called method overloading.

    In Java, every method has a signature, which consists of a method name and an argument list. The data type of the arguments and their sequence helps define the signature of a method.

    A Class cannot have two methods with the same signature. This is because compiler will not be able to determine which method to invoke.

    In addition to overloading a method with a different number of arguments, you can overload a method by specifying different data types for the arguments. You can also overload a method by providing a different sequence for arguments.

    void addNum(int num, float num1)
    void addNum(float num, int num1)

    Consider an example in which you declare a method that adds an integer value and a float value. In such situation, a user can pass an integer value first and then the float value or vice-versa. To conform to this requirement, you declare two methods with a different sequence of arguments but with the same name.

    Pass By Value: Primitives

    When you invoke a method, you may pass arguments to the method. The arguments are used by the method. Either the value of the argument or a reference to an object is passed.
    When you invoke a method by passing arguments by value, it is know as passing by value. When you invoke a method by passing a value to a method, it is known as passing arguments by value. Java passes all method arguments by value for primitive data types. By passing the arguments by value, the original value of arguments is not altered inside the method. The method only receives a copy of the variable.

    void computePrice(int unitPrice, int numberOfUnits) {
      unitPrice = unitPrice * numberOfUnits; 
      System.out.println(
        "unitPrice in the computePrice method : " 
        + unitPrice); 
    }

    For example, to calculate the total price for four identical items, you multiply the unit price of the item by four. This will not change the price of the individual item. This is because the price was passed by value.
    When you invoke a method by passing a value, a local copy of each argument is made in the called method. Consider the code of the item class shown in the above example. This class contains the computePrice method. This method has a piece of code that changes the value of the unitPrice parameter. The computePrice method calculates the price of the number of items and stores the total in the unitPrice variable. The method also displays the total value.

    In Summary: Calling a method and passing the arguments by value does not affect the original value.

    Pass By Reference: Objects

    Whenever arguments of type Object are passed to a method, their references are passed as opposed to a copy of the object. An object is passed by reference when it is an argument of a method. This ensures that the changes to the object are retained because the actual object is being updated.

    class Employee { String name; 
     String department; 
     double salary;
    
    
      public Employee(String empName, 
                      String empDept, 
                      double empSalary) {
        this.name = empName;
        this.department = empDept;
        this.salary = empSalary;
       }
    
    
       void printAll() {
         System.out.println("Name : " + name);
         System.out.println("Department : " + department); 
         System.out.println("Salary : " + salary); 
       } 
    
    
       public static void main(String args[]) { 
         Employee jane = new 
                      Employee("Jane", "Research", 60000); 
         Employee tempEmp = jane;
         tempEmp.name = "Tom";  
         jane.printAll();  
       } 
    }

    Consider a situation where each employee is assigned three details. These details are name, department, and salary. In addition, an employee can print all the details through the printAll method. The sample code in the example instantiates a new Employee object, bound to the variable jane. The code then assigns Jane to the name, Research to the department, and 60000 to the salary. Next, a variable of type Employee called tempEmp is declared and assigned to the same instance that the variable jane is bound to. Both jane and tempEmp are references pointing to the same object. A change to one will be reflected in the other.

    Related Post: Introduction to Java | Objects and Variables | Datatypes | Operators | Conditional Flow Control | Iterative Flow Control | Jump Statements

    Websphere Application Server 6

    Every J2EE project has difficulties in choosing the Application Server Containers. Even though open source Application Servers like JBoss tries to rule out the giants, still many commercial projects choose the giants as they have already made good impressions. Among the giants IBM’s Websphere and BEA’s Weblogic had equal competition. Many commercial J2EE projects still believe that their commericial product will be secure only with the giants and the downtime of the giant application servers are negotiable.

    Now IBM has released Websphere Version 6 and recently I attended IBM’s in-house workshop on WAS 6. After attending the workshop, I realized that WAS 6 is going to be the primary Application Server as it provides most of the solutions to the big commercial J2EE projects.

    WebSphere® Application Server V6.0 is the industry’s premier Java™-based application platform, integrating enterprise data and transactions for the dynamic e-business world. Each configuration available delivers a rich application deployment environment with application services that provide enhanced capabilities for transaction management, as well as the security, performance, availability, connectivity, and scalability expected from the WebSphere family of products.

    What Websphere V6.0 Offers:

    1. Full J2EE V1.4 compatibility, as well as Web services support above and beyond the specification, including a native, enterprise-ready JMS provider.

    2. New packaging providing full J2EE 1.4 compatibility across the board, from the base Express offering to the most robust Network Deployment, offering multiple deployment options from single server to clustered, highly available, high-volume configurations.

    3. Rapid development and deployment features that reduce development cycle time and maximize the ability to use existing skills and resources.

    4. Tight integration with IBM Rational tools, a highly productive development environment built on Eclipse, the open systems development environment.

    5. Industry’s broadest cross-platform support.

    6. Delivers an advanced, security-rich infrastructure that is extensible through a pluggable architecture.

    7. Delivers a single, unified Web browser-based administration across all configuration options.

    8. Offers distributed-workload and caching capabilities to intelligently optimize performance

    9. Provides enhanced application availability with sophisticated clustering and load-balancing capabilities

    My Observation on Websphere V6.0

    … WAS 6 has pretty good Administrative Console. Administrative console is built using Struts and JSF technologies.

    Hmm…we all know that Websphere Version 5 also had their Administrative Console built using Struts. So what’s special in Version 6 and why they have also used JSF?

    The Good News to all of us is they have integrated Tivoli Performance monitor in the admin console itself using the JSF technology. Now all our J2EE Projects can be benchmarked easily in the console.

    … They have replaced JMS C Processes with Java Process and embedded the JMS Servers in the Application Servers. In Older versions, once you start your JMS Server you can see list of C Process running in your CPU [Something that starts with ‘amq’].
    If you haven’t noticed it yet, try starting JMS Server in Version 5 and look at your Process list [See Task Manager for Windows. Ps –f for Unix].

    … Load balancing has improved drastically. According to their benchmarks, they claim that Websphere Version 6 can handle 10,000 Concurrent requests where as Websphere version 5 can handle only 500 concurrent requests.

    … They have improved in the areas of Caching

    … Websphere Version 6 has Scheduling Services. This is the one I admire the most. Because when I worked with one of the Reporting Project, the project had a module that involves scheduling architecture. And I had to learn Quartz API and write the scheduler service. Now since this is the part of Websphere, developer’s overhead in writing the services is reduced. And now the developers only need to configure the scheduler service and start using it.

    … Websphere Version 6 has support for Web services.

    Additional Interesting News:

    Finally in the workshop, IBM mentioned about the following that seems interesting to me…

    … Extended Deployment Server, which is capable of tuning the application server.

    … WebSphere Application Server V6.0 delivers Services Oriented Architecture today, across all configurations. The products allows businesses to increase their return on investment and lower their total cost of ownership by reusing existing IT assets using standards based messaging and the latest Web services standards. This translated into reduced costs, reduced time to value, and increased business flexibility.

    … WebSphere Application Server V6.0 provides a secure, dynamic platform for businesses. Businesses are able to do more work with less resource with WebSphere Application’s scaling abilities and security features.