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

Friday, 10 February 2017

Static Keyword In Java

 

Static Keyword

Static keyword in java is a non-access modifier. The static keyword makes your program memory efficient. Static keyword is used in java mainly for memory management. Static keyword is used to save memory in java. Static means class level. The static keyword belong to the class than instance of the class.

Static keyword can be apply to variable, method, nested class, block. There is no need to create an object to use to static variable and call static method. Just put the class name before the static variable or static method to use them. 


static keyword in java



Static keyword can be apply to

  • Variables
  • Methods
  • Nested class(A class within another class is called nested class)
  • Block


Static keyword cannot be applied to 


(1) Static Variable

  • If you declare any variable as static, it is known as static variable.
  • The static variable can be used to refer the common property of all objects(that is not unique for each objects) e.g collage name of students, company name of employees etc.
  • The static variables gets memory only once in class area at the class loading time.

Syntax to declare static variable:

static int a =10;
public static String collage = "IIT";


Let's understand the problem without static variable

class Employees
{
int emp_id ;
int emp_name ;
String emp_companyname="google";
};

suppose there are 100 employees in the company, now all instance data members gets memory each time when object is created. All employees have it s unique id and name so here instance data member is good but here company name refer to the common property of all objects. If we make it static, this field will get memory only once.

👉: When we want to share common property to each objects than we use static variables.

  

Example of Static Variable

class Employees
{
int id;
String name;
static String company = "Google";

Employees(int i, String n)
{
id = i;
name = n;
}

void record()
{
System.out.println(id);
System.out.println(name);
System.out.println(company);
                 OR
System.out.println(id+" "+name +" " +company);
}

public static void main(String args[])
{
Employees e = new Employees(1,"ranvir");
Employees e1 = new Employees(2,"amar");
e.record();
e1.record();
}
}

output:  1 ranvir google
               2 amar google


(2) Static Method

  • If you apply static keyword with any method, it is known as static method.
  • Static method belongs to the class rather than object of a class.
  • Static method can be called without creating an object(instance) of class.
  • Static methods can access static data member and It can change the value of static data member.
  • Any static method can call any other static method in same file.
  • You can define many static method. These methods are independent, except that they may refer to each other through calls.




Example of Static Method

Here in this program , we will change the value of static data member through static method and call the static method without creating any object.

class Students
{
int rollno;
String name;
static String college = "IIM";

static void change() 
{
college = "MII";
System.out.prinltn("this is static method");
}

Students(int r, String n)
{
rollno = r;
name = n;
}

void record()
{
System.out.println(rollno+""+name+""college);
}

public static void main(String args[])
{
Students.change();//calling static method through the class name

Students s = new Students(10,"bheem");
Students s1 = new Students(11,"karan");
s.record();
s1.record();
}
}

output: this is static method
             10 bheem MII
             11 karan MII


Restriction for Static method

  • The static method cannot access non-static data member and call non-static method directly.
  • this and super keyword cannot use in static context.

For example:

class Demo
{
int a = 10;//non-static data member
static void show()//can't access non-static data member 
{
System.out.println(a)
}
public static void main(String args[])
{
System.out.println("This is main method");
}
}

output: compile time error

Static Block In java

  • Static block is a set of statements and static block will be executed by the JVM before the main method at the time of class loading.
  • We can use static block to assign or initialize static data member.
  • We can define many static blocks in a class but all these blocks will be executed from top to bottom.

Syntax:

static
{
//Statements;
}

For example:

class StaticBlock
{
static
{
System.out.println("This is static block");
}
public static void main(String args[])
{
System.out.println("this is main method");
}
}

output: This is static block
              this is main method


Multiple static block example


class MultipleStaticBlock
{

static

{

System.out.println("This is static block 1");

}
static
{
System.out.println("This is static block 2");
}

public static void main(String args[])

{

System.out.println("this is main method");

}

}

output: This is static block 1
             This is static block 2
             this is main method

Share:

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:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate