B.Sc. CSIT 7th Semester Advanced Java Programming

Fundamental Programming Structure in JAVA.

Arrays

An array is a collection of similar elements with the same data type. It’s used to keep multiple values in a single variable.

Java array is an object that contains the elements of similar data types. In Java, arrays are indexed. In the array, the index starts at 0. The first element is indexed as 0, the last element as n-1, and so on.

Arrays are classified into two types:

  • Single dimensional Array
  • Multidimensional Array

Single Dimensional Array

Syntax to declare an array/Single dimensional array:

Datatype []array_name;

Datatype array_name [];

Instantiation of an Array in Java

variable=new datatype[size];

We can also declare the, instantiate and initialize the java array together by:

Int a[]={1,2,3,4,5};

Example of single dimensional array

programming structure in java

Output:

programming structure in java

Multidimensional array

In multidimensional array,data is stored in matrix form i.e. row and column form

 Syntax to declare multidimensional array

datatype [] [] array_name;

datatype array_name [][];

datatype [] array_name[];

Example:

programming structure in java
Source code: Multi dimensional Array

Output:

programming structure in java

For each loop

  •   For each loop  traverse the array  in Java.
  • It traverse each element one by one.
  • It makes the code readable and eliminates the bugs.
  •  For each loop is declare with  for keyword.
  •   It does not work in index basis and cannot traverse  the element in reverse order.  
  • Instead of declaring and initializing a loop counter variable, you declare a variable of the same type as the array’s base type, followed by a colon, and then the array name.         
  • Instead of using an indexed array element in the loop body, you can use the loop variable you created.

Syntax:

For(data-type variable:array)

{

//body  of for-each loop

}

Example:

programming structure in java

Output:

programming structure in java

Classes and objects

Class is a blueprint of real world objects that specifies what data and what methods will be included in objects of the class. The class is a description group of objects  having similar properties.A class is also called user defined data type or programmers defines data type because we can define new data types according to our needs by using classes.

Syntax:

class <class_name>

{  

     field;  

     method;  

}  

Objects are instances of classes. We can say that objects are variables of class type.Memory for instance variables are not allocated at the time of class declaration rather at the time of object creation.Thus we can say that objects have physical existence and classes are only concepts.

Creating objects

It can be done using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it.  This reference is, more or less, the address in memory of the object allocated by new.  This reference is then stored in the variable.  Thus, in Java, all class objects must be dynamically allocated.

Box mybox = new Box();

Example:

programming structure in java
Source code: Classes and object

Output:

programming structure in java

Access Modifiers

Access Modifiers in java specifies  the visibility  and accessibility of class,methods and member variables.  It also set  access levels for classes,variables, methods and constructors. There are two type of access modifiers .They  are:

  • Access Modifiers :It controls the access levels.
  • Non Access Modifiers:It does not control the access level but provide other functionality.

There are four access levels .They are:

Default Access Modifier: 

In default access modifier ,no keyword is used to define an access modifier for a class,field,method etc.The access level  of default access modifier is in all the class of same package i.e only within the package  but  not outside of the package.If no access  level is specified then,it will be the default.

Private Access Modifier:

The declared private methods, classes, constructors, and variables are only accessible within the declared class. It is not available outside of class. Variables declared private can be accessed outside the class if the class contains public methods. Using private access modifier is the main way that an object encapsulates itself and hides data from the outside world.

Protected Access Modifier:

Variables,methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package  of the protected class members class It cannot be accessed from outside the package if a child class is not created. The protected access modifier is inapplicable to classes and interfaces.

Public Access Modifier:

A class,variable,methods ,constructor ,interface which are declared public can be accessed  from everywhere i.e any other class.It can be accessed within the class and package and ,outside the class and package.

Example:

ACCESS..java file:

public class ACCESS {

   private int a;//private access modifiers

   int b;//default access modifiers

   protected int c;//protected access modifiers

   public int d;//public access modifiers

}

Access-modifier.java file:

public class Access_modifier {

    public static void main(String args[]) {

        ACCESS obj=new ACCESS();

        obj.a=5;//generates compiler error as a is private .

        obj.b=10;

        obj.c=12;

        obj.d=15;

    }

}

Final Modifier

The final modifier in  java can be used with  classes,method and member variables. It is used to restrict the user .The final keyword can be used with variables; a final variable with no value is referred to as a blank final variable or an uninitialized final variable. It can only be initialized in the constructor. The final modifier is used for following purposes:

To define constants

It is used with  variable to declare  them as a constant.once the value is assigned to final variable,it cannot be changed during the runtime.

Example:

public class Circle{

    private final float pi=3.14;

    private int r;

    Circle(int x)

    {

        Pi=3.1;//cannot be changed cause Pi is defined as final.

        r=x;

    }

    Void area(){

        float a=pi*r*r;

        System.out.println(“area”,a);

    }

}

To prevent Overridiing:

Final access modifier can prevent a method being overridden from subclass by declaring them as a final.

Example:

class Dog{

  final void eat(){

System.out.println(“Eating”);}

}

class Animal extends Dog{

   void eat()

    {

System.out.println(“eating meat”);

     }

   public static void main(String args[]){

  Animal obj= new Animal();

   obj.eat();

   }

To prevent Inheritance

Final access modifier can be use with class declaration to prevent it from further inheritance since final class cannot be further inherited.

Example

Final class A

{

//code;

}

Class B extends A // throws error

{

//code ;

Method Overloading

Method overloading is a Java feature that allows you to define different methods with the same name either with different number of parameters or a different type of parameter. Polymorphism is supported by Java through method overloading. Method overloading helps to increase the readability  of the program. In method overloading the return type of the method does not matter.

The two way to overload the method in java are:

  • By  changing the number of parameters.
  • By Changing the type of parameter.

Example:

public class method_overloading

 {

   static int sum(int a, int b)

   {

       return a+b;

   }

  static int sum(int a, int b,int c)//changing the number of parameter

  {

      return a+b+c;

  }

  static float sub(float x, float y)

  {

      return x-y;     

  }

  static double sub(double x,double y)//changing the type of parameter

  {

      return x-y;

  } 

    public static void main(String args[]) {

        System.out.println(sum(4,5));

        System.out.println(sum(7,10,11));

        System.out.println(sub(10.4f,2.5));

        System.out.println(sub(8.9,4.5));

    }   

}

Output:

programming structure in java

Method Overriding 

The process of redefining the inherited method of the super class in the derived class is called method overriding.In other word if the subclass has the same method as declared in the parent class then it is called method overriding.The overridden method in the subclass  must have same access modifier as the super class.It is used to provide the runtime polymorphism.The overridden method must have same name,and parameter as in the parent class.

Example:

class Plant{

  void color(){

System.out.println(“It is green color”);}

  }

  class Flower extends Plant{

  void  color(){

System.out.println(“It is yellow color flower”);}

  public static void main(String args[]){

  Flower obj = new Flower();

  obj.color();

  }

}

Output:

programming structure in java

Difference between Method overloading and method overriding

Method OverloadingMethod Overriding
It refers to having the same method but different signatures.It refers to having same method ,same signature but different class connected through inheritance.
It is used to increase readability of program.It is used to provide specific implementation of method.
Parameter must be different.Parameter must  be same
It is example of compile time polymorphism.It is example of runtime polymorphism.
It is  performed within class.It occurs in two classes that have IS-A relationship.

Inner class

Java inner class or nested class is a class that is declared inside the class or interface.Inner  classes represent a particular type of relationship that  can access all the members of the outer class, including private.The purpose of inner  classes is to group classes that belong together,which makes your code more readable and maintainable.

Syntax :

 class Java_Outer_class{  

 //code  

 class Java_Inner_class{  

  //code  

 }  

}  

Example:

programming structure in java
Source code: Inner class

Output:

programming structure in java

Packages

Packages are containers for classes that are used to keep the class name space 

compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.  The package is both a naming and a visibility control mechanism.It is used in order to prevent naming conflicts,to control access, to make searching/locating and usage of classes,interface,enumerations and annotations easier. Some of the existing packages in Java are:

  • java.lang
  • java.io

Using Package

There are two ways of accessing classes in another package.

One way is to add the full package name in front of every class name.

Example:

jav.util.Date today=new java.util.Date()

Another is using the import keyword to import a specific class or whole package.The import statement will be given at the top of the file just below the package statement. 

Example:

Import  java.util.*;

Date today= new Date();

Creating a Package

When creating a package ,you should chose a name food the package and put  a package statement with that name at the top of every source file that contains the classes,interfaces,enumerations,and annotations types that you want to include in the package.the package statement should be in the first line of the source file.

Example:

programming structure in java
Source code: packages

Output:

programming structure in java

Inheritance

Inheritance is  a mechanism in which one class inherits the properties and features  of another class.Inheritance represents IS-A relationship.In inheritance, a new class is created based on existing classes in order to inherit the existing classes’ features and properties. In the new class, new methods and fields can be added.with the use of inheritance the information is made manageable in a hierarchical order. A class that is derived from another class is Subclass.The class from where a subclass inherits the features is called superclass/base class/parent class.

Inheritance uses the concept of the code resuability.It allows to use the field and method of the existing class in the new class. Reusing the existing code saves time and money and increases the program’s reliability.

Syntax:

class Subclass-name extends Superclass-name  

{  

   //methods and fields  

}  

The extends keyword is used to inherit the properties of class.The meaning of “extends” is to increase the functionality.

Types of inheritance

There are four type of inheritance.They are:

  • Single inheritance
  • Multiple Inheritance 
  • Hierarchical inheritance
  • Multilevel inheritance

Single inheritance:

In single inheritance, a class is derived from only one existing class.

programming structure in java

Example:

programming structure in java
Source code: single inheritance

Output:

programming structure in java

Multiple inheritance

A class derives from more than one existing classes.Java does not support

The multiple inheritance.Multiple inheritance can be implemented by interface. programming structure in java

Hierarchical Inheritance

In hierarchical inheritance,two or more classes inherit the properties of one existing class.

programming structure in java

Example:

programming structure in java
Source Code: Hierarchical inheritance

Output:

programming structure in java

Multilevel Inheritance:

The mechanism of deriving a class from another subclass is known as multilevel inheritance.The process can be extended to an arbitrary number of levels.

programming structure in java

Example:

programming structure in java
Source code: Multilevel Inheritance

Output:

programming structure in java

Interface

Interfaces are syntactically similar to classes, but they lack instance variables, and 

their methods are declared without any body.In practice, this means that you can define interfaces which don’t make assumptions about how they are implemented.  Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces. 

To use an interface,we must write a class that implements the interface.When an instantiable class implements an interface,it should either provide method body for each of the methods declared in the interface or the class should be declared abstract.

Defining an interface

[access] interface InterfaceName[extends Iname1,Iname2]

{

Constant declarations;

Method declarations;

}

Example

programming structure in java
Source code:Interface

Output:

programming structure in java

Also Read:Exception Handling and creating exception in Java

About Author

Sarina Sindurakar