Variable Declaration and Initialization

The variable is a basic unit of storage in a Java Program.



Declaring a Variable: In Java, all the programs must be declared before they can be used.

Program to demonstrate what happens when we use a variable without declaring it:

class VariableNotDeclared
{
   public static void main(String args[])
   {
        a=5;    //Using a variable without declaring it
        System.out.println(a);
   }
 }

Output of this program:

Error. "Cant find the symbol a . Symbol: Variable a  Location: VariableNotDeclared" 

This error is displayed because we've not declared the variable a.

Program to demonstrate that we can declare more than one variable of same type in a single statement

class MultiDeclarationsSingleStatement
{
   public static void main(String args[])
   {
      int a,b,c;    //Here I've delcared three variables a,b and c as int data type in a single statement
 
      a=3;
      b=4;
      c=5;
 
      System.out.println("a:"+a);
      System.out.println("b:"+b);
      System.out.println("c:"+c);

   }
 }

Output of this program:

a:3
b:4
c:5

Program to demonstrate that we can initialize the variables while declaring itself

class InitializingVariablesWhileDeclaration
{
   public static void main(String args[])
   {
      int a=3,b=4,c=5;    // Initializing the variables by assigning values while declaring the variables itself

      System.out.println("a:"+a);
      System.out.println("b:"+b);
      System.out.println("c:"+c);

   }
 }

Output of this program:

a:3
b:4
c:5


Program to demonstrate the dynamic initialization of variables 

class DynamicInitialization
{
   public static void main(String args[])
   {
      int a=3,b=4;

      int c=a+b;    // Initializing the variable c dynamically i.e. while performing a+b operation and assigning it to c
      System.out.println("c:"+c);

   }
 }

Output of this program:

c:7

Assigning values to variables of different data type

The following are the example programs for demonstrating what happens when the variable's data type and the assigning value's data type don't match (Some cases throws errors where as some cases will convert the values).



Program to demonstrate what happens on providing a decimal value to a variable which is declared as an int data type.

class IntVariableDecimalValue
{
   public static void main(String args[])
   {
        int a=123.456;   // We have assigned a decimal value to a variable which is declared as int
        System.out.println(a);
   }
 }

Output of this program:

Error displayed while compiling the program. "Required int but found double"

This means that Java is telling us to provide the integer value instead of double (i.e. decimal) value.

Program to demonstrate what happens on providing an integer value to a variable which is declared as an double data type.

class DoubleVariableIntegerValue
{
   public static void main(String args[])
   {
         double a=123;    // We have assigned an integer value to a variable which is declared as double
         System.out.println(a);
   }
 }

Output of this program:

123.0

This means that Java will automatically assign 123.0 instead of 123 to the variable which is declared as double

Program to demonstrate what happens on providing a character value to a variable which is declared as int data type

class IntVariableCharValue
{
   public static void main(String args[])
   {
          int a='x';   // We have assigned a character value to a variable which is declared as int
          System.out.println(a);
   }
 }

Output of this program:

120

This means that Java will automatically convert the char value to Unicode value and assign it to the variable which is declared as int

Program to demonstrate what happens on providing a character value to a variable which is declared as boolean data type

class BooleanVariableCharValue
{
     public static void main(String args[])
    {
         boolean a='x';   // We have assigned a character value to a variable which is declared as boolean
         System.out.println(a);
   }
 }

Output of this program:

Error displayed while compiling the program. "Required boolean but found char"

This means that Java is telling us to provide the boolean value instead of char value.

Program to demonstrate what happens on providing a long integer value to a variable which is declared as short data type

class ShortVariableIntValue
{
     public static void main(String args[])
    {
         short a=1234567;   //Assigning an int value to a variable which is declared as short
         System.out.println(a);
     }
 }

Output of this program:

Error displayed while compiling the program. "Required short but found int"

This means that Java is telling us to provide the short value instead of int value.

Program to demonstrate what happens on providing an integer value to a variable which is declared as byte data type

class ByteVariableIntValue
{
    public static void main(String args[])
   {
        byte a=12345;   //Assigning an int value to a variable which is declared as byte
        System.out.println(a);
   }
 }

Output of this program:

Error displayed while compiling the program. "Required byte but found int"

This means that Java is telling us to provide the byte value instead of int value.

Program to demonstrate what happens on providing an integer value of size more than 10 digits to a variable which is declared as long data type

class LongVariableLongValue
{
   public static void main(String args[])
   {
         long a=1234567891112;  // Assigning a 13 digit integer value to a long declared variable
         System.out.println(a);
   }
 }


