-->

Sunday, December 28, 2014

Create an Object using New Operator: Java

New operator is used to create a new object of an existing class and associate the object with a variable that names it. Basically new operator instantiates a class by allocating memory for a new object and returning reference to that memory.
Every class needs an object to use its member and methods by other classes. Programmer have to create that object using new operator to use functionality provided by that class. Following is the syntax to create new object of an existing class:

Class_variable =new Class_Name();

This syntax basically describes some points about new operator as below:
  • Allocates memory to class_variable for new object of class.
  • It invokes object constructor.
  • Requires only single postfix argument which calls to constructor.
  • Returns reference to memory which is usually assigned to variable of appropriate type.
Following statement will create an object of city class and allocate memory to this newly created object:

City metro;
metro = new City();

The equivalent code for the above statement that can be written in single line is:

City metro = new City();

So new operator does two things overall i.e. it first allocates memory somewhere to hold an instance of the type, and then calls a constructor to initialize an instance of the type in that newly allocated memory.

After creating new object for a class, that object can use all the members and methods defined in that class. You can assign all the properties for that class and operate available or new functions on those properties.

Monday, May 26, 2014

How to Define Methods with Behavior: Java

Objects have behavior that is implemented by its methods. Other objects can ask an object to do something by invoking its methods. This section tells you everything you need to know about writing methods for your Java classes.

In Java, you define a class’s methods in the body of the class for which the method implements some behavior. Typically, you declare a class’s methods after its variables in the class body although this is not required.

Implementing Methods

Similar to a class implementation, a method implementation consists of two parts: the method declaration and the method body

methodDeclaration {
        methodBody
}

The Method Declaration

At minimum, a method declaration has a name and a return type indicating the data type of the value returned by the method:

returnType methodName( ) {
. . .
}

This method declaration is very basic. Methods have many other attributes such as arguments, access control, and so on.

Objects as Instances of Class

A class defines only a blueprint and its concrete version comes into effect only through objects that implement the functionality as defined by class. Recall our class example of City class. The objects created from this class will have two variables: name and population; and they will be able to represent cities. The object of City class will also have a method namely display ( ). An object of a class is typically named by a variable of the class type. For example, the program CityTrial in Example 4.7 declares the two variables metl1 and metro2 to be of type City, as follows;

City metro1, metro2;

This gives us variables of the class City, but so far there are no objects of the class. Objects are class value that are named by the variables. To obtain an object you must use the new operator to create a “new” object. For example, the following creates an object of the class City and names it with the variable metro1:

Metro = new city ( );

For now you need not go into details, simply note that the statement like:

Class-variable = new class-Name ( );

Creates a new object of the specified class and associates it with the class type variables. Since the class variable now names an object of the class, we will often refer to the class variable as an object of the class. (This is really the same usage as when we refer to an int variable n as “the integer n”, even though the integer is strictly speaking not n but the value of n.)

Unlike what we did in previous lines, the declaration of a class type variable and the creation of the object are more typically combined into one statement as follows:
City metro1 = new City( );
To instantiate an object, Java uses the keyword new.

How to Declare Member Variables in Classes: JAVA

A class’s state is represented by its member variables. You declare a class’s member variables in the body of the class. Typically, programmer declare a class’s variables before you declare its methods, although this is not required.

classDeclaration {
        member variable declarations
        method declarations
}
To declare variables that are members of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method i.e., available and accessible only inside the method.

Types


  • Class variable (static variable): A data member that is declared once for a class. All objects of the class type, share these data members, as there is single copy of them available in memory. The class variables are declared by adding keyword static in front of a variable declaration.
  • Instance variable: A data member that is created for every object of the class. For example, if there are 10 objects of a class type, there would be 10 copies of instance variables, one each for an object.
Consider the following code.


Public class sample {
        int anInt; // instance variable
        float aFloat; // instance variable
        static float anotherFloat; // class variable
};

Suppose there are five objects created for class type Sample. Then there would be five copies of variables anInt and aFloat but there would be one copy of variable anotherFloat which all five objects can share.

Notice that class variables are declared by adding a keyword static before the variable declaration. Keyword static in the variable declaration makes it class variable.

Method are similar: your classes can have instance methods and class methods. Instance methods operate on the current object’s instance variables but also have access to the class variables. Class methods (also called static methods), on the other hand, cannot access the instance variables declared within the class (unless they create a new object and access them through the object). Also, class methods can be invoked on the class, you don’t need an instance to call a class method.

A class method can be invoked by:

  • Just its name within its own class e.g., check( ).
  • Class-name.method-name outside its class e.g., Sample.check ( )

In above two lines, we assume that method check( ) is a static method in class Sample.

Implement Object-Oriented in JAVA

Sunday, May 18, 2014

How to Declare Classes with Members: JAVA

In order to bring a class into existence in Java program, it should be declared. A class is declared using keyword class. The generic syntax for class declaration in Java is:

Class   <class_name>
{
    Statements defining class come here
}

The angle-brackets < > mean these names are to be provided by the programmer and [ ] brackets mean, this part is optional. The class name must be provided while declaring a class. This is used to refer to the class whenever an instance (the object) of the class is created. The class name must be a legal identifier in Java. While naming classes, generally nouns are used and the first letter is given in uppercase e.g., City or Date etc. the curly brackets { } mark the beginning of a class and/or a method. The curly brackets are also used to specify block statements.

A class is a blueprint or prototype that you can use to create many objects. The implementation of a class is comprised of two components: the class declaration and the class body.

classDeclaration   {
    // classBody
}

When a class is declared, no memory space is allotted to it. This is because a class is simply a blueprint or logical placeholder containing objects and method. Memory space is allocated when objects of a class type are created.

The Class Declaration

The class declaration component declares the name of the class along with other attributes such as whether the class is public or not.

The Class Body

The class body follows the class declaration and is embedded with in curly braces ‘{‘ and ‘}’. The class body contains declaration for all instance variable and class variable (known collectively as member variable) for the class. In addition, the class body contains declarations and implementations for all instance methods and class methods (known collectively as methods) for the class. The following template shows the form of a class definition that is most commonly used; however, it is legal to intermix the method definitions and the instance variable declaration.
Public class class_Name    {
Instance_Variable_Declaration_1
Instance_Variable_Declaration_2
. . . . . .
Instance_Variable_Declaration_Last
Method_Definition_1
Method_Definition_2
     . . . . .
    Method_Definition_Last
}

How to Implement Object Oriented Design in JAVA

The basic unit of object-orientation in Java is the class. The class is often is described as a blueprint for an object. You can think of an object as an entity having a unique identity, characteristics and behaviour. For instance, a ceilingFan is an object : it has a unique identity ; its characteristics are : it has 3 or 4 blades, it has a motor, a colour etc. ; its behaviour is : it rotates the air at some specific speed. Similarly, a Student is an object. Its characteristics are: its rollno, name class, marks etc. Its behaviour is: it takes test, it attends classes etc.

To create an object in Java, you need a class. It allows a programmer to define all of the properties (i.e. characteristics) and methods (i.e. behaviour) that internally define an object, all of the API (Application programming interface) method that externally define an object. Therefore, we can say that a class is the BLUEPRINT of an object. A class define the types of shared characteristics, such as:
  • The set of attributes i.e. characteristics through data.
  • The set of behaviour i.e. behaviour through method/functions
In its role as a blueprint, the class specifies what an actual object will look like. But it is not an object. Objects are actually instances of classes. You can think of a class as a cookie cutter and an instance as an actual cookie. Similarly, you can think of a class as a blueprint of a house and an instance as an actual house.

Class as Basis of all Computation 

In Java, the class forms, the basis of all computation. Anything that has to exist as a part of a Java program has to exist as a part of class, whether that is a variable or a function or any other code-fragment. Unlike other OOP languages such as C++ that allows the existence of variables and functions outside any class. The reason being that Java is a pure Object Oriented Language. Here all functionality revolves around classes and object, as in real world. Therefore, if you want to use certain variable and functions in Java, you have to make them part of a class. ALL JAVA programs consist of objects (data and behaviour) that “interact” with each other by calling methods. All data is stored within objects which are instances of a class.

See, without classes can be no objects and without objects, no computation can take place in Java. Thus, classes form the basis of all computation in Java.

Defining Classes

A Java program consists of objects, from various classes, interacting with one another. Before we go into the details of how you can define classes, let’s review some of the general properties of classes. A value of class type is called an object. An object is usually referred to as an instance of the class rather than as a value of the class, but it is a value of the class type. An object is a value of the class type much like a value, such as 5, of a primitive type, like int, is a value of a variable of that type. 

However, an object typically has multiple pieces of data and has methods (action) it can take. Each object can have different data but all objects of the class have the same types of data and all objects in a class have the same methods. We generally say that data and methods belong to the object, and that is an acceptable point of view. The data certainly does belong to the object, but since all objects in a class have the same methods, it also would be correct to say that the methods actually belong to the class.
In this section we are going to learn about how to define classes in Java. Now consider the code fragment shown below that defines a class called City.

Public class City {
String name ;    // variable name will be name of the city
Long population ;    // will hold City’s population
Void display( )    {
Label1.setText(“city name :” + name) ;
Label2.setText(“population :” + population) ;
}
}

Let us examine this code line by line. The firstline Public class City Defines the name of the class which is City. The keyword class ensures that it is a class and the keyword public means it is available in entire program. When you add a top-level container frame in your GUI application, then a public class having the frame name is created in your application. In other words, the top-level frame is represented through a public class.

