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.


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

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.


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

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.

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.

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.

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.

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 (!=).


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


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.

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

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

/* blah blah blag */


Type 2: End-of-line comment

// 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.


Declaring Variables


datatype variableName;


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.

variable_name = value;

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

You can also simultaneously declare and initialize a variable.

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


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.

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


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.

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

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.


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


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


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.


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.

<<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.

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.

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