Output of this program:

Error displayed while compiling the program. "integer number too large"

This means in Java you cant assign an integer value of more than 10 digit size to a long declared variable. But the variable declared as long can hold more than 10 digit number if the value comes from an operation done as shown in the next example.


Program to demonstrate what happens when a variable declared as long gets an integer value of more than 10 digit in size from an operation

class LongVariableLongValueFromOperation
{
   public static void main(String args[])
   {
         long a=123456789, b=123456789, c;   // Assigning  integer values of 10 digit size to a and b variables
         c=a*b;  // c is a variable which is declared as long in the earlier step and will be assigned an integer value which is a result of  a*b (The result of this operation is an integer number of size more than 10 digits)
         System.out.println(c);
   }
 }

Output of this program:

15241578750190521  

This means the variable c which is declared as long is now holding an integer number which is of 17 digit size.


Program to demonstrate what happens when a variable declared as char is assigned a boolean value

class CharVariableBooleanValue
{
   public static void main(String args[])
   {
        char a=true;    // Assigning a boolean value true to the variable which is declared as char
        System.out.println(a);
   }
 }


Output of this program:

Error displayed while compiling the program. "Required char but found boolean"

This means that Java is telling us to provide the char value instead of boolean value.



'boolean' data type

'boolean' variable can only hold one of two possible values, true or false.




Program demonstrating the boolean type:

class BoolTest1
{
   public static void main(String args[])
   {
      boolean b=false;
      System.out.println(" b is " +b);

      b=true;
      System.out.println(" b is " +b);

    }
 }

Output of this program:

b is false
b is true



Program demonstrating that a boolean value can control the if statement
class BoolTest2
{
   public static void main(String args[])
   {
      boolean b=true;

      if(b)
      System.out.println("This is executed");

      b=false;

      if(b)
      System.out.println("This is not executed");

    }
 }
      
Output of this program:

This is executed



Program demonstrating that the outcome of a relational operator is a boolean value

class BoolTest3
{
   public static void main(String args[])
   {

      System.out.println("10 > 9 is "+(10>9));

   }
 }

Output of this program:

10 > 9 is true

'char' data type

Unlike the old programming languages C/C++, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all the characters found in all human languages. The range of char in Java is 0 to 65536.




Program demonstrating char variables:

class CharDemo
{
    public static void main(String args[])
    {
         char ch1, ch2;
     
          ch1 = 88;  // Unicode value which represents the letter X
          ch2 = 'Y';

          System.out.print("ch1 and ch2: ");
          System.out.println(ch1+ " " + ch2);
     }
}

Output for this program:

ch1 and ch2: X  Y



Program to show that the char variables behave like integers:

class CharDemo2
{
    public static void main(String args[])
    {
         char ch1='X';
         System.out.println("ch1 before increment: "+ch1);

         ch1++; //Increment ch1 char variable by one
         System.out.println("ch1 after increment: "+ch1);
     }
}

Output of this program:

ch1 before increment: X
ch1 after increment: Y

'float' data type

The variable which is declared using 'float' data type can store decimal values. But the only thing to observe is that the value should end with letter f as shown in the below program.


class Sample
{
     public static void main(String args[])
     {
          float a=123.456f;   //Observe that the value to be stored in the float declared variable should end with 'f' letter.
     
           System.out.println(a);
      }
}

Output of this program:

123.456

Try this program without adding the letter f at the end of the value. Observe that the program will throw an error on compiling the program.

'long' data type




Lets first compute the distance light travels using the 'int' data type to find out its drawbacks.

Computing the distance light travels using 'int' data type: 

class Light
{
    public static void main(String args[])
    {
         int lightspeed, days, seconds, distance;
     
         lightspeed = 186000;  // Approximate speed of light in miles per second
         days = 1000;

         seconds = days*24*60*60; // days x 24 hours x 60 minutes x 60 seconds
         distance = lightspeed*seconds; // compute distance

         System.out.print("In " + days);
         System.out.print(" days light will travel about ");
         System.out.println(distance + " miles.");
     }
}

Output of this program:

In 1000 days light will travel about -1367621632 miles. (Wrong output)

Reason for wrong output:

The int data type can hold that values of lightspeed, days and seconds variables (You can checkout by printing their values in the program and verify them using your system calculator), but int data type was not long enough to hold the value of distance variable. 




Lets try the above program with 'long' data type and find out how it resolves the above problem

Computing the distance light travels using 'long' data type: 

