Home Education Java Examples & Functions for beginners

Java Examples & Functions for beginners

We are going to study Java Functions and Java Examples in detail. In the previous blog, we saw the Syntax and the basics of Java. If you want to see the loops and keyword then you can visit our #2 blog page i.e. C programming. In every programming language, the logic will be the same but with different syntax.

Hey do you covered Java Basics?

What you are going to find here:

  1. What are the Functions?
  2. Java Examples
  3. Constructors
  4. Conclusion
  5. QnA

What are the Java Functions?

Functions are basically a block of code written in { } and only runs when it is called.

Java functions

Let’s take an example if you want to know the sum of odds and evens, then what should you do? You will be going to write two statements consisting of odds addition and the evens addition. But what if you take the addition part apart from odd and even.

This is what the function is.

We just have to pass the odd numbers to the add function( add() ) and after displaying its result then we pass the even numbers to the add function which is the same.

Before we understand this example, let’s understand how to call a function.

How to call a function?

public static void myMethod()
{
    System.out.println("This is a function");
}

Here you can see we called this function as the main method because the main is also a function.
This is a function, but how should we call it…

It is called inside the main.

Function without any parameters

class Main 
{
 public static void main(String[] args) 
 {
  System.out.println("About to encounter a method.");
   myMethod(); // Here we called the method.
  System.out.println("Successful"); 
  }
   private static void myMethod()
   {
    System.out.println("Method is called.");
   }
 }

Parameterized function

Parameters are the functions that accept values and also return them.

class Addition 
{
  public static void main(String[] args) {
  int result, a=2, b=4;
  result = add(a, b); 
  System.out.println("Sum of A & B is : " + result);
 }
  public static int add(int a, int b) // a & b are parameters
  {
    return a+b ;
 }
}

What is Recursion in Java?

A method which calls itself is called recursion.

To understand it fully let’s take Java example of Factorial.

//Recursion
class Factorial 
{
  public static int fact( int n ) 
  {
    if (n != 0) 
       return n * fact(n-1);
    else
       return 1;
  }
 public static void main(String[] args) 
 {
  int n = 5, res;
  res = fact(n);
  System.out.println( “Factorial is :” + result);
 }
}

Here in the above program, we used recursion.

The java first runs the main code. So, in the main method, we declared n which stores 5 and we passed it to the fact() so that it calculates the factorial of 5 and passes the result and will be stored in res.

We called the recursion the same as the function.

To calculate factorial of 5 we should know what actually the factorial is.

The factorial is the multiplication of all the numbers range from 1 to n( the original no. ).

As of for the 5, the factorial is 1*2*3*4*5 which is 120.

To perform the factorial, the compiler will check for the if condition( i.e. 5 != 0) which is true. So, the compiler goes for the return n * fact(n-1);  in which the n * fact(n-1) means that the equation will be 5* and then the compiler has to go for the fact() function with n-1 (5-1=>4) which means on the next loop the equation will be 4 * fact(4-1) and so on….

This loop will continue until the n became 1-1 i.e. 0, which means the compiler from the n=1 will return to its previous equation i.e. return 2*fact(n-1) where the returned value will be 1. So, the equation will look like this return 2*1. Again the loop went to the previous equation with the returned value and so on until 5.

After the successful recursion, the expression will become 5*4*3*2*1 which excludes 0 because we terminated the loop when the 0 occurs and returned back.

Java Examples

Java Examples
  1. Fibonacci:
class Fibonacci{  
public static void main(String args[])  
{    
 int n1=0,n2=1,n3,i,count=10;    
 System.out.print(n1+" "+n2);  
 for(i=2;i<count;++i)   
 {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }
} 

Here’s the code. Now you have to write this code using function & recursion.

  1. Finding a Palindrome number
public class Palindrome
{  
 public static void main(String args[])
 {  
  int res,sum=0,temp;    
  int n=454;   
  temp=n;    
  while(n>0)
  {    
   res=n%10; 
   sum=(sum*10)+res;    
   n=n/10;    
  }    
  if(temp==sum)    
   System.out.println("It’s a palindrome number ");    
  else    
   System.out.println("It’s not palindrome");    
 }  
}  

Here’s the code. Now you have to write this code using function & recursion.