The brace following the public Class City
    { marks the beginning of class’ block.

The next two lines
    String name;
    Long population;
declares the data members of the class to define its characteristics.
Each of these lines declares one instance variable name. You can think of and object of the class as a complex item with instance variables inside of it. So, you can think of an instance variable as a smaller variable inside each object of the class. In this case, the instance variables are called name and population.
The copy of instance variables is created for each object of the class. The next four lines
    void display ( )
    {
        Label1.setText(“City name :” + name);
        Label2.setText(“population :” + population);
    }

Define a method of the class which defines the behaviour of the class. The name of the method is display( ). By looking at its code, you can easily make out what its functionality is like. The last line
    }
marks the end of the class’ block.

Null Statement and Character Manipulation in JAVA

In Java programs, statements are terminated with a semicolon (;). The simplest statement of them all is the empty, or null statement.
; it is a null statement

A null statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not. We will see it in loops and their bodies.

Character Manipulation

Consider the following code. What does it print?
        :
System.out.print(“H” + “a”);
System.out.print(‘H’ + ‘a’);
        :

Aren’t you thinking that it would produce output as:    HaHa
But if you the program, you’ll find that the output produced is:    Ha169

As expected, the first call to System.out.print prints Ha. Its argument is the expression “H” + “a”, which performs the obvious string concatenation.
The second call to system.out.print is another story. Its argument is the expression ‘H’ + ‘a’. The problem is that ‘H’ and ‘a’ are char literals. Because neither operand is of type string, the + operator performs addition rather than string concatenation. Thus it adds ‘H”s value i.e. 72 and ‘a”s value I.e. 97 and gives 169. (A-Z have values 65-90; a-z have values 97-122).
You can force the + operator to perform string concatenation rather than addition by ensuring that at least one of its operands is a string. The common idiom is to begin a sequence of concatenations with the empty string (“ “), as follows:
    System.out.print(“ “ + ‘H’ + ‘a’) ;

But this approach can lead to some confusions also. Can you guess what the following statement prints?
    System.out.println(“2 + 2 = “ + 2 + 2);
---------------------------------------------------

Yes, you are right. It produces:    2 + 2 = 22
To perform the addition of expression 2+2 shown above, you need to convert it to Expression by enclosing it in parenthesis i.e. as
(2+2): System.Out.Println(“2+2 = ”+ (2+2));
The + operator performs string concatenation if and only If at least one of its operands is of type string: otherwise, it performs addition with primitive types.

Type of Statements used in JAVA

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( ; )
  • Assignment expressions
  • Any use of ++ or - -
  • Method calls
  • Object creation expressions
These kinds of statement are called expression statement. Here are some example of expression statements :

Avalue = 8933.234;                                          // assignment statement
Avalue++ ;                                                        // increment statement
System . out . println (avalue);                         // method call statement
Integer integerobject = new integer (4);           // object creation statement

In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. You’ve seen many examples of declaration statement.
Double avalue = 8933.234;            // declaration statement

A control flow statement regulates the order in which statements get executed. For loop and  if statements are both examples of control flow statements.

Block

A block is group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following listing shows two blocks.
If  (character . I suppercase(achar))
{
    Labe l1 . settext (“the character” + achar + “is upper case .”) ;
}
Else
{
    Labe l1. Settext (“the character” + achar + “is lower case .”) ;
    Label2. Settext(“thank you”) ;
}

Character.isLowerCase( )    tests whether a character is in lowercase.
Character.isUpperCase( )        tests whether a character is in uppercase.
Character.toLowerCase( )        converts the case of a character to lowercase
Character.toUpperCase( )        converts the case of a character to uppercase


First Block:
 If (character.isUpperCase(achar))
{            // block1 begins
    Label1.Settext (“ The character “ + achar + “ is upper case.”) ;
}            // end of block 1
Else
 
Another Block:
{            // block2 begins
Label1.Settext(“ The character “ + achar + “ is lower case . “) ;
}            // end of block2

See, the beginning and end of blocks have been marked.
A Block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
In this book, we shall be following conventional style where opening brace of the block is not put in a separate line, rather it is placed in continuation with the previous statement (whose part the block is).
For instance, rather than showing
If (a > b) { : }
We shall be writing
If (a > b)   {     :  }
Opening brace of the block in continuation with previous statement

Tuesday, May 13, 2014

Expression Evaluation and Compound Expression in JAVA

As discussed in earlier articles, expressions can either be pure expressions or mixed expressions. Pure expressions have all operands of same datatypes, contrary to mixed expressions that have operands of mixed datatypes.

Evaluating Pure Expressions

Pure expressions produce the result having the same datatypes as that of its operands e.g.

Int a = 5, b = 2, c;
a + b will produce result 7 of int type.
a/b will produce result 2 of int type.
Notice that it will not produce 2.5, it will produce 2.

Evaluating Mixed Expressions

In Java, when a mixed expression is evaluated, it is first divided into component sub-expressions up to the level of two operands and an operator. Then the type of sub-expression is decided keeping in mind general conversion rules. Using the results of sub-expressions, the next higher level of expression is evaluated and its type is determined. This process is continued till you get the final result of the expression.

Boolean (Logical) Expressions

The expressions that result into false or true called Boolean expressions. The Boolean expressions are combination of constants, variables and logical and relational operators. The rule for writing Boolean expressions states :
A Boolean expression may contain just one signed or unsigned variable or a constant, or it may have two or more variable or/and constant, or two or more expressions joined by valid relational and/or logical operators. Two or more variable or operators should not occur in continuation.
The following are examples of some valid Boolean expressions :
(i) x > y (ii) (y + z) >= (x/z)
(iii) (a + b) > c&& (c + d) > a (iv) (y > x) || (z<y)
(v) x||y && z (vi) (x)
(vii) (-y) (viii) (x-y)
(ix) (x > y) && ( !y < z) (x) x <= !y && z

Compound Expression

A compound expression is the one which is made up by combining two or more simple expressions with the help of operator. For example,
(a +b)  / (c +d)
Is a compound expression.
(a > b)  || (b > c)
Is example of another compound expression.

Type Conversion and its Types used in JAVA

An implicit type conversion is a conversion performed by the compiler without programmer’s intervention. An implicit conversion is applied generally whenever differing data types are intermixed in an expression (mixed mode expression), so as not to lose information.

The Java compiler converts all operands up to the type of the largest operand, which is called type promotion. This is done operation by operation, as described in the following type conversion rules
If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Once these conversion rules have been applied, each pair of operands is of same type and the result of each operation is the same as the type of both operands.
The implicit type conversion wherein datatypes are promoted is known as Coercion.
Although coercion exempts the user from worrying about different datatype of operands, yet it has one disadvantage. Coercions decrease the type error detection ability of the compiler. You have already used the implicit type conversion unknowingly. Recall that you use “ “ + <number> (e.g., “ “ +5) to convert it to string.

Explicit type conversion

An explicit type conversion is user-defined that forces an expression to be specific type. The explicit conversion of an operand to a specific Type Casting. Type casting in Java is done as shown below :

(type) expression Where type is a valid Java data type to which the conversion is to be done. For example, to make sure that the expression (x + y/2) evaluates to type float, write it as: (float) (x +y /2)

Casts are often considered as operators. As an operators, a cast is unary and has the same precedence as any other unary operator.

Below is a table that indicates to which of the other primitive types a given primitive data type can be cast. The symbol C indicates that an explicit cast is required since the precision is decreasing. The symbol A indicates that the precision is increasing so an automatic cast occurs without the need for an explicit cast. N indicates that the conversion is not allowed.

Type Conversion and its Types used in JAVA

The * asterisk indicates that the least significant digits, may be lost in the conversion even though the target type allows for bigger numbers. For example, a large value in an int type value that uses all 32 bits will lose some of the lower bits when converted to float since the exponent uses 8 bits of the 32 provided for float value.

Assigning a value to a type with a greater range (e.g. from short to long) poses no problem, however, assigning a value of larger data type to a smaller data type (e.g., from double to float) may result in losing some precision.
Programmer cannot typecast a Boolean type to another primitive type and viceversa. So, we cannot cast a primitive type to an object reference, or viceversa.  

Expressions and its types used in JAVA

An expressions is composed of one or more operations. The objects of the operation(s) are referred to as operands. The operations are represented by operators. Therefore, operators, constants, and variables are the constituents of expressions.

An Expression in Java is any valid combination of operators, constants, and variables are the constituents of Java tokens. The expression in Java can be of any type
  • Arithmetic expression
  • Compound expression
  • Relational (or logical) expression
Type of operators used in an expression determine the expression type. For instance, if an expression is formed using arithmetic operator, it is an arithmetic expression; if an expression has relational and/or Boolean operators, it is a Boolean expression. An arithmetic expression always results in a number (integer or real) and a logical expression always results in a logical value i.e., either true or false.

Arithmetic Expressions

Expressions and its types used in JAVA

Arithmetic expressions can either be pure integer expressions or pure real expressions. Sometimes a mixed expression can also be formed which is a mixture of real and integer expressions.
In pure expressions, all the operands are of same type. And in mixed expressions, the operands are of mixed or different data types.
Integer expressions are formed by connecting integer constants and/or integer variables using integer arithmetic operators.  The following are valid integer expression:

final int count = 30
int I, J, K, X, Y, Z
– J, K – X, K + X – Y + count, – J + K * Y, J/Z, Z % X

Real expression are formed by connecting real constants and/or real variables using real arithmetic operators. The following are valid real expression:

final float bal = 250.3f:
float qty, amount value;
double fin, inter;

Rule for these arithmetic expressions is the same and it states that:
An arithmetic expression may contain just one numeric variable or a constant, or it may have two or more variables or/and constants, or two or more expressions joined by valid arithmetic operators. Two or more variables or operators should not occur in continuation.

Apart from variables, constants and arithmetic operators, an arithmetic expression may consist of Java’s mathematical functions that are part of Java standard library and are available through Math class defined in java.lang package. The following image lists various math functions that are defined in the Math class of Java.lang package.

You can use these math functions as per following syntax:
Math.Function_name (argument list) ---- The arguments are the values required by a function to work upon. For example, to calculate ab, you may write: math.pow(a, b)

Following are examples of valid arithmetic expressions :
Given     int a, b, c ;  float, p, q, r ; double x, y, z ;
a/b, p/q +a-c, x/y + p*a/b, Math .sqrt (b)*a) – c, Math.ceil (p) + a)/c, Math. Max (c,b) +x/y – z/q +c  

Following are example of invalid arithmetic expressions :
Given int , a, b, c ;  float, p, q, r ;   double x, y, z ;
x + * r      two operators on continuation.
q(a + b – z/4)   operator missing between q and parenthesis.
Math.pow (0, - 1)  Domain error because if base = 0 then exp should not be <= 0.
n *log (-3) + p/q  Domain error because logarithm of negative number is not possible.

Sunday, May 4, 2014

Operator Precedence and Associativity to Evaluate Expression: JAVA

Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine the overall value of the expression. For example, take the following expression:
 Y  =  6  + 4/2

Depending on whether the 6+4 expression or the 4/2 expression is evaluated first, the value of y can end up being 5 or 8. Operator precedence determines the order in which expression are evaluated, so you can predict the outcome of an expression. In general, increment and decrement expression are evaluated before arithmetic expression; arithmetic expression are evaluated before comparisons, and comparisons are evaluated before logical expression. Assignment expression are evaluated are evaluated last.

Operator Precedence and Associativity to Evaluate Expression: JAVA


Above Table shows the specific precedence of the various operators in Java. Operators further up in the table are evaluated first; operator on the same line have the same precedence and are evaluated left to right based on how they appear in the expression itself. For example, given that same expression
Y = 6 + 4/2

You now known, according to this table, that division is evaluated before addition, so the value of y will be 8.

You always can change the order in which expressions are evaluated by using parentheses around the expressions you want to evaluate first. You can nest parentheses to make sure that expressions evaluate in the order you want them to (the innermost parenthetical expressions is evaluated first.

Consider the following expression:
y = (6 + 4)/2

This results in a value of5, because the 6+4 expression is evaluated first, and then the result of that expression (10) is divided by 2.

Parentheses also can be useful in cases where the precedence of an expressions isn’t immediately clear. In other words, they can make your code easier to read. Adding parentheses doesn’t hurt, so if they help you figure out how expressions are evaluated, go ahead and use them.

Operator Associativity

There is a linked term – Operator Associativity. Associativity rules determine the grouping of operands and operators in an expression with more than one operator of the same precedence. When the operations in an expression all have the same precedence rating, the associativity rules determine the order of the operators.

For most operators, the evaluation is done left to right, e.g.
X  = a + b – c

Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c is subtracted. Again, parentheses can be used to overrule the default associativity, e. g.
X = a + (b-c);

However, the assignment and unary operators, are associated right to left, e.g.,
X += y -= -4; equivalent to X  += (y  -= (-(4) ) );

Assignment and Remaining operators 

Other Remaining Operators used in JAVA Programming

All other remaining operators except assignment operators are listed in this article. Like instance of, shift operators, bitwise and many more described with example in the article.

The following table lists the other operators that the Java programming language supports.

Remaining operators used in java

In the following lines, we are discussing some of these operators. Discussion of all these operators may be large task here.

Conditional operator ?:

Java offers a shortcut conditional operator (?:) that store a value depending upon a condition. This operator is ternary operator i.e., it requires three operands. The general form of conditional operator ?: is as follows:
expressiona1 ? expression2 : expression3

If expression1 evaluates to true i.e., 1, then the value of the whole expression is the value of expression2, otherwise, the value of whole expression is the value of expression3. For instance
result = marks >= 50  ?  ‘P’ : ‘F’ ;

The identifier result will have value ‘P’ if the test expression marks >= 50 evaluates to true otherwise result eill have value ‘F’. Following are some more examples of conditional operator ? :

6 > 4 ? 9 : 7 evaluates to 9 because test expression 6 > 4 is true.
4 == 9 ? 10 : 25 evaluates to 25 because test expression 4 == 9 is false.

The conditional operator might be fascinating you but certainly one tip regarding ? :, we would like all of you to keep in mind and which is being told in form of following tip.
Beware that the conditional operator has a low precedence.The conditional operator has a lower precedence than most other operators that may produce unexpected results sometimes. Consider the following code:
n = 500;
bonus = n + sales > 15000 ? 250 : 50 ;

The above code is trying to add n and the value 250 or 50 depending upon whether sales > 15000 is true or false. But this code will not work in the desired manner. The above code will be interpreted as follows:
bonus = (n + sales) > 15000 ? 250 : 50;

Because operator ‘+’ has higher precedence over > and ?:
Therefore, for the desired behaviour the conditional expression should be enclosed in parentheses as shown below:
bonus = n + (sales > 15000 ? 250 : 50) ;

The [ ] Operator

The square brackets are used to declare arrays, to create arrays, and to access a particular element in an array. Similar data items, such as marks of 20 student or sales of 30 salesmen etc., are combined together in the form of arrays. Here’s an example of an array declaration
Float [ ] arrayofFloats = new float[10] ;

The previous code declares an array that can hold ten floating point numbers. Here’s how you would access the 7th item in that array :
arrayOfFlooats[6];

Please note that first element of array is referred to as array-named[0] i.e., to refer to first item of array namely arrayOfFloats, we shall write arrayOfFloats[0]. We are not going into further details of arrays right now.

The . Operator

The dot (.) operator accesses instance members of an object or class members of a class.

The ( ) Operator

When declaring or calling a method, the method’s arguments are listed between parenthesis ( and ). You can specify an empty argument list by using ( ) with nothing between them.

The ( type ) Operator

This operator casts ( or “ convent “ ) a value to the specified type. You’ll see the usage of this operator a title later in this chapter, under the topic Type Conversion.

The new Operator

You can use the new operator to create a new object or a new array. You’ll find examples highlighting the usage of new operator in a later section – Objects as instances of class – in this chapter.

The instance of Operator

The instanceof operator tests whether its first operand is an instance of second.
Op1  instanceof   op2

Op1 must be the name-of-an-object and op2 must be the name -of -a –class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.

Assignment and Shorthand Assignment Operators used in JAVA with Example

Java provides some assignment and shorthand operators listed in the article with example of each. The article also explains a table with all these assignment operators provided by JAVA Programming.

Like other programming languages, Java offers an assignment operator =, to assign one value to another e.g.
int x, y, z;
x = 9;
y = 7;
z = x + y;
z = z * 2;

Java shorthand Operators

Java offers special shorthand operators that simplify the coding of a certain type of assignment statement. For example,
a = a + 10; may be written as a += 10;

The operator pair += tells the compiler to assign to a value of a + 10. This shorthand works for all the binary operators in Java (those that require two operands). The general form of Java shorthand is
var = var operator expression same as var operator = expression

Following are some examples of Java shorthands:
X   -= 10; equivalent to x = x-10;
X*=3; equivalent to x=x*3;
X /=2; equivalent to x=x/2;
X%=z; equivalent to x=x%z;

Thus, we can say (=,*=, /=, %=, -=) are assignment operators in Java. The operators (*=, /=, %=, += and -=) are called arithmetic assignment operators. One important and useful thing about such arithmetic assignment operators of Java is that they combine an arithmetic operator and an assignment operator, and eliminate the repeated operand thereby facilitate a condensed approach.

The following table lists some shortcut assignment operators and their lengthy equivalents:

Shorthand assignment operators in java


Sunday, April 27, 2014

Solve Decision-Making Expression using Logical Operators in JAVA

Relational operators often are used with logical operators (also known as conditional operators sometimes) to construct more complex decision-making expression. The Java programming language supports six conditional operators-five binary and one unary-as shown in the following image.


The logical OR operator (||)

The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to Boolean true if either of its operands evaluate to true.

This principle is used while testing evaluating expressions. Following are some examples of logical OR operation:

  • (4= =4) || (5 = =8)    results into true because first expression is true.
  • 1 = = 0 || 0 > 1         results into false because neither expression is true (both are false).
  • 5 > 8 || 5 < 2            results into false because both expression are false.
  • 1 < 0 || 8 > 0            results into true because second expression is true.

The operator || (logical OR) has lower precedence than the relational operators, thus, we don’t need to use parenthesis in these expressions.

The logical AND operator (&&)

The logical AND operator, written as &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expression (its operands) are true. Following are some examples of AND operator (&&).

  • (6 == 3) && (4 == 4)           results into false because first expression is false.
  • (4 == 4) && (8 == 8)           results into true because both expressions are true.
  • 6 < 9 && 4 > 2                     results into true because both expressions are true.
  • 6 > 9 && 5 < 2                     results into true because both expressions are false.

Because logical AND operator (&&) has lower precedence than the relational operators, we don’t need to use parentheses in these expressions.

The logical NOT operator (!)

The logical NOT operator, written as "!", works on single expression or operand i.e. it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e. if the expression is true, then expression is false, and vice versa.

Following are some examples of logical NOT operation:

  • ! (5 ! = 0) results into false because 5 is non zero (i.e., true)
  • ! (5 >2) results into false because the expression 5>2 is true.
  • !(5>9)  results into true because the expression 5>9 is false.

The logical negation operator "!" has a higher precedence then any of the relational or arithmetic operators. Therefore, to negate an expression, you should enclose the expression in parentheses:

!( x > 5 ) will reverse the result of the expression x > 5
    Whereas! x > 5 is equivalent to ( ! x ) > 5

i.e., it will first reverse the truth value of x and then test whether the reverse of x’s truth value is greater than 5 or not.

Relational Operators in JAVA

Compare Values using Relational Operators in JAVA

In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands.

Java provides six relational operator for comparing numbers and characters. But they don’t work with strings. If the comparison is true, the relational expression results into the Boolean value true and to Boolean value false, if the comparison is false. The six relational operators are:

  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to) and
  • != (not equal to)

Summarizes the action of these relational operators.

Compare Values using Relational Operators in JAVA

t represents true and f represents false.
The relational operators have a lower precedence than the arithmetic operators. That means the expression
a + 5 > c – 2  ...expression 1
Corresponds to
( a + 5 ) > ( c – 2 ) ...expression 2
And not the following
a + ( 5 > c ) -2  …expression 3

Though relational operators are easy to work with, yet while working with them, sometimes you get unexpected results and behavior from your program. To avoid so, we would like you to know certain tips regarding relational operators.
Do not confuse the = and the = = operators.
A very common mistake is to use the assignment operators (=) in place of the relational operator (==). Do not confuse the testing the operator (==) with the assignment operator (=). For instance, the expression
Value = 3
Tests whether value is equal to 3? The expression has the Boolean value true if the comparison is true and Boolean false if it is false.

But the expression
Value = 3
Assigns 3 to value. The whole expression, in the case, has the value 3 because that’s the value of the left-hand side.
Avoid equality comparisons on floating-point numbers.
Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 X 5 is exactly 15, but 3.25 X 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 X 5.25 is 17.0625.

Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.
The relational operators group Left-to-right i. e., a <b<c means (a <b) < c and not a < ( b < c ).

Postfix version of operators 

Monday, March 3, 2014

Increment and Decrement Operators in Java Programming

Earlier article was about the operators in java with some of the binary operators, example of each. This article is about plus (+) operator and increment/decrement operator in brief.

Operator + with strings

Programmer have used the operator ‘+’ with numbers. When you use + with numbers, the result is also a number. However, if you use operator + with strings, it concatenates them for example:

(5 + 6) results in to 11.
(“5” + “6”) results in to “56”.
(“17” + “A, V. Vihar”) result in to “17 A, V. Vihar”
(“abc” + “123”) results in to “abc 123”
(“” + 5 + “xyz”) results in to “5xyz”
(“” + 5) results in to “5”

(In above two expressions Java would internally convert 5 in to “5” first and then concatenate with “xyz” and “” respectively.)

Increment/Decrement Operators (++, --)

Java includes two useful operators not generally found in other computer languages (expect C and C++). These are the increment and decrement operators, ++ and --. The operators ++ adds 1 to its operand, and – subtracts one.

In other words,
a = a + 1;        same as   ++a ; or a++;
And
a = a – 1          same as --a ; or a --;

However, both the increment and decrement comes into two varieties: they may either precede of=r follow the operand. The prefix version comes before the operand (as in ++a or --a) and the postfix version comes after the operand (as in a++ or a--). The two version have the same effect upon the operand, but they differ when they take place in an expression, that would be discussed in later articles.

Wednesday, February 26, 2014

How to Use Operators with Strings in Java Programming

Operator + with strings

You have used the operator + with numbers. When you use + with numbers, the result is also a number. However, if you use operator + with strings, it concatenates them e.g.

5 + 6 results in to 11.
“5” + “6” results in to “56”.
“17” + “A, V. Vihar” result in to “17 A, V. Vihar”
“abc” + “123” results in to “abc 123”
“” + 5 + “xyz” results in to “5xyz”
“” + 5 results in to “5”

(In above two expressions Java would internally convert 5 in to “5” first and then concatenate with “xyz” and “” respectively.)

Increment/Decrement Operators (++, --)

Java includes two useful operators not generally found in other computer languages (expect C and C++). These are the increment and decrement operators, ++ and --. The operators ++ adds 1 to its operand, and – subtracts one.
In other words,
a = a + 1;
is the same as
++a ; or a++;
And
a = a – 1
is the same as
--a ; or a --;

However, both the increment and decrements come in to two varieties: they may either precede of=r fallow the operand. The prefix version comes before the operand (as in ++ a or -- a) and the post-fix version comes after the operand (as in a++ or a--). The two version have the same effect upon the operand, but they differ when they take place in an expression.

Wednesday, February 19, 2014

Types and Examples of Binary Operators in Java Programming part-2

Operators that act upon two operands are referred to as Binary Operators. The operands of a binary operator are distinguished as the left or right operand. Together, the operator and its operands constitute an expression.

Addition operator (+). The arithmetic binary operator ads the values of its operands and the result is the sum of the values of its operands and the result is the sum of the values of its two operands. For example,
4 + 20 result in 24.
A + 5 (where a = 2) result in 7.
A + b (where a = 4, b = 6) result in 10.
Its operands may be of integer (byte, short, char, int, long) or float (float, double) types.

Subtraction operator (-). The – operator subtracts the second operand from the first. For example,
14 – 3 evaluates to 11
A – b (where a = 7,  b = 5) evaluates to 2.
The operands may be of integer or float types.

Multiplication operator (*). The * operator multiplies the values of its operands. For example,
3 * 4 evaluates to 12.
b * 4 (where b = 6) evaluates to 24.
a * c (where a = 3, c = 5) evaluates to 15.
The operands may be of integer or float types.

Division operator (/). The / operator divides its first operand by the second. For example,
100 / 5 evaluates to 20.
a / 2 (a = 16) evaluates to 8.
a / b (a =15.9, b = 3) evaluates to 5.3.
The operands may be of integer or float types.

Modulus operator (%). The % operator finds the modulus of its first operand relative to the second. That is, it produces the remainder of dividing the first by the second operand. For example,

19 % 6 evaluates to 1, since 6 goes into 19 three times with a reminder 1. Similarly 7.6 % 2.9 results into 1.8 and – 5% -2 result into -1.

Thursday, February 13, 2014

Types and Examples of Operators in Java Programming part-1

In Java programming, the operations (specific tasks) are represented by operators and the objects of the operations (s) are referred to as operands.
Java’s rich set of operators comprise of arithmetic, relational, logical and certain other type of operators. Let us discuss these operators in detail.

Arithmetic Operators

To do arithmetic, Java use operators. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division and remainder which are +, -, *, / and % respectively. Each of these operators is a binary operator i.e., it requires two values (operands) to calculate a final answer. A part from these binary operators, Java provides two unary arithmetic operators (that require one operand) also which are unary +, and unary -.

Unary Operators

Operators that act on one operand are referred to us as Unary Operators.

Unary +. The operators unary ‘+’ precedes an operand. The operand (the value on which the operator operates) of the unary + operator must have arithmetic type and the result is the value of the argument.
For example

if a = 5 then +a means 5.
if a = o then +a means 0.
If a = -4 then +a means -4.

Unary-. The operator unary – precedes an operand. The operand of the unary – operator must have arithmetic type and the result is the negation of its operand’s value.
For example

If a = 5 then –a means -5
if a = o then +a means 0. (There is no quantity known as -0)
If a = -4 then +a means -4.

This operators reverse the sing of the operand’s value.

Binary Operators

What is the Scope of Variable in Java Programming?

In Java Programming, an important thing that you must know about variable is their scope. Scope generally refers to the program-region within which a variable is accessible. The board rule is: a variable is accessible with in the set of braces it is declared in e.g.

{
int a ;
:  /* a would be accessible as long as its block (a block is marked with a pair of matching brace) is not closed. Variable a is said to have block scope*/
}

Constants

Often in a program you want to give a name to a constant value. For example you might have fixed tax rate of 0.030 for goods and tax rate of 0.020 for services. These are constants, because their value is not going to change when the program is executed. It is convenient to given these constant a name.

This can be done as follows:

final double TAXRATE = 0.25;
The keyword final makes a variable as constant i.e. whose value cannot be changed during program execution.

Consider the following program that declare and uses two constants.

class calculateTax {
:  {
            final double GOODS_TAX =0.030 ;  
            final double SERVICE_TAX = 0.020 ;
                         …………
         }
     }

The reserved word final tells the compiler that the value will not change in the program. The names of constants follow the same rules as the names for variables. (Programmers sometimes use all capital letters for constants; but that is a matter of personal style, not part of language).      

Once declared constants, their value cannot be modified e.g.; after declaring constant GOODS_TAX, if you issue a statement like:

GOODS_TAX =0.050 ;  //error
It will cause an error, as the value of constants cannot be modified.

Advantage of Constants

They make your program easier to read and check for correctness.
If a constant needs to be changed (for instance a new tax law changes the rates) all you need to do is change the declaration. You don’t have to search through your program for every occurrence of a specific number.

© Copyright 2013 Computer Programming | All Right Reserved