class Light
{
    public static void main(String args[])
    {
        long lightspeed, days, seconds, distance;
     
         lightspeed = 186000;  // Approximate speed of light in miles per second
         days = 1000;

         seconds = days*24*60*60; // days x 24 hours x 60 minutes x 60 seconds
         distance = lightspeed*seconds; // compute distance

         System.out.print("In " + days);
         System.out.print(" days light will travel about ");
         System.out.println(distance + " miles.");
     }
}

Output of this program:

In 1000 days light will travel about 160700000000 miles (Correct output)

'double' data type

As you have seen that assigning decimal values to the integer variable is resulting in an error in our previous post. So we have to declare the variable with the data type that allows us to assign decimal values to the variables. This is possible only by declaring the variables using 'double' data type.




The following program will demonstrate the 'double' data type:

class Sample
{
     public static void main(String args[])
     {
         double count = 100.123;
         System.out.println(count);
      }
 }

Output of this program:

100.123




Program to compute the area of the circle using 'double' data type

class Area
{
  public static void main(String args[])
  {
     double pi,r,a;
 
     r = 10.8;   //Radius of the circle
     pi = 3.1416;   //Approximate Pi value
     a = pi*r*r;   //Compute area of the circle
 
     System.out.println("Area of the circle is " + a);
   }
 }

Output of this program:

Area of the circle is 366.436224

'int' data type

Data Types - In order to assign a value to a variable in Java, we have to first declare the variable as any type. For example, if you want to store integers like 10, 100 etc into a variable say 'var', we have to declare the 'var' as type 'int' as shown below -


int var;

Now we can assign an integer value say 100 as shown below -

var = 100; 

Now if you try to assing a non-interger value say "cat", Java will give you an error -

var = "cat";

Hence in Java, we use Data Types to define the variables to store the required type of values. The below examples will give you an understanding of how Data Types help us to declare variables of different types and assign values to the variables.



int is the most commonly used integer data type.


A sample program for demonstration the usage of int data type:

class Sample1
{
     public static void main(String args[])
     {
          int count = 100;    // A variable declared using integer data type int can store integer values like 100 
          System.out.println(count);
      }
 }

The output of this program will be:

100




What happens on passing the decimal values to an integer variable?

class Sample2
{
    public static void main(String args[])
    {
         int count;
         count = 100.123;
         System.out.println(count);
     }
 }

The following error will be displayed on compiling this program:

error: possible loss of precision

      count=100.123;
            ^
  required: int
  found:    double
1 error


'short' data type is also an integer data type but stores less range of values from -32768 to 32767. This is a very less used data type, so I'm not writing it in a separate post.

'byte' data type is also an integer data type but stores less range of values from -128 to 127. This is a very less used data type, so I'm not writing it in a separate post.

Ranges of Integer data types:

Second Simple Java Program

First lets understand the concept of Variables followed by writing the second simple Java program.


Variables

Variable is a named memory locations that can be assigned a value by your program.

Example of a variable in Java Programming Language:

int num = 5;

Here num is a variable name to which the value 5 is assigned. And also this variable name is declared as int to store integer values like 5.

Second Simple Java Program

    /*
         Here is another short example.
         Call this file 'Example2.java'.
   */

    class Example2
    {

           public static void main(String args[])
           {

                int num;   // This statement declares the variable called num as integer variable.
           
                num = 100; // This statement assigns the value 100 to the integer variable num.
           
                System.out.println("This is num: " + num);  //This prints the current holding value of num variable 
 
                num = num * 2;  // This statement multiplies the value assigned to the num integer variable by 2. i.e. num = 100 * 2. So after multiplications the resultant value will be stored in num (i.e. num will be holding 200 after Java executing this statement)
           
                System.out.print("The value of num * 2 is ");
                System.out.println(num);  

            }

    }

Output of this program

This is num: 100  
The value of num*2 is 200

Observe that though we have three print statements, we got the output for only two. This is because the second print statement is using print( ) method instead of println( ) method to print the output. Hence at the output console the third print statement will get printed in the same line of the second print statements output. In order to have the all the statements in this program to print the outputs in the separate lines we have to use println( ) method instead of print( ) statement in the second print statement.

First Simple Java Program

I will write down the simple java program first and will explain each and every line of this program followed by it.


First Simple Java Program


/*  
    This is a simple Java Program.
    Call this file 'Example.java'
*/

class Example
{

      // Your program begins with a call to main() method.

      public static void main(String args[])
      {
       
             System.out.println("This is a simple java program");

       }

}


Output of the above program is: This is a simple java program


Step by Step explanation of the above program:


The program beings with the following lines.

   /* 
         This is a simple Java Program.
         Call this file 'Example.java'
   */ 

This is a multiline comment which starts with /* and ends with */. All the lines between /* and */ will be treated as comments and wont be executed by JVM. This syntax is mainly used if there are more than one lines of comments.

   class Example
   {
        
    }

We can clearly understand from the code that we have created a class named Example. In Java, all the code must reside inside a class by writing the code inside the braces i.e. { and } of the class.

Note - The name of the class should match the name of the file that holds this program. In this example, the name of the class is Example , so while saving this program having the class Name as Example, we've to save the program file as Example.java. If we save the program file with a different name then your program wont execute. And also observe that if the class name is Example and you are going to save the program file as example.java, the program wont run as the class name and program file name wont match in case.

    // Your program begins with a call to main() method

This is a single line comment that starts with // and ends at the end of the line. JVM wont execute the single line comments.

   public static void main(String args[])
   {

    }

This is the line at which the program will begin execution. All the Java applications will begin execution by calling main() method. There can be more than one method inside a class but the program execution starts from main() method only. The main method may further call the other methods in the class for execution.

Also we've to understand the usage of public, static, void and String args[] terms in this simple program.

  • public - This means we've specified the main( ) method as public method. All the members of the class (i.e. methods and instance variables) which are preceded by public access specifier can be accessed by code outside the class. In this example main( ) method is preceded by public access specifier, hence it can be accessed by the code outside the main( ) method. We've to always use public access specifier before the main( ) method, because the main( ) method should always be accessed from outside the class by Java Virtual Machine (JVM).
  • static - In order to call any method from outside the class, we've to create an instance (creating object) for the  class in which the method is available. We have to create an instance where ever we want to use this method. But by specifying static keyword before any method, we can use the methods outside the class without creating any instances (i.e. without creating objects for the class in which the method is available). Since main( ) method  is called by the JVM before any objects are created, we've to specify static keyword in order to use the main() method.
  •  void - Using methods we can return values. For example there is a method called addition method which contains the code to add two numbers. When ever this method is called, the addition method can return sum of the two given numbers. The returned sum can be used by the method which called the addition method. But by specifying the void keyword before any methods, we are telling the compiler that this method is not going to return any values. Since we're specifying the void keyword before the main() method in the above simple program, we're telling the compiler that this main( ) method is not going to return any values.
  • main(String args []) - All the methods receives the information from outside the method, by using the variables (also called as parameters) which are specified within the set of parenthesis(i.e. (  ) )that follow the name of the method. Here in the above simple program, we've give the parameter as args[] and we've declared it as String type. args[] parameter receives any command line arguments present when the program is executed. But this simple program is not making use of String args[], we'll discuss more on this topic in the future posts. So when ever we write the main method, we've to compulsorily use the args[] parameter by declaring it as a String irrespective of whether the main() method will use it or not. For the other methods, when there is noting to be received by the methods, we can keep the braces empty i.e. addition( ). i.e. addition( ) method wont receive any information from outside the method as the braces followed by the method name addition don't have any parameters. 
All the code related to the main() method should be written inside the braces { and } of the main( ) method. The same applies to the other normal methods.


    System.out.println("This is a simple Java program.");


This line of code is written inside the main( ) method in the above simple program. This line prints  This is a simple Java program. output on execution.

We've to understand the 'println( )', 'System' and 'out' terms to understand how this line prints the This is a simple Java program text as output.

  • println( ) - This is a built-in method of Java. i.e. Writing any separate code for this method is not requried, as this is built-in method which is readily available in Java. In this case println( ) method  will display the text that is passed to it under " " as output.
  • System - This is a predefined class of Java that provide access to the system on which the output needs to be displayed. 
  • out - is the output stream that is connected to the console.

Also you may notice that the above line ends with a semicolon ; . All the statements in Java end with a semicolon. All the other lines in the above simple program which don't end with the semicolon are
not statements.

Object Oriented Programming

What is Object Oriented Programming ?


Object Oriented Programming organizes a program around its data (that is objects) and a set of well defined interfaces to that data. Object Oriented Program can be characterized as data controlling access to code.

Object Oriented Programming methodology is to design a program using classes and objects.It simplifies the software development and maintenance by providing some concepts:
  •  Object
  •  Class 
  •  Inheritance
  •  Polymorphism
  •  Abstraction
  •  Encapsulation

Object 

Object is an instance of a class. i.e. In Java program we're going to use object as an instance of a class as shown below:

class Pen   // Pen is a class. It is a template for creating objects.
{
    public static void main(String args[])
    {
       Pen Reynolds = new Pen();  // Reynolds and Parker are objects. These objects are just instances of the class Pen.
       Pen Parker = new Pen();
     }
}

Class

Any concept you wish to implement in Java must be encapsulated in a Class. And also the class is a template or blueprint from which objects are created.

class Pen   // Pen is a class. It is a template for creating objects.
{
    public static void main(String args[])
    {
       Pen Reynolds = new Pen();  // Reynolds and Parker are objects. These objects are just instances of the class Pen.
       Pen Parker = new Pen();
     }
}

Abstraction

Abstraction in java is used to hide certain details and only show the essential features of the object.

For example: - People don't think of a car as set of tens of thousands of individual parts, instead think car as a well defined object with its own unique behaviors like Speed, Mileage etc.

Encapsulation

Encapsulation is a protective wrapper that prevents the code and data from being arbitrarily accessed by the other code defined outside the wrapper. Access to code and data inside the wrapper is tightly controlled through a well defined interface.

Class is the protective wrapper that prevents the code and data from being arbitrarily accessed by the other code defined outside the wrapper . The Code and  Data are called as the members of a class. The data defined by the class are referred to as instance variables. The code that operates on the defined data is called as method. Methods define how the instance variables/data can be used (i.e. Behavior and interface of a class are defined by methods that operate on  its instance variables/data). Since the purpose of the class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation  inside the class. Each method or variable in a class can be marked as public or private. The public method or variable inside a class can be accessed from the outside of the class, where as the private method or variable inside a class cant be accessed outside of the class.

i.e. In Java, code (i.e. Methods) and data (i.e. instance variables) are protected inside a wrapper called  class.

Inheritance

Inheritance is a mechanism in which one object acquires the properties of another object. The following example will show you how the objects are hierarchically organized and how the child objects inherit the properties from the parent objects


In programming like Java, the idea behind using Inheritance concept is to create a new classes built upon existing classes. i.e. The new classes reuses the methods and data by inheriting them from the existing classes.

Polymorphism

Polymorphism means of having many forms. In programming languages like Java, polymorphism concept is subjected to methods, where the code inside the same method can perform differently on different conditions.

Example: - Suppose there a method called 'Smell' under class 'Dog'. The output of the 'Smell' method can take several forms i.e. 1. When a dog smells a cat -> The output of the 'Smell' method will be 'The dog barks and runs after the cat' 2. When a dog smells food -> The output of the 'Smell' method will be 'The dog will salivate and run after its bowl'. Hence in this example I want to conclude that the same  method 'Smell' will take different forms based on what the dog smells.

Write and execute Java Programs using TextPad tool

Pre-requisites -

  1. Install Java JDK as explained in the Install Java JDK
  2. Configure Java as explained in the Configure Java
  3. Understand the Simple Java Program explained in the A Simple Java Program
  4. Install TextPad editor tool as explained in the TextPad editor Installation
Please follow the below steps to write and execute Java programs using TextPad editor tool:

1. Launch TextPad editor tool as shown below:


2. Write any sample Java program in the editor tool as shown below:


3. Select 'Compile Java' option  from the Tools Menu -> External Tools Sub Menu (or you can also try Ctrl+1 shortcut key instead):



4. Ensure that the 'Sava As' dialog is displayed. In 'Save As' dialog, ensure that 'Save As Type' is selected as All Files , type 'Simple.java' into the 'File Name' field (Ensure that the class name you have mentioned in the above java program and the name you are giving here to save the Java file should match else the java program will throw an error i.e. class Simple in the java code and Simple.java while saving) and click on 'Save' button as shown below:



5. Repeat Step 3 to compile the saved Java file 
6. Select 'Run Java Application' option from the Tools Menu -> External Tools Sub Menu (or you can also try Ctrl+2 shortcut key instead)


7. Observe that the output of the above written Java program is displayed in the command window as shown below:


TextPad editor installation

TextPad is an editor which will help us in writing Java Programs and execute them from the editor itself, i.e. instead of executing the java program from command line. Below, I will explain from where we've to download the TextPad and how to install it.


1. Go to  http://www.textpad.com/download/ page
2. Choose the English User interface and click on 'Download' link as shown below (Install 32-bit if you have 32 bit machine or Install 64-bit if you have 64 bit machine):



3. Right click on the downloaded Zip file and unzip it (I use WinRAR software to unzip Zip files) as shown below:


4. Open the unzipped folder and double click on the Setup file to install the software as shown below:


5. Ensure that you are able to launch the TextPad application without any problems after its installation as shown below: