Function and Type Casting

Function and typecasting in Java

Function and Type Casting

Functions

A function or a method is a peice of code which will perform certain task, it can take input and produce an output

Syntax

 public static return_type function_name(datatype arg1, datatype arg2,....... datatype argn )
{

 return value;

 }

Example

  public static void add(int a, int b) {

 return a+b;

  }

Function with no return value

 public static void add(int a, int b, int c)
 {

   System.out.println(a+b+c);
  }

Functions with multiple return value

  public static void add(int a, int b, boolean isActive)
  { 
    if(isActive)
      {
         return a+b;
      } else {

         return 0;
         }
   }

Note

Statements after return statements are not executed as they are unreachable.

Impact of return statement inside loops

    for(int i=1;i<=10;i++) 
     {

       if(i==6)
         {
          return
          }
      System.out.println(i);
      }

Output

1 2 3 4 5

TypeCasting

What is Type Casting?

Type casting is nothing but assigning a value of one primitive data type to another. When you assign the value of one data type to another, you should be aware of the compatibility of the data type. If they are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not, then they need to be casted or converted explicitly. There are two types of casting in Java.

Widening Casting (automatically)

This type of casting takes place when two data types are automatically converted. It is also known as Implicit Conversion. This happens when the two data types are compatible and also when we assign the value of a smaller data type to a larger data type.

Example 1:

 int i = 200;
 long l = i;
System.out.println(l);

Output

200

Example 2:

  byte x = 10;
  int y = x;
  System.out.println(y);

Output

10 Example 3:

  char ch = 'A';
  String st = ch;
  System.out.println(st);

Output

Error- Incompatible Types

Narrowing Casting

In this case, if you want to assign a value of larger data type to a smaller data type, you can perform Explicit type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be done. Example 1:

 double d = 200.06d;
 int number = (int)d;
 System.out.println(number);

Output

200

Example 2:

  float a = 341.09453f;
  short b = (short)a;
  System.out.println(b);

Output

341 Example 3:

   char a = 'C';
   boolean b = (boolean)a;
   System.out.println(b);

Output

Error - Incompatible Types