Friday, August 11, 2017

Final keyword


It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance.

final keyword can be used in following way.

  1. Final at variable level
  2. Final at method level
  3. Final at class level



Final at variable level

Final keyword is used to make a variable as a constant.

A variable declared with the final keyword cannot be modified by the program after initialization.


Example

public class Circle

{

public static final double PI=3.14159;

public static void main(String[] args)

{

System.out.println(PI);

}
}



Final at method level

It makes a method final, meaning that sub classes cannot override this method.


Example

class Employee

{

 final void disp()

{ System.out.println("Hello Good Morning");

 }
}

class Developer extends Employee

{

void disp()

{

System.out.println("How are you ?");

} }

class FinalDemo

 {

 public static void main(String args[])

{

Developer obj=new Developer();

obj.disp();

}
}


Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes.

example

final class Employee

 {

 int  salary=10000;

 }

class Developer extends Employee

{ void show()

 {

 System.out.println("Hello Good Morning");

} }

 class FinalDemo

{

 public static void main(String args[])

 {

Developer obj=new Developer();

 obj.show();

}
}

Recursion



The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion.

Syntax:

returntype methodname()

{  

//code to be executed  

methodname();//calling same method  

}  

Example

public class RecursionExample
{
   int factorial(int n)
 {
  if(n==1)
   return 1;
  else
 return(n * factorial(n-1));
}
public static void main(String[] args)
{
RecursionExample ob=new RecursionExample();
 System.out.println("Factorial of 5 is:"+ob.factorial(5));
}
}

Argument Passing


There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Example
Object as Argument
class CallByValue1
{
int data=50;
void change(CallByValue1 op)
{
op.data=op.data+100;//changes will be in the instance variable 
}
public static void main(String args[])
{
 CallByValue1 op=new CallByValue1();
 System.out.println("before change "+op.data);
 op.change(op);//passing object
 System.out.println("after change "+op.data);
 }
}

Example

Value As an Argument

class CallbyValue
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
//System.out.println("local change change"+data);
}
public static void main(String args[])
{
CallbyValue op =new CallbyValue();
System.out.println("before change"+op.data);
op.change(500);
System.out.println("after change"+op.data);
}
}

Method Overloading


If two or more method in a class has same name but different parameters, it is known as method overloading.

Method overloading can be done by changing number of arguments or by changing the data type of arguments.

If two or more method have same name and same parameter list but differs in return type are not said to be overloaded method.



Different ways to overload the method

  1. By changing number of arguments or parameters.
  2. By changing the data type.
  3. Sequence of Data type of parameters.

When an overloaded method is called the compiler looks for exact match.

Sometime when exact match is not found, java automatic type conversion plays a vital role

Example for By changing number of arguments or parameters.
class ChangeArgumentList
{
 void find(int l, int b)
 {
  System.out.println("Area is"+(l*b)) ;
 }
 void find(int l, int b,int h)
 {
  System.out.println("Area is"+(l*b*h));
 }
 public static void main (String[] args)
 {
  ChangeArgumentList  ar = new ChangeArgumentList();
  ar.find(8,5);     //find(int l, int b) is method is called.
  ar.find(4,6,2);    //find(int l, int b,int h) is called.
 }
}


Example for By changing the data type.
class ChangeDataType
{
 void sum (int a, int b)
 {
  System.out.println("sum is"+(a+b)) ;
 }
 void sum (float a, float b)
 {
  System.out.println("sum is"+(a+b));
 }
 public static void main (String[] args)
 {
  ChangeDataType  cal = new ChangeDataType();
  cal.sum (8,5);      //sum(int a, int b) is method is called.
  cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
 }
}

Example for Sequence of Data type of parameters.

class SequnceOfDatatye
{
   public void disp(char c, int num)
   {
       System.out.println("I’m the first definition of method disp");
   }
   public void disp(int num, char c)
   {
       System.out.println("I’m the second definition of method disp" );
   }
}
class Sample3
{
   public static void main(String args[])
   {
       SequnceOfDatatye obj = new SequnceOfDatatye();
       obj.disp('x', 51 );
       obj.disp(52, 'y');
   }
}



Constructor Overloading



Whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known as Constructor overloading.

The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Constructor overloading can be used to initialize same or different objects with different values.

Example
 // Constructor Overloading
class Box
{
 double width, height, depth;
 // constructor used when all dimensions
 // specified
 Box(double w, double h, double d)
 {
  width = w;
  height = h;
  depth = d;
 }
 // constructor used when no dimensions
 // specified
 Box()
 {
  width = height = depth = 0;
 }
 // constructor used when cube is created
 Box(double len)
 {
  width = height = depth = len;
 }
 // compute and return volume
 double volume()
 {
  return width * height * depth;
 }
}
// Driver code
public class Test
{
 public static void main(String args[])
 {
  // create boxes using the various
  // constructors
  Box mybox1 = new Box(10, 20, 15);
  Box mybox2 = new Box();
  Box mycube = new Box(7);
  double vol;
  // get volume of first box
  vol = mybox1.volume();
  System.out.println(" Volume of mybox1 is " + vol);
  // get volume of second box
  vol = mybox2.volume();
  System.out.println(" Volume of mybox2 is " + vol);
  // get volume of cube
  vol = mycube.volume();
  System.out.println(" Volume of mycube is " + vol);
 }
}

Garbage Collection


Garbage Collection is process of reclaiming the runtime unused memory automatically.

In other words, it is a way to destroy the unused objects.

Advantages of Garbage Collection

  1. Programmer doesn't need to worry about dereferencing an object.
  2. It is done automatically by JVM.
  3. Increases memory efficiency and decreases the chances for memory leak.



How can an object be unreferenced

There are many ways:

  1. By nulling the reference
  2. By assigning a reference to another
  3. By anonymous object

By nulling a reference

Employee e=new Employee();  

e=null; 

By assigning a reference to another

Employee e1=new Employee();  

Employee e2=new Employee();  

e1=e2;//now the first object referred by e1 is available for garbage collection  

By anonymous object

new Employee();  





finalize() method


The finalize() method is invoked each time before the object is garbage collected.

This method can be used to perform cleanup processing.

 protected void finalize()

{

 

Important Points to Remember

  1. finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
  2. finalize() method is declare as proctected inside Object class.
  3. finalize() method gets called only once by a Daemon thread named GC (Garbage Collector)thread



gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing.

 The gc() is found in System and Runtime classes.

Syntax

public static void gc(){} 



example

Constructors


Constructor is a special type of method that is used to initialize the state of object.

It provides the values to the data members at the time of object creation that is why it is known as constructor.

Characteristics of constructor

1. A constructor must have the same name as of its class.

2. It is invoked at the time of object creation and used to initialize the state of an object.

3. It does not have an explicit return type.



Types of constructor

1. Default or no-argument constructor.

2. Parameterized constructor.

Default or no-argument constructor

A constructor with no parameter is known as default or no-argument constructor.

If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation.

Syntax

Class_name()

{
//optional block of code

}



Parameterized constructor

A constructor with one or more arguments is known as parameterized constructor.

Parameterized constructor is used to provide values to the object properties.

By use of parameterized constructor different objects can be initialize with different states.

 Syntax

class ClassName

{ .......

ClassName(list of parameters) //parameterized constructor

{ .......

 }

....... }



Important points Related to Parameterized Constructor

      Whenever we create an object using parameterized constructor, it must be define parameterized constructor otherwise we will get compile time error.

      Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructors.

      In any class maximum one default constructor but 'n' number of parameterized constructors.
Difference between Method and Constructor

Methods


A method is a collection of statements that are grouped together to perform an operation.

Method describes the behavior of an object

Creating Method

Syntax

modifier returnType nameOfMethod (Parameter List) {

// method body

}



Parameter Vs. Argument



Parameter is variable defined by a method that receives value when the method is called.

Parameter are always local to the method they dont have scope outside the method.

argument is a value that is passed to a method when it is called.



Example

Introducing Classes and Object


Class

Class is a blue print which is containing only list of variables and method and no memory is allocated for them. A class is a group of objects that has common properties.

A class contains

      Data Member

      Method

      Constructor

      Block

      Class and Interface



Object

 Object is an instance of class.

An Object has three characteristics

      State

      Behavior

      Identity

State: Represents data of an object.

Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.

Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.


Difference between Class and Object
















Syntax to declare a Class

class Class_Name

{

data member;

 method;

}

Syntax to create an Object

Class_name ObjectName=new Class_name();



Example

class Employee

{

 int eid; // data member (or instance variable)

 String ename; // data member (or instance variable)

eid=101;

ename=“ram";

public static void main(String args[])

{

Employee e=new Employee(); // Creating an object of class Employee

System.out.println("Employee ID: "+e.eid);

System.out.println("Name: "+e.ename);
 }
}


Basic IO


Java I/O (Input and Output) is used to process the input and produce the output.

It uses the concept of streams to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

Stream

A stream is a sequence of data. In Java a stream is composed of bytes.

In java,3 streams are created for us automatically. All these streams are attached with console.



1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream



Let's see the code to print output and error message to the console.

System.out.println("simple message");  

System.err.println("error message");  



Let's see the code to get input from console.



int i=System.in.read();//returns ASCII code of 1st character  

System.out.println((char)i);//will print the character  


Output Stream vs Input Stream



OutputStream

Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket.

Reading Console Input



In Java, there are 3 ways to read input from a console.

  1. BufferedReader + InputStreamReader (Classic)
  2. Scanner (JDK 1.5)
  3. System.console (JDK 1.6)





1. BufferedReader + InputStreamReader

InputStreamReader  that can read data from the keyboard.



Syntax

InputSteamReader obj = new InputStreamReader (System.in);



Connect InputStreamReader to BufferReader, which is another input type of stream to read data properly.

Syntax

BufferedReader br = new BufferedReader (obj);

two steps can be combined and rewritten in a single statement

Syntax

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
 

Now, we can read the data coming from the keyboard using read () and readLine () methods available in BufferedReader class.
2. Scanner Class
In JDK 1.5,the developer starts to use java.util.Scanner to read system input.
Syntax
Scanner scanner = new Scanner(System.in);

3. System.console

In JDK 1.6, the developer starts to switch to the more simple and powerful java.io.Console class to read system input.
 It provides methods to read texts and passwords.
syntax
Console c=System.console();  

 Writing Console Output

PrintStream is an output stream derived from OutputStream,it also implements the low-level method write().
write() can be used to write to the console.
Syntax
The simplest form of write() defined by the PrintStream  is
void write(int byteval)

Naming conventions

All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.
      class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
      interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
      method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
      variable name should start with lowercase letter e.g. firstName, orderNumber etc.
      package name should be in lowercase letter e.g. java, lang, sql, util etc.
      constants name should be in all uppercase letters. e.g. RED, YELLOW, MAX_PRIORITY etc.
       

Arrays


Array is a collection of similar type of data. It is fixed in size means that you can't increase the size of array at run time. It is a collection of homogeneous data elements. It stores the value on the basis of the index value.



Advantage of Array

1.      Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.

2.      Random access: We can get any data located at any index position.

Disadvantage of Array

1.      Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime.



Types of Array

  1. Single Dimensional Array
  2. Multidimensional Array

 Array Declaration

Single dimension array declaration

Syntax

  1. int[] a;
  2. int a[];
  3. int []a

Multidimensional Array declaration

Syntax

  1. int[][] a;
  2. int a[][];
  3. int [][]a;
  4. int[] a[];
  5. int[] []a;
  6. int []a[];
Array creation

Every array in a Java is an object, Hence we can create array by using new keyword.

Syntax

int[] arr = new int[10]; // The size of array is 10.

or

int[] arr = {10,20,30,40,50};

Accessing array elements

Access the elements of array by using index value of an elements.

Syntax

arrayname[n-1];

every array type has  its corresponding class .

Class arr

{

Public static void main(String[] args)

{

Int[]  x=new int[3];

S.O.P(x.getClass().getName());// [I

}

}

Control Statements


Control statements are the statements which alter the flow of execution and provide better control to the programmer on the flow of execution.

Types of control statements

  1. selection control statements.
  2. iteration control statements.
  3.  jump control statements.  

1. Selection control statements

Selection statements can be divided into the following categories.

  1. The if statements
  2. The if-else statements
  3. The if-else-if statements
  4. The switch statements

1. If statement

if statement performs a task depending on whether a condition is true or false.

Syntax:

                                    if (condition)   

                                    statement1;

2. The if-else statements.

if the specified condition in the if statement is false, then the statement after the else keyword  will execute.

Syntax:

if (condition)  

 statement1;  

else  

statement2;



3. The if-else-if statements

This statement following the else keyword can be another if or if-else statement.

Syntax

if(condition)
   statements;
else if (condition)
   statements;
else if(condition)
   statement;
else
   statements;



4. The Switch Statements

When there are several options and we have to choose only one option from the available ones, we can use switch statement.

Syntax:

switch (expression)

   {

 case value1: //statement sequence     

break;   

case value2: //statement sequence

break;      

 ………….…..   

case valueN: //statement sequence  

   break;   

default: //default statement sequence 

 } 



2. Iteration Statements

Repeating the same code fragment several times until a specified condition is satisfied is called iteration.

the following loop for iteration statements

  1. The while loop
  2. The for loop
  3. The do-while loop
  4. The for each loop





1. The while loop

It continually executes a statement while a condition is true. The condition must return a Boolean value.

Syntax:

while (condition)  

{   

statements; 

 }



2. The do-while loop

The only difference between a while and a do-while loop is that do-while evaluates its expression at the bottom of the loop instead of the top. The do-while loop executes at least one time then it will check the expression prior to the next iteration.

Syntax

      do  

        {  

             //Statements

        }  

        while ( condition);  



3. The for loop

A for loop executes a statement as long as the Boolean condition evaluates to true. A for loop is a combination of the three elements initialization statement, Boolean expression and increment or decrement statement.

Syntax:

for(<initialization>;<condition>;<increment or decrement statement>)

     {     
//block of code
}



4. The For each loop

This was introduced in Java 5. This loop is basically used to traverse the array or collection elements.

Syntax

for(data_type variable : array | collection)

{

}  







3. Jump Statements

Jump statements are used to unconditionally transfer the program control to another part of the program.

Java provides the following jump statements

  1. break statement
  2. continue statement
  3. return statement



1. Break Statement

The break statement immediately quits the current iteration and goes to the first statement following the loop.

2. Continue Statement

The continue statement is used when you want to continue running the loop with the next iteration and want to skip the rest of the statements of the body for the current iteration.

3. Return Statement

The return statement is used to immediately quit the current method and return to the calling method. It is mandatory to use a return statement for non-void methods to return a value.

Saturday, August 5, 2017

Operators


Operator is a symbol that is used to perform operations.
Types of operators in java

  1. Arithmetic operators
  2. Relation operators
  3. Logical operators
  4. Bitwise operators
  5. Assignment operators
  6.  Ternary operator
  7. Unary Operator
Arithmetic operators

Arithmetic operators are used in mathematical expression.

Relation operators



Logical operators
Bitwise operators

Assignment Operators
Ternary operator
It is also known as Conditional operator and used to evaluate Boolean expression.
epr1 ? expr2 : expr3
If epr1Condition is true? Then value expr2 : Otherwise value expr3

Unary Operators


Friday, August 4, 2017

Type Conversion and Casting


Assigning value of one type to variable of another type is known as conversion.

In java we have two types of conversions.

  1. Implicit type conversion.
  2. Explicit type conversion.



1. implicit type conversion
Java automatically converts from one type to another  if it satisfy the following conditions.
1 Both types are compatible with each other.
2 The size of destination type is more than the source type.
This is also known as “Widening Conversion”.
Example
int i = 3;                                   int i=5;//size of int is 32
double f;                                  long d;//size of long is 64
f = i;                                        d=I;    
Example program
class TypeConversion
{
    public static void main(String arg[])
    {
        byte b = 50;
        short s = 4125;
        int i = 800000;
        long l = 107343L;       
        s = b;    
        i = s;   
        l = i;   
        float f = 25.0f;
        double d = 327.98;
        f = i;
        d = f;
        System.out.println("b = " + b );   
        System.out.println("s = " + s );   
        System.out.println("i = " + i );   
        System.out.println("l = " + l );   
        System.out.println("d = " + d );   
        System.out.println("f = " + f );  
    }
}

2. Explicit type conversion
If we want to convert two types which are incompatible or if the size of destination type is less than the size of source type, then we must do the conversion explicitly.
This process is also called as “type casting”. This is also called as Narrowing conversion .
Explicit type cast is requires to Narrowing conversion to inform the compiler that you are aware of the possible loss of precision.
Syntax
newValue = (typecast)value;
Example
double f = 3.5;
int i;
 i = (int)f; // it cast double value 3.5 to int 3.

Example program
class DatatypeCasting
{
    public static void main(String arg[])
    {
        byte b;
        int i = 81;
        double d = 323.142;
        float f = 72.38f;
        char c = 'A';
       
        c = (char) i;
        System.out.println("i = " + i + " c = " + c);
       
        i = (int) d; 
        System.out.println("d = " + d + " i = " + i); 
       
        i = (int) f; 
        System.out.println("f = " + f + " i = " + i); 
       
        b = (byte) d;
        System.out.println("d = " + d + " b = " + b);
   
    }
}

Data Types


Data type is a special keyword used to allocate sufficient memory space for the data.

Categories of data types

1.      Fundamental or primitive data types

2.      Derived data types

3.      User defined data types





1. Primitive data types
Primitive data types are those whose variables allows us to store only one value but they never allows us to store multiple values of same type.
Example
 int a; // valid
 a=10; // valid
a=10, 20, 30; // invalid


We have eight Primitive data type which are organized in four groups.
  1. Integer category data types
  2. Character category data types
  3. Float category data types
  4. Boolean category data types
1. Integer category data types

2. Character category data types
This data type takes two byte since it follows Unicode character set.

3. Float category data types
4. Boolean category data types


2. Derived data types
Derived data types are those whose variables allow us to store multiple values of same type. But they never allows to store multiple values of different types.
Example
int a[] = {10,20,30}; // valid
int b[] = {100, 'A', "ABC"}; // invalid
3. User defined data types
User defined data type related variables allows us to store multiple values either of same type or different type or both.
This is a data type whose variable can hold more than one value of dissimilar type.
Example
Student s = new Student();