Friday 27 February 2015

Inheritance in Java

         Inheritance is the process by which one object acquires the property of another object.Using inheritance you can create a general class which has all related items and this class can be inherited by other classes. The inherited class in called superclass and the class that does inheriting is called subclass in Java.

You can inherit a class using the keyword extends. Below is the simple example for inheritance.
You can copy code by select+ctrl+C
 


Output:

 





Types of Inheritance:
1) Single Inheritance
2) Multiple Inheritance
3) Multilevel Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance

1)Single Inheritance
If a class inherited to only one class then we call that inheritance as single inheritance.



Here Class A Extends to Class B here the inheritance is only one level .

2)Multiple Inheritance
If a class Inherits property from more than one class is called Multiple Inheritance.

Java does not supports Multiple inheritance by using Extends. We can achieve this by Implementing the interfaces. We will discuss more about this in Interfaces in Java section.

3)Multilevel inheritance.
One class inherited to another class and this class will be base class for next class.

Here Class A Inherited to Class B and class B is inherited to Class C . Class B will become base class for class C. Class C will have the properties of both the class A and B.

4) Hierarchical Inheritance
If the properties of one class is inherited to multiple classes then this inheritance is called the hierarchical inheritance.

5)Hybrid Inheritance
Hybrid inheritance is the combination of Hierarchical and multiple Inheritance. We can achieve Hierarchical inheritance using Extends and we can achieve Multiple inheritance using Implements .


Thursday 26 February 2015

Encapsulation in Java

       Encapsulation is the concept of hiding/restricting data to access from outside . Encapsulation provides the attribute access control. The access control can be achieved through access specifiers.

There are 4 access specifiers in Java
1)public
2)private
3)protected
4)default

Public:
   If you use public as access specifier then you can access those members of a class from outside the class/package also.

Private:
     If you use private access specifier then you cannot access those members of a class outside the class . it will be accessible only within that scope.
We will discuss later about the scope of an instance.

Protected :
     The protected access specifier behaves as private to outside but it will allow to access the members in inherited classes .

We will discuss more about protected with example in the section Inheritance.

default:  
      If you declare any members of a class without any access specifier i.e public,private,protected then it will consider the member as default . It is a private access specifier will allow to access the members of the class only inside that class.
Note: default is not a keyword to specify the access specifier. If you not mention the access specifier then it will be considered as default.

Example:
To copy the code you can select the code and ctrl+C


Output :
with out private variable access outside the class







 Error if you try to access private variable in another class







Classes in Java

       A class is the logical construct upon which entire java language is built. The class defines the shape and nature of an object. it consists of variables and methods.

      A class defines a new data type . An objects is the instance of the class and the objects can be created of the type class. In simple we can say class is template of the object and object is instance of the class.

General Syntax:


       The class can have only 2 access specifier i.e default and public. If you declare a class without any access specifier then it will consider it as default . If you wish to declare a class as public then you have to specify like
public class_name{//Body of the class}

Creating Object:
You can create an object of a class using below syntax
class_name object_name=new class_name();
you can call a method using (.) operator i.e object_name.method_name(parameter_list);

Example:


Output:








Saturday 21 February 2015

Jump statements in Java

Jump statements are the statements which transfers the control to another part of the program. There are 3 types of jump statements
1)break
2)continue
3)return

1)Using break statements
There are mainly 3 uses of break statement
           * It terminates a sequence in a switch statements.
           * It can be used to exit a loop
           * It can be used the civilized form of GO TO.

Example for exit a loop :


Output:









Example for form of Go TO:
Syntax:
break label;

where label is the name given to a block of code.



Output:







Using Continue:
In the iteration statement you can come up with a scenario as you need to continue with next iteration without executing the remaining statements in the loop body .In such scenario continue can be used.

Example:


Output:














 return statement:
The return statement is used to explicitly return from a method. It directly returns the control to the caller of the method.
We will discuss later about this with more examples.

Friday 20 February 2015

Iteration statements in Java

       Iteration statements are the statements which is used to specify the logic of a loop. i.e a same set of statements executes 0 or more times until termination condition is met. 

Java supports 3 iteration statements i.e for , while, and do-while . 

while Loop:
It is the fundamental loop statements in Java and it is the entry controlled loop statement.The block of statements will be executed until the condition is met. Once the conditions becomes false it will come out from the loop. 

Syntax:


The condition can be any Boolean expression. If you are using any counter for condition then you have to increment the counter for each iteration.

Example:


Output:









do-while Loop:
        If you use the while loop once the condition is false it will not execute the while block. If the condition is false at first attempt the while block will not execute at all. You may come across the scenario as the while block should execute at least once even though the condition becomes false .In such scenario you need to use do-while Loop. Make a note that in do-while Loop while statement should end with semicolon(;).

Syntax:


Output:







In the example l_count is initially 6 which is >5 and it is printed inside the while loop.

for Loop:
The for statement provides a compact way to iterate over a range of values. There are two types of for loop in java i.e Simple for Loop and for-each Loop

Simple for Loop:

Syntax:


No need to declare ,initialize and increment the counter outside the for loop as do that in while and do-while loop

Example :


Output:

As for-each Loop is advance concept we will discuss later with more examples.







Thursday 19 February 2015

Selection statements in Java

A selection statement is a control statements that allows the option between 2 or more execution paths in a program. Java supports 2 Types of selection statements i.e if and switch.

If statement in Java:
It is also called conditional branch statement

Simple if statement :
In simple if statement if a condition specified is satisfied then the if block will be executed. 

Syntax:


Example:


Output:







The if…else statement
In if…else statement if a condition specified is satisfied then the if block will be executed otherwise else block will be executed.

Syntax:


Example:


Output:

 





Nested if…else statement
In nested if…else statement you can use one if or else if statement inside another else if statement

Syntax:


Example:


Output:

 




The if..else..if ladder
The sequence of nested if statement is called if..else…if ladder.

Syntax


Example:


Output:

 




switch Statement:
The switch is the selection statement which is the multiway branch statement in java . We can say it is the best alternative for large series of if…else..if statement.

Syntax:


Example:


Output:








break statement is optional and if you omit , it will execute the next all case statements without checking the condition. 

If you omit the break statement from above Eg:


The output will be as below even though a=3 ideally it should not.

 





Nested switch statement:
We can use the switch statement inside another switch statement.

Syntax:


Difference between IF and Switch statement:
1) If statement is used to select among 2 alternatives . switch statement is used to select among multiple alternatives.
2) In if statement you compare about 2 objects using =,<,> but switch statement compares 2 objects only using equal.
3) If statement works under Boolean literal where as switch statement works under integer/character literals
4) Need to write complex code using if…else..if statement where as switch simplifies the complexity of the code .



Tuesday 17 February 2015

My First Java Program Using JDeveloper and command Prompt


You can create your java program using command prompt or Using JDeveloper. Let us discuss about both ways to create the java program.

1)My First Java program using JDeveloper:
Step 1: Open JDeveloper and create your own application

Right click on Applications->New

Select category as General and Items as Application

Name your application

Name your project name

Step 2: Create your Java program
Expand your application from applications Navigator and right click on your project >>New

Select category as General and Items as Java class

Name your class and select check box Generate mail method

Step 3: Execute your java program
Write the output statement in the program

Right click and Rebuild the program. Right click and Run the program. You can get the output at the bottom

2)My First Java program using Command Prompt:

Step 1: Create your java program in notepad and save the file with extention *.java 


Step 2: Need to set java path
If your *.java file is saved outside the JDK/bin folder you need to set java path.
There are 2 ways i.e Temporary and permanent 

How to set temporary path:
1)Go to command prompt and go to the location where the *.java file is placed.

2)Find the JDK/bin path and execute that in command prompt
set path= C:\Program Files\Java\jdk1.6.0_35\bin

How to set permanent path:
Go to MyComputer properties -> advanced System settings -> environment variables -> new tab of user variable -> write ‘path’ in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Step 3:Compile the *.java file using the command ‘javac file_name.java’ in command prompt
              Here *.class file will be created in the folder where you are in 

Step 4: Execute the *.java file using the command ‘java file_name’

Please find the output of myFirstProg



Monday 16 February 2015

Introduction to Java

       Java is an Object Oriented ,Platform Independent Programing Language .Object Oriented Programming (OOP) is a programming methodology based on objects ,Instead of just functions and procedures. These objects are organized into Classes which allow individual objects to be grouped together.

Object: An object is an entity that keeps together state and behaviors. An Object can be a variable, data structure or a function and it refers to the particular instance of a class.
Eg: A Dog has a states like color, name and behavior like barking,eating 

Class: A class is a blueprint or template or set of instructions to build a specific type of object. It defines the characteristics of the objects such as attributes and actions or behaviors
Eg: A Dog is a class which defines the states and behavior but no physical existence. 

Method: A method is same as a procedure, function , or routine in procedural programming languages. The only difference is that in object-oriented programming, a method is always associated with a class. 
Eg: The behavior of a Dog i.e barking will be stored in the method . and the states i.e color/name will be stored in a field.
 public class Dog{ //class 
                                String name; 
                                 int age; //Field 
                                String color; 
                                  void barking(){ } //Method 
                                   void eating(){ }
                                  }} 

Principles of Object Oriented Programming: 
There are mainly 4 OOP Principles 
            1)Encapsulation 
             2)Polymorphism 
             3) Inheritance 
             4)Abstraction 

1) Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse or in other words it is a concept of hiding data to prevent the access from outside. 
Java supports Keywords like public, private, protected to implement encapsulation.

 2) Polymorphism: Polymorphism means many forms . It is an OOP concept that refers to the ability of a variable,function or object to take on multiple forms.
Eg: If we take an example of a car , we can get many offers like power/normal steering . 4/6/8-Cylinder engines and different types of braking system on same car . Still you have to press the same break padel to stop ,turn the steering wheel to change direction. 

3) Inheritance: Inheritance is the process by which one object acquires the property of another object. 
Eg: Mammal and Reptile is a class which is under the class Animal. Mammal might have some other unique properties with all the properties acquired from the the class animal

 4) Abstraction : Abstraction is the act of representing essential features without including the background details or explanations. 
 Eg : Even though a car consists 1000 of parts people consider it as whole . They can drive the car without being overwhelmed by the complexity of the parts that form the car. 

How Java code will be executed? 
       As java is platform Independent language the source code will be converted to intermediate code called bytecode. Bytecode is the highly optimized set of instructions designed to be executed by Java runtime system i.e Java Vertual Machine (JVM). JVM uses Just-In-Time(JIT) compiler to execute the bytecode. 

JIT compiler will convert only the selected portion of bytecode to executable code in real time on a piece by piece or demand basis instead of compile an entire Java program into executable code all at once. Hence it will not effect on performance even though there is intermediate bytecode conversion. 

Reference: Java The Complete Reference  By Herbert Schild

Display rows into columns using PIVOT in oracle 11g


We can use PIVOT Keyword to display rows into columns and UNPIVOT Keyword to display column into rows to generate result in crosstab format.

PIVOT:

General Syntax :


Pivot_clause -> Which defines the columns to be aggregated
Pivot_for_clause->Which defines the columns to be grouped and pivoted
Pivot_in_clause ->Which defines the filter for the columns

Example:
Requirement: Need a query to display number of order created each day of the week and total count of the order for that week.
Expected output :


The table oe_order_headers_all consists order creation date . We have developed below query to get the output (Here we have taken the data only for the year 2014)

Query:


Output(Without PIVOT):


Output(With PIVOT):



UNPIVOT:
It is exactly opposite to PIVOT