  1. Prime Number
public class Prime
{    
 public static void main(String args[])
 {    
  int i,m=0,flag=0;      
  int n=3;//it is the number to be checked    
  m=n/2;      
  if(n==0||n==1)  
   System.out.println(n+" is not prime number");      
   else
    {  
     for(i=2;i<=m;i++)
      {      
        if(n%i==0)
        {      
         System.out.println(n+" is not prime number");      
         flag=1;      
         break;      
      }      
     }       
    if(flag==0)  { System.out.println(n+" is prime number");
    }  
  }  
 }    
} 

Here’s the code. Now you have to write this code using function & recursion.

Java Constructors

In most cases, it is required that as soon as an instance(or object) is created, its members should be initialized. Java allows objects to initialize themselves when they are created.

Java Constructors

Types of Constructors

  1. Default Constructor

This is a constructor with no parameters. If you don’t define a constructor for a class, it is automatically created by the compiler. However, if you define any constructor for your class, a default constructor is no longer automatically created.

Ex.

class MyRectangle
{
 int length, breadth;
 MyRectangle()
 {
  Length =0; breadth =0;
}
}
  1. Parameterized Constructor

Java supports method overloading. This means that two or more methods can have the same signature within the same scope. We can add another constructor to the class which will assign user-given values to the members. The job of the parameterized constructor is to assign specific values to members.

class MyRectangle
{
 int length, breadth;
 MyRectangle(int l, int b )
 {
   this.length =l;
   this. breadth =b;
 }
}

In this example, the constructor takes two arguments l & b. The values of l and b are used to initialize data members(instance members) length and breadth.

  1. Overloading Constructor

A constructor is a member function of the class. A class can have multiple constructors. This is called overloading of constructors. Having multiple constructors allows objects to be created in different ways.

class MyRectangle
{
 int length, breadth;
 MyRectangle() // default constructor
 {
  Length =0; breadth =0;
 }
 MyRectangle(int length, int breadth) //parameterized constructor
 {
   this.length =length;
   this. breadth =breadth;
 }
}

In the above example, the class has two constructors. The first is default and the second is parameterized. In the parameterized constructor, we have used the same names for the parameters as the instance members. Hence, there is an ambiguity. This can be resolved using “this” keyword. The “this” keyword is used to identify the instance variables.

this keyword

The object which invokes a method is called the implicit or the hidden object. Sometimes a method needs to refer to this implicit object. To allow this, Java defines this keyword. 

this keyword always refers to the current or the implicit object.

Conclusion

We have covered the basics of Java, Java functions, and Java Examples. Java is very deep. You can get an intermediate or advanced course for Java.

After Intermediate you can easily move to Android development. You can’t make Android apps immediately, you have to go very far to achieve success.

I mean to say that you still have to learn a lot. Every programmer/coder who is having a job is actually trying to learn more so that he/she can get more out of it. Never Stop Learning.

QnA

Q1. Are Java and Javascript the same?

No. It’s totally different.

Q2. How should I start coding Android apps?

If you know Java language, then download Android Studio. Also, you need little knowledge of XML.

Q3. With Java, am I able to make IOS app?

No. IOS supports Swift language.

Q4. What programming languages should I need to know to start Java?

Not a single one. You just need to learn from scratch.

Q5. Can I learn Java without programming experience?

Yes.

You completed Java from our side. But you have to learn a lot.

But, do you know Python is the most demanding language. Want to learn basics and wanted to see how easy it is, then check this:- Learn Python Programming (Most powerful Language)

RELATED ARTICLES

List of Best Kitchen Hobs in India 2021 with a Detailed Guide

Indian Houses are always incomplete without a kitchen, and one of the essential appliances for any kitchen is a kitchen hob. Whether...

Best Gaming Laptops in India That You Can Buy in 2021

Presently, laptops play a crucial role in everyone's life. Due to advancements in technology, nowadays all individuals use laptops for various purposes....

Best Wi-Fi Modem for BSNL Broadband – Detailed Comparison

In this information age, we all firstly depend on the internet very much for day to day tasks. Almost every business has...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

List of Best Kitchen Hobs in India 2021 with a Detailed Guide

Indian Houses are always incomplete without a kitchen, and one of the essential appliances for any kitchen is a kitchen hob. Whether...

Best Gaming Laptops in India That You Can Buy in 2021

Presently, laptops play a crucial role in everyone's life. Due to advancements in technology, nowadays all individuals use laptops for various purposes....

Best Wi-Fi Modem for BSNL Broadband – Detailed Comparison

In this information age, we all firstly depend on the internet very much for day to day tasks. Almost every business has...

Rice Companies in India

Rice, unlike most other cereals, we consume it as a whole grain. No one is there who is not fond of rice....

Recent Comments