-->

Thursday, February 18, 2016

How to retrieve items from database table in JAVA using Netbeans

In this article i will explain you, how to retrieve items from database table in Java using Netbeans. In previous article, we have already learned, how to create connection with the derby database using netbeans. Before reading this article, please must to see the previous article for implementations. In this article, i only explain you, how to use executeQuery( ) method and select statement in java.

--How to create connection with database full video tutorial 


Code :

class abc {
    public abc() throws SQLException
    {
        Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/student", "tarun", "tarun");
        System.out.println("Connection Created");
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select * from USERTABLE");
        while(rs.next())
        {
            System.out.println(rs.getString(2));
        }
   
    }

}

Here, we have a table i.e USERTABLE. If you want to learn how to create table in exists database using Netbeans. Read mentioned steps:
Step-1 :  Right click on Connection String, select "connect" from popup menu.
Step-2 :  Expand username which contains Tables, views and stored procedure.
Step-3 :   Right click on table, select create table.


Write the name of table also add columns with their datatypes. 

Wednesday, February 17, 2016

How to create Database connection in JAVA using Netbeans

If you want to connect database with your java application then first to need a database. First to create database using Netbeans services tab. This tab available under Windows tab. You can also select this tab by using shortcut CTRL+ 5.


services tab in netbeans


  1. Expand the databases tab, select "Create Database." option. 
create database in netbeans

2. Fill fields which are shown under diagram.

Database fields in Netbeans
 3. After filling the form, you have to create database successfully.
 4. Right Click on your connection string name, select properties for copy the database URL.

java netbeans database properties

5. Copy Database URL, which is used further.

netbeans database properties
6. Create a new java project under projects tab. 
7. Add a Library in the "Libraries" section of your project.
add libraries in projects
8. Select Java DB Driver under Add Library section.

JAVA DB Drivers
9. Open your .java file which is exists in java packages folder of your project. 
10. Create a another class object, which is exists in same package.
11. Now, Open the object class, create constructor in it.
12. paste the code under the constructor.

Connection conn=DriverManager.getConnection("jdbc:derby://localhost:1527/jk", "jk", "jk");
        System.out.println("connection created"); 

Here we have three parameters in getConnection method. 
First refer to database url ; according to 5th step.
Second : Username 
Third :  password.

Saturday, December 12, 2015

AWT Frame close using close Button

In AWT Java we have a Frame class which is inherit from window class. If you are a beginner in AWT Java then you know that Frame doesn't close when we press close button of it. So, In last we pressed stop debugging button in Netbeans IDE. If you want to close Frame using Close button, which is see in top right corner of Frame then you should implement code for it. 


Complete Java Code


package awtframe;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class AWTFrame {

    public AWTFrame()
    {
        Frame f1=new Frame("Welcome to Closing");
        f1.setSize(500,500);
        f1.setVisible(true);
       
        f1.addWindowListener(new WindowAdapter(){
           
            @Override
            public void windowClosing(WindowEvent e)
            {
              System.exit(0);
            }
           
        });
       
       
    }
    public static void main(String[] args) {
     
       AWTFrame at=new AWTFrame();
       
    }
   
}

Here, we have windowClosing ( ) method to close Frame using close button.

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, November 10, 2014

Compiling and Running Java Programs

There are various steps to compiling and running java programs, these are
Step-1 : First to install JDK, JRE and JVM into the System.
Step-2 : Prepare source code in any editor like notepad, c++ editor etc.
Step-3:

class HelloWorld
{
public static void main(String r[])
{
int a=10, b=10,c;
c=a+b;
System.out.println("Output of the program is"+c);
}
}

Step-4 : Save the source code in the java bin directory. Class name which contain main method should same of the file name.
Example :  HelloWorld (class name)
                  HelloWorld.java (file name)

Step-5 : Open command prompt and change the directory where your java program has been saved.
Suppose your java software installed in C:/>. Now, compiling steps is:

C:/java/jdk1.7.0/bin> Javac filename.java   (press Enter)
C:/java/jdk1.7.0/bin> Java  filename.java    (press Enter)

Step-6: During compilation, if program generate errors, it means you can't run your program.                 

Wednesday, October 8, 2014

Life Cycle of applet

In the previous article, we have already learned about basics of applet.

Life Cycle of applet

1. init() : init method is used to initialize the applet. Before doing anything, must to initialized, so same thing with the applet. Like, in the games.
Before play any games, must to initialized all the  drivers in the system, which is necessary for the games. In the applet, init method is invoked only once, also that method invoked after param tag, which is inside in <applet></applet> tag.

2. start() : This is invoked after the initialization completed. It is used to start the applet, also automatic start. When user navigate to the web page, if
web page contain applet code then it start automatically also start when user moves from other web pages.

3. paint () : This method is invoked just after start() method. Actually only this method is responsible to design the applet, also responsible for repaint the browser, if applet is stooped. It has contain graphics argument as a parameter, through Graphics class we can design any graphics in the applet like rectangle, oval etc. Graphics class inherit from java.awt class.
4. stop() : This method is invoked, just after when the user moves to other browser tab from current applet tab.

5. destroy() : This method is invoked only that time when user close the browser. You can say, opened web page contain applet code , on that time applet is running
properly but in case if user close the browser, applet instance is automatically deleted from the page and destroy method is called automatically.

Example of Applet

The following is a simple applet named HelloWorld.java

import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 30, 50);
}
}

The first line of code define, imports some packages, which is used for design the applet. Here are two class that is applet and awt. In the second line of code, we have a class "HelloWorld" which is inherited from Applet class. This Applet class inside in java.applet.* package. Through the Graphics class, we can design new object in the applet. This class inherited from java.awt.*. In this example, we have to draw a string with height and width argument(width=30, height=50).
With the help of applet tag, we will show the output in any browser, which support applet. Applet tag is:
  <applet code="HelloWorld.class" width=50 height=60></applet>

This tells the viewer or browser to load the applet whose compiled code is in HelloWorld.class (in the same directory as the current HTML document), and to set the initial size of the applet to 50 pixels wide and 60 pixels high.

Monday, October 6, 2014

Basics of applet

Applet is a small java program that run in browser, but JVM is required for run applet in browser. Basically applet is used where user want to put some dynamic content into html page.
There are some features and advantages of Applet

Features:


  1. It is a java class file, which is inherit from java.applet.Applet class.
  2. A applet class file don't take main() method for entry point.
  3. Applet codes are embedded in HTML page
  4. For run the applet code in browser, must to install JVM in the client machine
  5. During the execution of applet code in browser, code first to download in the client machine.

Advantages:


  1. Very less response time because Applet designed for client machine. If applet is used for server machine then server take more time to execute applet code.
  2. More secure
  3. Platform independent, so it can run on any platform that is windows, Linux, UNIX, etc.
  4. Use for dynamic application


Disadvantages of applet


  1. For run to its code in browser, must to installed JVM plugin

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
© Copyright 2013 Computer Programming | All Right Reserved