General Syntax:


unpivot_clause: this clause specifies a name for a column to represent the unpivoted measure values.

unpivot_for_clause: the unpivot_for_clause specifies the name for the column that will result from our unpivot query.

unpivot_in_clause: this contains the list of pivoted columns to be unpivoted.

Tuesday 3 February 2015

Extract Data to a Flat File using UTL_FILE in Oracle Apps



In Oracle PL/SQL, UTL_FILE is an Oracle supplied package which is used for file operations (read and write).Let us discuss about how you  can use this package to extract data to a flat file like *.csv.

Follow the below steps


Step 1:

Find the valid directory to place the file at server.  Execute below query to get the valid directory in Oracle Apps
 SELECT VALUE
 FROM v$parameter
 WHERE NAME = 'utl_file_dir'

Step 2:

 Need to declare a variable of the type UTL_FILE.FILE_TYPE in the procedure/plsql block.
DECLARE
--Cursor to fetch the data
f_handle              UTL_FILE.FILE_TYPE;
BEGIN
--Remaining logic
UTL_FILE.FILE_TYPE will point to the file at server


Step 3:

Write the code to open the file in write mode using UTL_FILE.FOPEN
DECLARE
--Cursor to fetch the data
f_handle              UTL_FILE.FILE_TYPE;
BEGIN
--Remaining logic
 f_handle :=UTL_FILE.FOPEN('/usr/tmp',l_filename,'w',32767);
--Remaining logic

Step 4:

Open the cursor and put the data to the file using UTL_FILE.put_line

UTL_FILE.put_line (f_handle,order_data.order_number

                               ||'|'

                               ||order_data.Ordered_date

                               ||'|'

                               ||order_data.ordered_item

                               ||'|'

                               ||order_data.line_number);

Step 5:

Close the filel using UTL_FILE.FCLOSE.
UTL_FILE.FCLOSE(f_handle);

Example:

Here we have created a simple plsql block which extracts data from oe_order_headers_all and oe_order_lines_all and will write the data to *.csv file with delimiter ‘|’ 

DECLARE
  CURSOR cur_order_detail                                                                                                                                                     --Cursor to fetch records
  IS
    SELECT ooha.order_number
          ,ooha.ordered_date
          ,oola.ordered_item
          , oola.line_number || '.' || oola.shipment_number line_number
      FROM oe_order_headers_all ooha
          ,oe_order_lines_all oola
     WHERE ooha.header_id = oola.header_id;
  f_handle                      UTL_FILE.file_type;
  l_filename                    VARCHAR2 (100);
 BEGIN
  l_filename := REPLACE ('order_detail', '.', '_') || '.csv';
  f_handle := UTL_FILE.fopen ('/usr/tmp', l_filename, 'w', 32767); 
  FOR order_data IN cur_order_detail
  LOOP
    UTL_FILE.put_line (f_handle, order_data.order_number 
                                 || '|' 
                                 || order_data.ordered_date 
                                 || '|' 
                                 || order_data.ordered_item 
                                 || '|' 
                                 || order_data.line_number);
  END LOOP;
  UTL_FILE.fclose (f_handle);
EXCEPTION
  WHEN OTHERS
  THEN
--  retcode:=2;
    fnd_file.put_line (fnd_file.LOG, 'Error Occured while creating  ' || l_filename || '  ' || SQLERRM);
END;

UTL_FILE Package Exception:

Some exceptions might raise by the utl_file package . You can find below exceptions.

INVALID_PATH                 -> File location or filename was invalid. 

INVALID_MODE               ->The open_mode parameter in FOPEN was invalid. 

INVALID_FILEHANDLE    ->File handle was invalid. 

INVALID_OPERATION    ->File could not be opened or operated on as requested. 

READ_ERROR                  ->Operating system error occurred during the read operation. 

WRITE_ERROR               ->Operating system error occurred during the write operation. 

INTERNAL_ERROR         ->Unspecified PL/SQL error.