Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Sunday 29 January 2017

Polymorphism in java

 Polymorphism

Polymorphism In Java

Polymorphism is derived from 2 greek words 'poly' and 'morphs'. The word poly means many and morphs mean behavior or form.

                                          Poly + Morphs   
                                             ↓               ↓              

                                          many    behavior or form = many behavior

Polymorphism in java is an oops concept, Whenever an object producing different-different behavior in different-different circumstances is called polymorphism in java.

Polymorphism is always achieved via behavior(member function) of an object. Properties(data member) of an object do not play any role in case of polymorphism. Polymorphism can be defined in other words "one name many forms".


Examples of polymorphism related to real life

(1) Related to person
  • Suppose you are in a classroom that time you behave like a student.
  • When you at your home at that time you behave like a son or daughter or brother.
  • When you are in a market, you behave like a customer.

(2) Related to product
  • Suppose Air Conditioner producing hot air in winter and cold air in summer.
So there is one name but producing different -different behavior in different circumstances.


Types of polymorphism in java, these are

  • Compile time or static polymorphism
  • Run time or dynamic polymorphism


Compile-time polymorphism

Method overloading (function overloading) and operator overloading both are compile time polymorphism. Method overloading(function overloading) or static binding(early binding ) is also known as compile time polymorphism in java.

"Whenever an object is bound with their functionality at compile time, this known as compile time polymorphism".


👉: Java does not support compile-time or static polymorphism. Java supports only dynamic polymorphism or run-time polymorphism.



Runtime polymorphism

Method overriding (function overriding) or Dynamic Binding(late binding) is known as runtime polymorphism in java. In java polymorphism principal is implemented with method overriding concept.

"Whenever an object is bound with their functionality at run-time, this known as run time polymorphism".


👉: Without inheritance concept method overriding is not possible in java So we will learn method overriding or dynamic binding after inheritance concept of oops.



Difference between Compile Time and Run Time Polymorphism  in Java

Compile-Time Polymorphism
  • In Compile Time polymorphism, call is resolved by the compiler.
  • Compile-Time polymorphism is also known as static binding, early binding, and overloading as well.
  • Overloading is compile time polymorphism, where more than one methods share the same name with different parameter or arguments.
  • Compile Time polymorphism is achieved by function overloading or method overloading and operator overloading.
  • It provides fast execution because known early at compile time.
  • Compile time polymorphism is less flexible as all thing executes at compile time.
Run-Time Polymorphism
  • In Run-Time polymorphism, call is not resolved by the compiler.
  • Run-Time polymorphism is also known as dynamic binding, late binding, and overriding as well.
  • Overriding is runtime polymorphism having the same method with same parameters or arguments but associated in a class and its subclass.
  • It is achieved by method overriding.
  • It provides slow execution as compared to early binding because it is known as run time.
  • Runtime polymorphism is more flexible because all thing executes at runtime.

Read More:


Share:

Saturday 21 January 2017

Constructor in Java

 

Constructor

Constructor in java is a special type of method or member function of a class which is used to initialize the objects, object initialization means putting the values into data member. Constructor are required to create an objects for a class and Java constructor is invoked at the time of object creation.

When the object is created , constructor executes first. Any code you have in your constructor will then get executed. You don't need to make any special calls to a constructor , they happens automatically when you create new object.


Rules for creating constructor in java 

  • Constructor name must be same as it class name
  • Constructor must have no explicit return type


Types of java constructor

  • Default constructor (non-arg constructor)
  • Parameterized constructor 
Constructor in Java


Default Constructor in Java

Default constructor is a constructor that have no arguments or parameters.


Example of Default Constructor in Java

class Students
{
Students()//creating default constructor
{
System.out.println("default constructor is running");
}
public static void main(String args[])
{
Students d = new Students();//creating object with new keyword
}
}

output will be : default constructor is running


👉If we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class.


For example:


                                                                                             

class Students                                                                  class Students 
{                                                                      →                        
public static void main(String args[])      compiler               Students()
{                                                                                                    {
Students s = new Students();                                                     
 }                                                                                                       }
}                                                                                 p s v m(String args[])
                                                                                                   
                                                                                                               }}


What is the use of default constructor?

Default constructor provide the default values to the objects like 0 and null. Depending on the data types.

Default constructor example that provides default values 

class Student
{
int rollno;
String name;
void display()
{
System.out.println(rollno);
System.out.println(name);
}
public static void main(String...s)
{
Student ss = new Student();//creating object of Student class
ss.void();//calling method
}
}

output: 0

              null

Here in the above class we are not creating any constructor so compiler provides you default constructor. 0 and null provided by default constructor.



Parameterized Constructor in Java

A constructor that have parameters is known as parameterized constructor.


Why use parameterized constructor in java?

Parameterized constructor is used to provide different values to the different objects.

Example of parameterized constructor

In this example, we have created constructor of Employees class that have two parameters. We have any number of parameters in the constructor.

class Employees
{
int id;
String name;
Employees(int i, String n)// two parameter
{
id = i;
name = n;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employees e = new Employees(1,"prem");
Employees ee = new Employees(2,"ram");
e.show();
ee.show();
}
}

output: 1 prem
              2 ram 


Another example of parameterized constructor


class Employees
{
int id;
int age;
Employees(int i, int a)
{
System.out.println(" i am parameterized constructor");
id = i;
age = a;
System.out.println("id is : " +id);
System.out.println(" age is : " +age);
}
public static void main(String args[])
{
Employees e1 = new Employees(100,26);
}
}

output: i am parameterized constructor
              id is : 100
              age is : 26


Some point related to parameterized constructor

  1. Whenever we create an object using parameterized constructor, it must be defined parameterized constructor otherwise we will compile time error.
  2. Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructor.
  3. You can keep maximum one default constructor and 'n' number of parameterized constructor in class.
Share:

Sunday 15 January 2017

Java Naming Conventions

 

What is a Naming Convention in Java?

A naming convention in java is a rule to follow as you decide what to name your identifiers (e.g class, variable, method, package, constant, etc...).


Java Naming Conventions


Why use Naming Conventions in Java?

By using standard java naming conventions they make their code easier to read for themselves and for other programmers . They can also give the information about the function of the identifiers for example, whether it is a constant, class , variable, package, interface, etc. Readability of java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix and modifying it.


Let's take an examples


(1) Class Name Identifier

class name should be a noun and start with uppercase letter and in mixed case with the first letter of each internal world capitalized. Try to keep your class name simple and descriptive .
Use whole words, avoid acronyms and abbreviations(unless the abbreviation  is much more widely used than the long form such as URL and HTML).

For example:

class Customer;
class Car;
class HelloWorld;

(2) Variable Name Identifiers

Variable name should start with lowercase letter. Names should be in mixed case. The names should represent  what the value of the variable represents. Internal world start with capital letter.

For example:

int i;
char c;
int orderNumber;
String firstName;

(3) Package Name Identifiers

Package name should be in lowercase letter. With small projects that have a few packages it's okay to just give them simple but meaningful name.

For example:

package java;
package mycalculator;
package util;


(4) Constant Name Identifiers 

The names of a variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores("_"). e.g MAX_PRIORITY.

For example:

static final int MAX_HIEGHT;
static final int MAX_PRIORITY;

CamelCase in Java Naming Conventions

java  follows camelcase syntax for naming the classes, interfaces, methods and variables.when name is combined two words, second word start with uppercase letter e.g ActionEvent, firstName, fisrtRun(), etc.


Identifiers in java

While defining identifiers we must follow some rules, else its lead to compile time error.
  • Identifiers is the name of the basic programming elements.
  • Class name, variables name, method name, object name are identifiers.

Rules of Identifiers

(1) identifier should only contain
  • Digits(0-9)
  • Alphabets(a-z or A-Z)
  • Special characters(_ and $)

(2) identifiers should not start with a digits
  • A digits can be used from second character onwards.
For example:

2Student is wrong : throw error

Student2 is right : run fine

Student200 is right : run fine


(3) identifiers should not contains special character except '_' and '$'

For example:

_Student  is right : run fine
$Student is right : run fine
Student_John is right : run fine
#Student is wrong : error
*Student is wrong : error
Student*john is wrong : error


(4) identifiers is case sensitive
  • Identifiers is case sensitive e.g There is difference between 'a' and 'A'.

(5) identifiers cannot be used as keyword name

For example:

There is 'int' cannot be  used as variable name.
There is 'extend' cannot be use as method name or variable name.

Share:

Friday 13 January 2017

OOPS

 OOPS (Object Oriented Programming System)

Object-Oriented Programming is a programming concept or paradigm used in several modern programming languages like C++, java, etc. The object-oriented programming language directly represents real-life objects like car, bus, table, fan, laptop, customer, account, etc. Before object-oriented programming programs were viewed as procedures that accepted data and produced output.

Object-oriented programming is used to design program using classes and objects. It simplifies the software development and maintenance.

Simula is the first object-oriented programming language.

Truly object-oriented programming: A language in which everything is represented in the form of objects that is known as the truly object-oriented programming language. 

👉: In java, everything is represented in the form of object except primitive data types.


Concepts of OOPS

OOPS provides some concepts, these are 
  1. Object
  2. class
  3. Polymorphism
  4. Inheritance
  5. Encapsulation
  6. Abstraction 

Object

An object is something which has its own identity and can be easily compared to real-world objects like chair, laptop, bed, pen, bike, pencil, all these are objects. Object means real-world entity. An object contains state and behaviors. An object can be physical and logical (tangible and intangible) e.g tangible objects - pen, table, pencil and intangible object - banking system. But the class can be logical entity only.


oops



An Object in java has 3 characteristics   

  • State: states represent state(data) of an object.
  • Behavior: represents the behavior(functionality) of an object.
  • Identity: object identity is typically implemented via unique ID. The value of the ID is not visible to the external users, but it is used internally by the JVM to identify each object uniquely.

For example: 

A dog has states - name, color, height etc.

and behaviors is - wagging the tail, eating, barking, running etc.

An object is an instance of a class because objects are created from a class.

The state of an object is the properties of the object at the particular time and behavior is the function, It will perform. The behavior of an object is usually described using methods and these methods will be part of the object itself.


Class

Objects are grouped into a class. A class can be defined as a group of objects that have common properties. A class can be considered as the blueprint or template of definition for an object. A class describes the properties and behaviors of that objects.

A class in java can contain:

  • data member or field
  • member function or method
  • constructor
  • nested class
  • interface
  • block
Syntax to declare a class

class  Class_Name
{
data member;
method;
}


Instance Variable in Java

An instance variables is a variable which is created inside a class but outside the method is known as the instance variable. Instance variable get memory at runtime when an object(instance) is created. That why, it is known as the instance variable.

Method in java

A method in java is like a function, which is used to expose the behavior of an object.

For example:

class MethodDeclareExample
{
void run()
{

}
}

  • Here 'void' is return type, Which does not return any value.
  • run() is method name.


new Keyword in Java 

  • A new keyword is used to allocate memory at runtime.
  • A new keyword is used to create an object of a class.
For example;

Suppose there is Student class

Student s = new Student();

A class with data member(instance variable) and method(member function) and creating an object by new keyword. Let 's take an example


class Employees
{
int a;//data member(or instance variable)
double d;//data member(or instance variable)
public static void main(String []args)
{
Employees e = new Employees();//creating object by new keyword
System.out.println(e.a);
System.out.println(e.d);
}
}

output: 0

             0.0d


printing default values or object values.


We will learn in details next chapters constructor, interface, block, nested class.
Share:

Saturday 7 January 2017

Break, Switch, Continue keword

 

Break Keyword 

Break,Switch,Continue Keyword

Break keyword in java programming is used to come out of the loop control statement. The break keyword is used to stops execution of for loop, while loop, and switch-case statement. It breaks the current flow of the program at specified condition. In case of inner loop , it breaks only inner loop.

Syntax:

break;

The following example shows break statement inside a for loop

class BreakStatement1
{
public static void main(String args[])
{
for(int i = 1; i<=10; i++)
{
if(i == 5)
{
break;
}
System.out.println(i);
}
}
}

output: 1

              2
              3
              4

The following example shows break statement inside a Inner loop

class BreakStatement2
{
public static void main(String args[])
{
for(int i = 1; i<=3; i++)
{
for(int j= 1; j<=3; j++)
{
if(i == 2 && j == 2)
{
break;
}
System.out.println(i+""+j);
}
}
}
}

output: 1
1
              12
              13
              21
              32
              33

The following example shows break statement inside a while loop

class BreakStatement3
{
public static void main(String args[])
{
int number = 0;
while(true)
{
number++;
System.out.println(number);
if(number >= 10)
{
break;
}
}
}

output: It will print 1 to 10 numbers.


Before using break keyword in switch statement , we learn what is switch statement in java.


Switch Statement with Java

The java switch statement executes one statement from multiple condition. A switch statement work with byte, short, int , char primitive data types and it is also work with String and enumerated types.

Syntax:

switch(expression)
{
case value1:
//Statements;
break; //optional

case value2:
//Statements;
break; //optional

case value3:
//Statements;
break; //optional

default:
//Statement will execute if all cases are not matched.
}


There are some rules to work with Switch Statement

  • Variables use in switch statement can only be int, byte, char, short, String, enums.
  • You can use any number of case statements within switch but values for a case must be same as the variable in switch.

Flow of switch statement

  • Expression values is compared with each case value. If it is matches , statements following case would be executed.
  • Break statement is used to terminate the execution of statement.
  • If none of these case matches, statement following default would be executed.
  • If break statement is not used within case, all cases following matching cases would be executed.

For example:

class BreakWithSwitch
{
public static void main(String args[])
{
int i = 100;
switch(i)
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 100:
System.out.println("100");
break;
default:
System.out.println("100 number are not matched with cases");
}
}
}

output: 100


Continue Keyword

Continue statement is used to skip a particular iteration or specified condition of the loop.

Syntax:

continue;

For example:

class ContinueExample
{
public static void main(String []args)
{
for(int i = 1; i<=10; i++)
{
if(i == 5)//5 will not print
{
continue;
}
System.out.println(i);
}
}
}

output:1
             2
             3
             4
             6
             7
             8
             9
            10

There are all number except 5.

If you want make your logic strong then you will have to good practice of break, switch and continue keyword because these keyword are mostly used.

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate