Methods of Java

Methods of Java


Methods In Java


Java program consists of one or more classes, and a class may contain methods. In this blog, we will learn about Java and their methods. Methods are known as functions in C and Cpp programming languages. A method has a name and return type. The main method is a must in a Java program as execution begins from it.

Syntax of methods:
"Access specifier" "Keyword(s)" "return type" methodName(List of arguments)
{
// Body of method
}

Access specifier can be public or private which decides whether other classes can call a method.
Keywords such as static or synchronized are used for some particular methods.
Return type indicates return value which method returns.
Method name is a valid Java identifier name.

Access specifier, keyword(s), and arguments are optional.

Examples of methods declaration:
public static void main(String[] args);
void myMethod();
private int maximum();
public synchronized int search(java.lang.Object);

Java Method example:

class Methods
{

  // Constructor method

  Methods()
  {
    System.out.println("Constructor method is called when an object of it's class is created");
  }

  // Main method where program execution begins

  public static void main(String[] args)
  {
    staticMethod();
    Methods object = new Methods();
    object.nonStaticMethod();
  }

  // Static method

  static void staticMethod()
  {
    System.out.println("Static method can be called without creating object");
  }

  // Non static method

  void nonStaticMethod()
  {
    System.out.println("Non static method must be called by creating an object");
  }
}

Java methods list


Java has a built-in library of many useful classes, and there are thousands of methods which can be used in a program. Just call a method and get your work done :). You can find the list of methods in a class by typing following command on command prompt:

javap package.classname

For example
javap java.lang.String // list all methods and constants of String class.
javap java.math.BigInteger // list constants and methods of BigInteger class in java.math package

Java String methods
String class contains methods which are useful for performing operations on String(s). Below program illustrate how to use inbuilt methods of String class.

Java string class program
class StringMethods
{
  public static void main(String args[])
  {
    int n;
    String s = "Java programming", t = "", u = "";

    System.out.println(s);

    // Find length of string

    n = s.length();
    System.out.println("Number of characters = " + n);

    // Replace characters in string

    t = s.replace("Java", "C++");
    System.out.println(s);
    System.out.println(t);

    // Concat string with another string

    u = s.concat(" is fun");
    System.out.println(s);
    System.out.println(u);
  }
}
Basic Java Programs

Basic Java Programs

Java program to reverse a number


Following program prints reverse of a given number, i.e., if input is 268 then the output will be 862.

Source code :

import java.util.Scanner;

class Rev
{
   public static void main(String arg[])
   {
      int x, rev = 0;

      System.out.println("Enter a number to reverse");
      Scanner sc = new Scanner(System.in);
      x = sc.nextInt();

      while(x != 0)
      {
          rev = rev * 10;
          rev = rev + x%10;
          x = x/10;
      }

      System.out.println("Reverse of the number is = " + rev);
   }

}


Java program to print prime numbers:


This program prints prime numbers. And also Remember that smallest prime number is 2.

Source code:

import java.util.*;

class PrimeNum
{
   public static void main(String args[])
   {
      int n, status = 1, num = 3;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter the number of prime numbers you want");
      n = in.nextInt();

      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are :-");
         System.out.println(2);
      }

      for ( int count = 2 ; count <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            count++;
         }
         status = 1;
         num++;
      }         
   }

}

Java program to find odd or even


Following java program finds a number is odd or even. If the number is divisible by two then it will be even, otherwise, it is odd. We use the modulus operator to find remainder in our program.

Java programming source code
import java.util.Scanner;

class OddOrEven
{
   public static void main(String args[])
   {
      int x;
      System.out.println("Enter an integer to check if it is odd or even ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();

      if ( x % 2 == 0 )
         System.out.println("You entered an even number.");
      else
         System.out.println("You entered an odd number.");
   }
}

How to take input from a user in Java

Get input from a user: we are using Scanner class to get input from the user. This program asks the user to enter an integer, a float, and a string; then they are printed on the screen. Scanner class is present in java.util package so we import this package into our program. We first create an object of Scanner class and then we use the methods of Scanner class. 
Consider the statement:

 Scanner a = new Scanner(System.in);

Here Scanner is the class name, a is the name of the object, new keyword is used to allocate the memory and System.in is the input stream. Following methods of Scanner class are used in the program:

1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string

Program:

import java.util.Scanner;

class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      String s;

      Scanner in = new Scanner(System.in);

      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer "+a);

      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float "+b);   

      System.out.println("Enter a string");
      s = in.nextLine();
      System.out.println("You entered string "+s);
   }

}
How to show status bar notifications:

How to show status bar notifications:


How to show status bar notifications:

A status bar notification adds an icon to the system’s status bar with an optional ticker-text message and a notification message in the notifications window. When the user selects the notification, usually an Activity is opened. The notification can be configured to alert the user with a sound, a vibration, and flashing lights on the device.
In the example below a notification is fired immediately and when user clicks on it, the PuNotification activity opens.


@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   // Get a reference to the NotificationManager
   NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

   // Instantiate the Notification with an icon, ticker text, and when to be displayed
   int icon = R.drawable.ic_launcher;
   CharSequence tickerText = "New notification";
   long when = System.currentTimeMillis(); //now
   Notification notification = new Notification(icon, tickerText, when);

   // Define the notification's message and PendingIntent
   Context context = getApplicationContext();
   CharSequence title = "Notification title";
   CharSequence text = "Notification description";
   // The activity PostNotification.class will be fired when notification will be opened.
   Intent notificationIntent = new Intent(this, PostNotification.class);
   PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

   // Makes the notification disappear after clicked in the status bar
   notification.flags|=Notification.FLAG_AUTO_CANCEL;

   // When the notification will be fired, notify the user with default notification phone sound.
   notification.defaults|=Notification.DEFAULT_SOUND;

   notification.setLatestEventInfo(context, title, text, pendingIntent);

   // Pass the Notification object to NotificationManager
   notificationManager.notify(1, notification);
}
If you’d like to try the example above, create a new Activity called: PuNotification, create a new layout file, say punotification.xml and add in the PostNotification activity:
setContentView(R.layout.punotification);

Android Menu (OptionsMenu)


Android OptionsMenu Tutorial
Menu is an important user interface component which provides some action options for a particular activity. In this post I’ll show the basics for setting up a menu.
The final output will look like this:

The activity will contain 2 menu options: Add and Help. When clicking an option menu, a Toast notification will be displayed.
 Fill in the content of options.xml file with following code:
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
   <item
      android:id="@+id/add"
      android:icon="@android:drawable/ic_menu_add"
      android:title="Add"/>

   <item
      android:id="@+id/help"
      android:icon="@android:drawable/ic_menu_help"
      android:title="Help"/>
</menu>
menu – defines the menu
item  – defines a menu item

4. Open the main Activity class and type following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MenuTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
}

// Inflate the menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.options, menu);
   return true;
}

// Handle click events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
   case R.id.add:
      Toast.makeText(this, "Add", Toast.LENGTH_SHORT).show();
      return true;
   case R.id.help:
      Toast.makeText(this, "Help", Toast.LENGTH_SHORT).show();
      return true;

   default:
      return super.onOptionsItemSelected(item);
}
}
}
– The onCreateOptionsMenu() method inflates your menu defined in the XML resource.
– The onOptionsItemSelected() method handle click events. When the user selects an item from the options menu, the system calls the onOptionsItemSelected() method. This method passes the MenuItemselected. The MenuItem can identify the item by calling the getItemId() which returns the unique ID for the menu item defined by the android:id attribute in the menu resource. Depending of the returned ID, we display the appropriate Toast notification.