Part 24: List of Java Keywords with real Example

Part 24: List of Java Keywords with real Example

Java Keywords

Java keywords are also known as reserved words. They are particular words that acts as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.

Let’s know the list of Java Keywords. A list of Java keywords or reserved words are given below:

abstract:

This keyword is used to declare abstract class. Abstract class can provide the implementation of interface. It can have abstract and non-abstract methods.

boolean:

The Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.

break:

Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at specified condition.

byte:

The byte keyword is used to declare a variable that can hold an 8-bit data values.

case:

The java case keyword is used to with the switch statements to mark blocks of text.

catch:

Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.

char:

The char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters

class:

In Java, the class keyword is used to declare a class.

continue:

In Java, the continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.

default:

The default keyword in java is used to specify the default block of code in a switch statement.

do:

The Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several times.

double:

The Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.

else:

The default Java else keyword is used to indicate the alternative branches in an if statement.

enum:

The Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.

extends:

The default Java extends keyword is used to indicate that a class is derived from another class or interface.

final: The default Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is used to restrict the user.

finally: The default Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether exception is handled or not.

float: The Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.

for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.

if: The default  Java if keyword tests the condition. It executes the if block if condition is true.

implements: The default Java implements keyword is used to implement an interface.

import: The Java import keyword makes classes and interfaces available and accessible to the current source code.

instanceof: The default Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.

int: The default Java int keyword is used to declare a variable that can hold a 32-bit signed integer.

interface:

The default Java interface keyword is used to declare an interface. It can have only abstract methods.
long: The default Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: The default Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).

new: The default Java new keyword is used to create new objects.

null:

The default Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.

package:

The default Java package keyword is used to declare a Java package that includes the classes.

private:

The default Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.

protected:

The default Java protected keyword is an access modifier. It can be accessible within package and outside the package but through inheritance only. It can’t be applied on the class.

public:

The default Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.

return:

The default Java return keyword is used to return from a method when its execution is complete.

short:

The default Java short keyword is used to declare a variable that can hold a 16-bit integer.

static:

The default Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is used for memory management mainly.

strictfp:

The default Java strictfp is used to restrict the floating-point calculations to ensure portability.

super:

The default Java super keyword is a reference variable that is used to refer parent class object. It can be used to invoke immediate parent class method.

switch:

The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.

synchronized:

Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.

this:

In Java this keyword can be used to refer the current object in a method or constructor.

throw:

The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exception. It is followed by an instance.

throws:

The Java throws keyword is used to declare an exception. Checked exception can be propagated with throws.

transient:

In Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.

try:

In Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.

void:

In Java void keyword is used to specify that a method does not have a return value.

volatile:

In Java volatile keyword is used to indicate that a variable may change asynchronously.

while:

In Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

Here is a few example with keywords:

public abstract class AbstractClass {
// This method is abstract ; it does not have a body
public abstract void abstractMethod();

// it is implemented in the abstract class and gives a default behavior.
public void concreteMethod() {
System.out.println("Already coded.");
}
}

The above code abstract keyword use here first method has no body as it is a abstract.

AbstractClass myObject = new AbstractClass() {
public void abstractMethod() {
System.out.println("Implementation.");
}
};

Above example code uses keyword new and the code has implemented method which has body.

 

Part 24: List of Java Keywords with real Example

Part 18: Iterator in java with real Time example

Iterator in java

Iterator in java allows to cycle through a collection can be added or removing elements. To access a collection over an iterator, must attain one. Each of the collection classes offers an iterator () method that returns an iterator to the start of the collection. By using this iterator object can access each element in the collection at a time each element. Class ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements. In general, to use an iterator to cycle through the contents of a collection steps are:

  • Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
  • Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  • Within the loop, obtain each element by calling next( ).

The Methods Declared by Iterator

Method with Description mention below

  • hasNext( ) returns true if there are more elements. Otherwise, returns false.
  • Object next( ) returns the next element. Throws NoSuchElementException if there is not a next element.
  • remove( ) method is used to removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).

The Methods Declared by ListIterator

  • add(Object obj): It is used to Inserts obj into the list in front of the element that will be returned by the next call to next( ).
  • hasNext( ): It returns true if there is a next element. Otherwise, returns false.
  • hasPrevious( ):It returns true if there is a previous element. Otherwise, returns false.
  • Object next( ): It returns the next element. A NoSuchElementException is thrown if there is not a next element.
  • nextIndex( ):It returns the index of the next element. If there is not a next element, returns the size of the list.
  • Object previous( ): This is returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
  • previousIndex( ):This is returns the index of the previous element. If there is not a previous element, returns -1.
  • remove( ): It is removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.
  • set(Object obj): This is used to assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Example

import java.util.*;
public class Main {
public static void main(String args[]) {
ArrayList letters = new ArrayList();// Create an array list
// add elements to the array list
letters.add("C");
letters.add("A");
letters.add("E");
letters.add("B");
letters.add("D");
letters.add("F");
// Use iterator to display contents of letters
System.out.print("Original contents of letters: ");
Iterator itr_1 = letters.iterator();
while(itr_1.hasNext()) {
Object object = itr_1.next();
System.out.print(object + " ");
}
System.out.println();
// Modify objects being iterated
ListIterator itr_2 = letters.listIterator();
while(itr_2.hasNext()) {
Object object1 = itr_2.next();
itr_2.set(object1 + "+");
}
System.out.print("Modified contents of letters: ");
itr_1 = letters.iterator();
while(itr_1.hasNext()) {
Object object = itr_1.next();
System.out.print(object + " ");
}
System.out.println();
// Now, display the list backwards
System.out.print("Modified list backwards: ");
while(itr_2.hasPrevious()) {
Object object = itr_2.previous();
System.out.print(object + " ");
}

System.out.println();

}

}

This will produce the following result −

Output

Original contents of al: C A E B D F

Modified contents of al: C+ A+ E+ B+ D+ F+

Modified list backwards: F+ D+ B+ E+ A+ C+

Part 24: List of Java Keywords with real Example

Part 17: HashSet in Java with real time example

Java HashSet

In a HashSet, every item is unique which is known as collection. It is found in the java.util packages. This  collection uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. A list can contain duplicate elements whereas Set contains unique elements only.

The importantfeatures about Java HashSet class are:

  • It stores the elements by using a mechanism called hashing.
  • It contains unique elements only.
  • It allows null value.
  • It class is none synchronized.
  • It doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • It is the best approach for search operations.

Java HashSet  Declaration:

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet

  • HashSet():It is used to construct a default HashSet.
  • HashSet(int capacity):It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
  • HashSet(int capacity, float loadFactor):It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
  • HashSet(Collection<? extends E> c):It is used to initialize the hash set by using the elements of the collection c.

Methods of Java HashSet class

  • add(E e):It is used to add the specified element to this set if it is not already present.
  • clear():It is used to remove all of the elements from the set.
  • object clone(): It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
  • contains(Object o):It is used to return true if this set contains the specified element.
  • isEmpty():It is used to return true if this set contains no elements.
  • iterator():It is used to return an iterator over the elements in this set.
  • remove(Object o):It is used to remove the specified element from this set if it is present.
  • int size():It is used to return the number of elements in the set.

Example

//Create a HashSet object called letters that will store strings:

import java.util.HashSet; // Import the HashSet class

HashSet<String> lettes = new HashSet<String>();

Add Items: The HashSet class has many useful methods. For example, to add items to it, use the add() method:

Example

// Import the HashSet class

import java.util.HashSet;

public class Main {

public static void main(String[] args) {

HashSet<String> lettes = new HashSet<String>();

lettes.add("A");

lettes.add("B");

lettes.add("C");

lettes.add("B");

lettes.add("E");

System.out.println(lettes);

}

}

OUTPUT:

A B C E

In the example above, even though Bis added twice it only appears once in the set because every item in a set has to be unique.

  • Check If an Item Exists: In order to check whether an item exists in a HashSet, use the contains() method:

Example

lettes.contains(“B”);

  • Remove an Item: In order to remove an item, use the remove() method:

Example

lettes.remove(“A”);

To remove all items, use the clear() method:

Example

lettes.clear();

HashSet Size

In order to find out how many items there are, use the size method:

Example

lettes.size();

HashSet Loop: Loop through the items of an HashSet with a for-each loop:

Example

for (String i : letters) {

System.out.println(i);

}

Other Types:

In order To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Example

Use a HashSet that stores Integer objects:

import java.util.HashSet;

public class ExMain {

public static void main(String[] args) {

// Create a HashSet object called numbers

HashSet<Integer> numbers = new HashSet<Integer>();

// Add values to the set

numbers.add(4);

numbers.add(7);

numbers.add(8);

// Show which numbers between 1 and 10 are in the set

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

if(numbers.contains(i)) {

System.out.println(i + " was found!");

} else {

System.out.println(i + " was not found!");

}

}

}

}

OUTPUT​

1 was not found!

2 was not found!

3 was not found!

4 was found!

5 was not found!

6 was not found!

7 was found!

8 was found!

9 was not found!

10 was not found!

Part 24: List of Java Keywords with real Example

Part 15: Java ArrayList with real time example

Java ArrayList

The ArrayList class is a resizable array in the java.util package. There is a difference between a built-in array and an ArrayList in Java. The size of an array cannot be modified to add or remove elements to/from an array to create a new one. While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

Example

Create an ArrayList object called cars that will store strings:

import java.util.ArrayList; // This is import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // This is create an ArrayList object

If you are not gather much  knowlodge what a package is, read our Java Packages Tutorial.

Add Items

To add an items, the ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method:

Example

import java.util.ArrayList;

public class Main {

  public static void main (String[] args) {

    ArrayList<String> names = new ArrayList<String>();

    names.add("Babita");

    names.add("Mamita");

    names.add("Kabita");

    names.add("Cabita");

    names.add("Rabita");

    System.out.println(names);

  }

}

Access an Item

To access an element in the ArrayList need to use the get() method and refer to the index number:

Example

names.get(0);

Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Item

In order to modify an element, use the set() method and refer to the index number:

Example

names.set(0, “Jarite”);

Remove an Item

In order to remove an element, use the remove() method and refer to the index number:

Example

names.remove(0);

To remove all the elements in the ArrayList, use the clear() method:

Example

names.clear();

ArrayList Size

In order to find out how many elements an ArrayList have, use the size method:

Example

names.size();

Loop Through an ArrayList

Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run:

Example

public class ExampleMain {

  public static void main(String[] args) {

    ArrayList<String> names = new ArrayList<String>();

    names.add("Babita");

    names.add("Mamita");

    names.add("Kabita");

    names.add("Cabita");

    names.add("Rabita");

    for (int i = 0; i < names.size(); i++) {

      System.out.println(names.get(i));

    }

  }

}

You can also loop through an ArrayList with the for-each loop:

Example

public class Main {

  public static void main(String[] args) {

    ArrayList<String> names = new ArrayList<String>();

    names.add("Babita");

    names.add("Mamita");

    names.add("Kabita");

    names.add("Cabita");

    names.add("Rabita");

    for (String i : names) {

      System.out.println(i);

    }

  }

}

Other Types

Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type “String”. Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Example

Create an ArrayList to store numbers (add elements of type Integer):

import java.util.ArrayList;

public class ExampleMain {

  public static void main(String[] args) {

    ArrayList<Integer> myNumbers = new ArrayList<Integer>();

    myNumbers.add(10);

    myNumbers.add(15);

    myNumbers.add(20);

    myNumbers.add(25);

    for (int i : myNumbers) {

      System.out.println(i);

    }

  }

}

Sort an ArrayList

Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically:

Example: Sort an ArrayList of Strings:

import java.util.ArrayList;

import java.util.Collections;  // Import the Collections class

public class Main {

  public static void main(String[] args) {

    ArrayList<String> cars = new ArrayList<String>();

    names.add("Babita");

    names.add("Mamita");

    names.add("Kabita");

    names.add("Cabita");

    names.add("Rabita");

    Collections.sort(names);  // Sort cars

    for (String i : names) {

      System.out.println(i);

    }

  }

}

Example

Sort an ArrayList of Integers:

import java.util.ArrayList;

import java.util.Collections;  // Import the Collections class

public class Main {

  public static void main(String[] args) {

    ArrayList<Integer> myNumbers = new ArrayList<Integer>();

    myNumbers.add(33);

    myNumbers.add(15);

    myNumbers.add(20);

    myNumbers.add(34);

    myNumbers.add(8);

    myNumbers.add(12);

    Collections.sort(myNumbers);  // Sort myNumbers

    for (int i : myNumbers) {

      System.out.println(i);

    }

  }

}

Java ArrayList class hierarchy:

Java ArrayList class uses a dynamic array for storing the elements. It is simila to an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package.  The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of List interface here. The ArrayList maintains the insertion order internally. It inherits the AbstractList class and implements List interface.

The important points about ArrayList are:

  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.

In ArrayList, manipulation is little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.

Hierarchy of ArrayList class

As shown in the above diagram, Java ArrayList class extends AbstractList class which implements List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let’s see the declaration for java.util.ArrayList class.

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable

Constructors of ArrayList, Constructor   with  Description BELOW

  1. ArrayList() :  It is used to build an empty array list.
  2. ArrayList(Collection<? extends E> c): It is used to build an array list that is initialized with the elements of the collection c.
  3. ArrayList(int capacity): It is used to build an array list that has the specified initial capacity.
Methods of ArrayList Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator.
boolean addAll(int index, Collection<? extends E> c) It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an ArrayList instance.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
Iterator() It works to traverse collection.
listIterator() It works to traverse collection or list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the correct order.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> filter) It is used to remove all the elements from the list that satisfies the given predicate.
protected void removeRange(int fromIndex, int toIndex) It is used to remove all the elements lies within the given range.
void replaceAll(UnaryOperator<E> operator) It is used to replace all the elements from the list with the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified comparator.
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements lies within the given range.
int size() It is used to return the number of elements present in the list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list’s current size.
void add(int index, E element) It is used to insert the specified element at the specified position in a list.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.

Old non-generic example of creating java collection.

ArrayList list=new ArrayList();//creating old non-generic arraylist. New generic example of creating java collection.

ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.

Java ArrayList Example

import java.util.*; 

 public class ArrayListExample1{ 

 public static void main(String args[]){ 

  ArrayList<String> list=new ArrayList<String>();//Creating arraylist   

      list.add("Man");//Adding object in arraylist   

      list.add("Cat");   

      list.add("Banana");   

      list.add("Cow");          //Printing the arraylist object  

      System.out.println(list); 

 } 

}

Test it Now

Output:

[Man, Cat, Banana, Cow]

Iterating ArrayList using Iterator

Let’s see another example to traverse ArrayList elements using the Iterator interface.

import java.util.*; 

public class ArrayListExample2{ 

 public static void main(String args[]){ 

  ArrayList<String> list=new ArrayList<String>();//Creating arraylist 

  list.add("Man");//Adding object in arraylist   

  list.add("Cat");   

  list.add("Banana");   

  list.add("Cow");            //Traversing list through Iterator 

  Iterator itr=list.iterator();//getting the Iterator 

  while(itr.hasNext()){//check if iterator has the elements 

   System.out.println(itr.next());//printing the element and move to next 

  } 

 } 

}

Output:
Man
Cat
Banana
Cow

Iterating ArrayList using For-each loop

Let’s see another example to traverse the ArrayList elements using the for-each loop

import java.util.*; 

public class ArrayListExample3{ 

 public static void main(String args[]){ 

  ArrayList<String> list=new ArrayList<String>();//Creating arraylist 

  list.add("Man");//Adding object in arraylist   

      list.add("Cat");   

      list.add("Banana");   

      list.add("Cow");            //Traversing list through for-each loop 

  for(String fruit:list)   

    System.out.println(fruit);   

 } 

}

Output:
Man
Cat
Banana
Cow

Get and Set ArrayList

The get() method returns the element at the specified index, whereas the set() method changes the element.

import java.util.*; 

public class ArrayListExample4{ 

 public static void main(String args[]){ 

  ArrayList<String> list=new ArrayList<String>(); 

  list.add("Man");//Adding object in arraylist   

      list.add("Cat");   

      list.add("Banana");   

      list.add("Cow");            //accessing the element   

  System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0 

  //changing the element 

  list.set(1,"Dates"); 

  //Traversing list 

  for(String lives:list)   

    System.out.println(lives);   

 } 

}

Output:

Returning element:
Man
Cat
Banana
Cow

How to Sort ArrayList

The java.util package provides a utility class Collections which has the static method sort(). Using the Collections.sort() method, we can easily sort the ArrayList.

import java.util.*; 

class SortArrayList{ 
 public static void main(String args[]){ 
  //Creating a list of fruits 
  List<String> list1=new ArrayList<String>(); 
  list.add("Man");//Adding object in arraylist   
      list.add("Cat");   
      list.add("Banana");   
      list.add("Cow");            //Sorting the list 
  Collections.sort(list1); 

   //Traversing list through the for-each loop 

  for(String lives:list1) 

    System.out.println(lives); 

    System.out.println("Sorting numbers..."); 

  //Creating a list of numbers 

  List<Integer> list2=new ArrayList<Integer>(); 

  list2.add(12); 

  list2.add(11); 

  list2.add(10); 

  list2.add(9); 

  //Sorting the list 

  Collections.sort(list2); 

   //Traversing list through the for-each loop 

  for(Integer number:list2) 

    System.out.println(number); 

 } 

}

Output:

Man
Cat
Banana
Cow

Sorting numbers…

9
10
11
12

Ways to iterate the elements of the collection in Java: 

There are various ways to traverse the collection elements. By Iterator interface, for-each loop, ListIterator interface, for loop,forEach() and  forEachRemaining() method. Let’s see an example to traverse the ArrayList elements through other ways

import java.util.*; 

class ArrayList4{ 

 public static void main(String args[]){ 

    ArrayList<String> list=new ArrayList<String>();//Creating arraylist 

           list.add("Man");//Adding object in arraylist   

      list.add("Cat");   

      list.add("Banana");   

      list.add("Cow");                      

           System.out.println("Traversing list through List Iterator:"); 

           //Here, element iterates in reverse order 

              ListIterator<String> list1=list.listIterator(list.size()); 

              while(list1.hasPrevious()) 

              { 

                  String str=list1.previous(); 

                  System.out.println(str); 

              } 

        System.out.println("Traversing list through for loop:"); 

           for(int i=0;i<list.size();i++) 

           { 

            System.out.println(list.get(i));    

           } 

             

        System.out.println("Traversing list through forEach() method:"); 

        //The forEach() method is a new feature, introduced in Java 8. 

            list.forEach(a->{ //Here, we are using lambda expression 

                System.out.println(a); 

              }); 

            System.out.println("Traversing list through forEachRemaining() method:"); 

              Iterator<String> itr=list.iterator(); 

              itr.forEachRemaining(a-> //Here, we are using lambda expression 

              { 

            System.out.println(a); 

              }); 
 } 

}

Output:

Traversing list through List Iterator:
Man
Cat
Banana
Cow

Traversing list through for loop:

Cow
Banana
Cat
Man

Traversing list through forEach() method:

Cow
Banana
Cat
Man

Traversing list through forEachRemaining() method:

Cow
Banana
Cat
Man

User-defined class objects in Java ArrayList

Let’s see an example where we are storing Student class object in an array list.

class Student{ 

  int rollno; 

  String name; 

  int age; 

  Student(int rollno,String name,int age){ 

   this.rollno=rollno; 

   this.name=name; 

   this.age=age; 

  } 

} 

import java.util.*; 

 class ArrayList5{ 

 public static void main(String args[]){ 

  //Creating user-defined class objects 

  Student s1=new Student(101,"Harun",20); 

  Student s2=new Student(102,"Md",21); 

  Student s2=new Student(103,"Paru",22); 

  //creating arraylist 

  ArrayList<Student> al=new ArrayList<Student>(); 

  al.add(s1);//adding Student class object 

  al.add(s2); 

  al.add(s3); 

  //Getting Iterator 

  Iterator itr=al.iterator(); 

  //traversing elements of ArrayList object 

  while(itr.hasNext()){ 

    Student st=(Student)itr.next(); 

    System.out.println(st.rollno+" "+st.name+" "+st.age); 

  } 

 } 

}

Output:

101 Harun 20
102 Md 21
103 Paru 22

Java ArrayList Serialization and Deserialization Example

Let’s see an example to serialize an ArrayList object and then deserialize it.

import java.io.*; 

import java.util.*; 

 class ArrayList6 { 
        public static void main(String [] args) 
        { 
          ArrayList<String> list=new ArrayList<String>(); 
          list.add("R");   
          list.add("V");   
          list.add("A");    
          try 
          { 
              //Serialization 

              FileOutputStream foslist=new FileOutputStream("file"); 

              ObjectOutputStream ooslist =new ObjectOutputStream(fos); 

              ooslist.writeObject(list); 

              foslist.close(); 

              ooslist.close(); 

              //Deserialization 

              FileInputStream fislist=new FileInputStream("file"); 

              ObjectInputStream oislist=new ObjectInputStream(fislist); 

            ArrayList  alist=(ArrayList)oislist.readObject(); 

            System.out.println(alist);   

          }catch(Exception e) 

          { 
              System.out.println(e); 
          } 

       } 

    }

Output:

[R, V, A]

Java ArrayList example to add elements

Here, example code of different ways to add an element.

import java.util.*; 

 class ArrayList7{ 

 public static void main(String args[]){ 

  ArrayList<String> list =new ArrayList<String>(); 

           System.out.println("Initial list of elements: "+ list); 

           //Adding elements to the end of the list 

           list.add("R"); 

           list.add("V"); 

           list.add("A"); 

           System.out.println("After invoking add(E e) method: "+ list); 

           //Adding an element at the specific position 

           list.add(1, "G"); 

           System.out.println("After invoking add(int index, E element) method: "+al); 

           ArrayList<String> list2=new ArrayList<String>(); 

           list2.add("S"); 

           list2.add("H"); 

           //Adding second list elements to the first list 

           list2.addAll(list2); 

           System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ list); 

           ArrayList<String> list3=new ArrayList<String>(); 

           list3.add("J"); 

           list3.add("R"); 

           //Adding second list elements to the first list at specific position 

           list.addAll(1, list3); 

           System.out.println("After invoking addAll(int index, Collection<? extends E> c) method: "+ list);           

 } 

}

Output:

Initial list of elements: []
After invoking add(E e) method: [R, V, A]
After invoking add(int index, E element) method: [R, G, V, A]
After invoking addAll(Collection<? extends E> c) method:
[R, G, V, A, S, H]
After invoking addAll(int index, Collection<? extends E> c) method:
[R, J, R, G, V, A, S, H]

Java ArrayList example to remove elements

Here, we see different ways to remove an element.

import java.util.*; 

 class ArrayList8 { 
        public static void main(String [] args) 
        { 
          ArrayList<String> list=new ArrayList<String>(); 

          list.add("R");   

          list.add("V");   

          list.add("A");  

          list.add("A"); 

          list.add("G"); 

          System.out.println("An initial list of elements: "+ list);  

          //Removing specific element from arraylist 

          list.remove("V"); 

          System.out.println("After invoking remove(object) method: "+ list);  

          //Removing element on the basis of specific position 

          list.remove(0); 

          System.out.println("After invoking remove(index) method: "+ list);             

          //Creating another arraylist 

          ArrayList<String> list2=new ArrayList<String>();   

          list2.add("R");   

          list2.add("H");   

          //Adding new elements to arraylist 

          list2.addAll(list2); 

          System.out.println("Updated list : "+ list);  

          //Removing all the new elements from arraylist 

          list.removeAll(list2); 

          System.out.println("After invoking removeAll() method: "+ list);  

          //Removing elements on the basis of specified condition 

          list.removeIf(str -> str.contains("A"));   //This is Lambda expression  

          System.out.println("After invoking removeIf() method: "+ list); 

          //Removing all the elements available in the list 

          list.clear(); 

          System.out.println("After invoking clear() method: "+ list);  

       } 

    }

Output:
An initial list of elements: [R, V, A, A, G]
After invoking remove(object) method: [R, A, A, G]
After invoking remove(index) method: [A, A, G]
Updated list : [A, A, G, R, H]
After invoking removeAll() method: [A, A, G]
After invoking removeIf() method: [A, G]
After invoking clear() method: []

Part 24: List of Java Keywords with real Example

Part 14: Date and Time in Java with real time Example.

 Date and Time in Java

Example of Constructor

  1. Date( ) this constructor initializes the object with the current date and time.
  2. Date(long millisec) this constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.

Following are the some methods of the date class.

Method Description
boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
Object clone( ) Duplicates the invoking Date object.
int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
long getTime( ) Returns the number of milliseconds that have elapsed since May 1, 2020.
int hashCode( ) Returns a hash code for the invoking object.
void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, May 1, 2020.
String toString( ) Converts the invoking Date object into a string and returns the result.

Getting Current Date and Time

This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows:

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // This statement Instantiate a Date object

      System.out.println(date.toString()); // display time and date using toString()

   }

}

This will produce the following result:

Output

Mon Jun 07 11:55:32 UTC 2021

Date Comparison

Following are the three ways to compare two dates:

  • Method getTime( ) to obtain the number of milliseconds that have passed since midnight, June 1, 2021, for both objects and then compare these two values.
  • methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 21).before(new Date (99, 2, 21)) returns true.
  • Method compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Format Using SimpleDateFormat class:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.  This class allows you to start by choosing any user-defined patterns for date-time formatting.

Example

import java.util.*;

import java.text.*;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date dNow = new Date( );

      SimpleDateFormat ft =

      new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + ft.format(dNow));

   }

}

This will produce the following result:

Output

Current Date: Mon 2021.06.07 at 01:04:15 PM UTC

Simple DateFormat Format Codes

In order to specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:

Character            Description 
G             Era designator, Example: AD
y              Year in four digits, Example: 2001
M            Month in year,  Example: July or 07
d             Day in month,    Example: 10
h             Hour in A.M./P.M. (1~12) Example:12
H             Hour in day (0~23), Example:22
m            Minute in hour  30, Example:
s              Second in minute, Example:55
S              Millisecond Example:234
E              Day in week Example:Tuesday
D             Day in year Example:360
F              Day of week in month    Example:2 (second Wed. in July)
w            Week in year      Example:40
W            Week in month Example:1
a              A.M./P.M. marker           Example:PM
k              Hour in day (1~24)           Example:24
K             Hour in A.M./P.M. (0~11)             Example:10
z              Time zone           Example:Eastern Standard Time
‘               Escape for text  Delimiter
”              Single quote       `

Date Format Using printf

Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // Instantiate a Date object

      String str = String.format("Current Date/Time : %tc", date );       // display time and date

      System.out.printf(str);

   }

}

This will produce the following result −

Output

Current Date/Time : Mon Jun 07 13:08:21 UTC 2021

It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $.

Example

import java.util.Date;

public class DateDemo {

   public static void main(String args[]) {    

      Date date = new Date();// Instantiate a Date object      

      System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);// display time and date

   }

}

This will produce the following result:

Output

Due date: June 07, 2021

Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // This statement Instantiate a Date object

      System.out.printf("%s %tB %<te, %<tY", "Due date:", date); // This statement display formatted date

   }

}

This will produce the following result −

Output

Due date: June 7, 2021

Date and Time Conversion Characters

Character Description
c Complete date and time; Example: Mon May 04 09:51:52 CDT 2009
F ISO 8601 date
D U.S. formatted date (month/day/year). Example: 02/09/2004
T 24-hour time
r 12-hour time
R 24-hour time, no seconds. Example:
Y Four-digit year (with leading zeroes). Example:
y Last two digits of the year (with leading zeroes). Example:
C First two digits of the year (with leading zeroes)
B Full month name
b Abbreviated month name
m Two-digit month (with leading zeroes)
d Two-digit day (with leading zeroes)
e Two-digit day (without leading zeroes)
A Full weekday name
a Abbreviated weekday name. Example:
j Three-digit day of year (with leading zeroes) . Example:
H Two-digit hour (with leading zeroes), between 00 and 23
k Two-digit hour (without leading zeroes), between 0 and 23
I Two-digit hour (with leading zeroes), between 01 and 12
l Two-digit hour (without leading zeroes), between 1 and 12
M Two-digit minutes (with leading zeroes) . Example:
S Two-digit seconds (with leading zeroes)
L Three-digit milliseconds (with leading zeroes)
N Nine-digit nanoseconds (with leading zeroes)
P Uppercase morning or afternoon marker
p Lowercase morning or afternoon marker
z RFC 822 numeric offset from GMT
Z Time zone
s Seconds since 1970-01-01 00:00:00 GMT. Example:
Q Milliseconds since 1970-01-01 00:00:00 GMT. Example:

There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation.

Parsing Strings into Dates

The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.

Example

import java.util.*;

import java.text.*;

public class DateDemo {

public static void main(String args[]) {

SimpleDateFormat ft = new SimpleDateFormat (“yyyy-MM-dd”);

String input = args.length == 0 ? “1818-11-11″ : args[0];

System.out.print(input + ” Parses as “);

Date t;

try {

t = ft.parse(input);

System.out.println(t);

} catch (ParseException e) {

System.out.println(“Unparseable using ” + ft);

}

}

}

A sample run of the above program would produce the following result −

Output

1818-11-11 Parses as Wed Nov 11 00:00:00 UTC 1818

Sleep for a While

You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds −

Example

import java.util.*;

public class SleepDemo {

public static void main(String args[]) {

try {

System.out.println(new Date( ) + “\n”);

Thread.sleep(5*60*10);

System.out.println(new Date( ) + “\n”);

} catch (Exception e) {

System.out.println(“Got an exception!”);

}

}

}

This will produce the following result:

Output

Mon Jun 07 13:13:30 UTC 2021

Mon Jun 07 13:13:33 UTC 2021

Measuring Elapsed Time

Sometimes, you may need to measure point in time in milliseconds. So let’s re-write the above example once again −

Example

import java.util.*;

public class DiffDemo {

public static void main(String args[]) {

try {

long start = System.currentTimeMillis( );

System.out.println(new Date( ) + “\n”);

 

Thread.sleep(5*60*10);

System.out.println(new Date( ) + “\n”);

 

long end = System.currentTimeMillis( );

long diff = end – start;

System.out.println(“Difference is : ” + diff);

} catch (Exception e) {

System.out.println(“Got an exception!”);

}

}

}

This will produce the following result :

Output

Mon Jun 07 13:14:57 UTC 2021

Mon Jun 07 13:15:00 UTC 2021

Difference is : 3036

GregorianCalendar Class

GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. We did not discuss Calendar class in this tutorial, you can look up standard Java documentation for this. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar. There are also several constructors for GregorianCalendar objects:

Constructor Description
GregorianCalendar() This Constructor constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date) This Constructor constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute) This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(Locale aLocale) This Constructor constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone zone) This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
GregorianCalendar(TimeZone zone, Locale aLocale) This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Here is the list of few useful support methods provided by GregorianCalendar class:

Method Description
void add(int field, int amount) Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules.
protected void computeFields() Converts UTC as milliseconds to time field values.
protected void computeTime() Overrides Calendar Converts time field values to UTC as milliseconds.
boolean equals(Object obj) Compares this GregorianCalendar to an object reference.
int get(int field) Gets the value for a given time field.
int getActualMaximum(int field) Returns the maximum value that this field could have, given the current date.
int getActualMinimum(int field) Returns the minimum value that this field could have, given the current date.
int getGreatestMinimum(int field) Returns highest minimum value for the given field if varies.
Date getGregorianChange() Gets the Gregorian Calendar change date.
int getLeastMaximum(int field) int getLeastMaximum(int field) Returns lowest maximum value for the given field if varies.
int getMaximum(int field) Returns maximum value for the given field.
Date getTime() Gets this Calendar’s current time.
long getTimeInMillis() Gets this Calendar’s current time as a long.
TimeZone getTimeZone() Gets the time zone.
int getMinimum(int field) Returns minimum value for the given field.
int hashCode() Overrides hashCode.
boolean isLeapYear(int year) Determines if the given year is a leap year.
void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
void set(int field, int value) Sets the time field with the given value.
void set(int year, int month, int date) Sets the values for the fields year, month, and date.

Example

import java.util.*;

public class ExampleGregorianCalendarDemo {

public static void main(String args[]) {

String months[] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”,

“Oct”, “Nov”, “Dec”};

int year;   // Create a Gregorian calendar initialized  with the current date and time in the default timezone.

GregorianCalendar gcalendar = new GregorianCalendar();

System.out.print(“Date: “);// Display current time and date information.

System.out.print(months[gcalendar.get(Calendar.MONTH)]);

System.out.print(” ” + gcalendar.get(Calendar.DATE) + ” “);

System.out.println(year = gcalendar.get(Calendar.YEAR));

System.out.print(“Time: “);

System.out.print(gcalendar.get(Calendar.HOUR) + “:”);

System.out.print(gcalendar.get(Calendar.MINUTE) + “:”);

System.out.println(gcalendar.get(Calendar.SECOND));

if(gcalendar.isLeapYear(year)) { // Test if the current year is a leap year

System.out.println(“The current year is a leap year”);

}else {

System.out.println(“The current year is not a leap year”);

}

}

}

This will produce the following result −

Output

Date: Jun 7 2021
Time: 1:16:54
The current year is not a leap year

For a complete list of constant available in Calendar class, you can refer the standard Java documentation.

Java Dates does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:

  • LocalDate class: Represents a date (year, month, day (yyyy-MM-dd))
  • LocalTime class: Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
  • LocalDateTime  class: Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
  • DateTimeFormatter class:Formatter for displaying and parsing date-time objects

If you don’t know what a package is, read our Java Packages article .

Current Date

To display the current date, import the java.time. LocalDate class, and use its now() method:

Example

import java.time.LocalDate; // import the LocalDate class

public class ExampleMain {

  public static void main(String[] args) {

    LocalDate myObj = LocalDate.now(); // This is Create a date object

    System.out.println(myObj); // This is Display the current date

  }

}

The output will be:

2021-06-07

Current Time 

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:

Example

import java.time.LocalTime; // This is import the LocalTime class

public class ExapleMain {

  public static void main(String[] args) {

    LocalTime myObj = LocalTime.now();

    System.out.println(myObj);

  }

}

The output will be:

14:47:34.528

Display Current Date and Time

In order to display the current date and time, import the java.time.LocalDateTime class, and use its now() method:

Example

import java.time.LocalDateTime; // import the LocalDateTime class

public class ExampleMain {

public static void main(String[] args) {

LocalDateTime myObj = LocalDateTime.now();

System.out.println(myObj);

}

}

The output will be:

2021-06-07T14:48:24.914

Formatting Date and Time

The “T” in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the “T” and nanoseconds from the date-time:

Example

import java.time.LocalDateTime; // This Import the LocalDateTime class

import java.time.format.DateTimeFormatter; //This Import the DateTimeFormatter class

public class ExampleMain {

  public static void main(String[] args) {

    LocalDateTime myDateObj = LocalDateTime.now();

    System.out.println("Before formatting: " + myDateObj);

    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    String formattedDate = myDateObj.format(myFormatObj);

    System.out.println("After formatting: " + formattedDate);

  }

}

output:

Before formatting: 2021-06-07T14:50:38.049
After formatting: 07-06-2021 14:50:38

The ofPattern() method receive all of values, if you want to display the date and time in a different format. For example:

Value

yyyy-MM-dd      Example:  “2020-05-29″

dd/MM/yyyy     Example:”29/05/2020″

dd-MMM-yyyy Example:”29-May -2020″

E, MMM dd yyyy  Example:”Thu, May 29 2020”

Part 24: List of Java Keywords with real Example

Part 13: User input in java with real time example code

Java User Input

The Scanner class is used to get user input and is the easiest way to read input in Java program. Java Scanner class permits the user to take input from the console. The class is belongs to java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte.

Syntax

Scanner sc=new Scanner(System.in);

The above statement creates a constructor of the Scanner class having System.in as an argument. it is going to read from the standard input stream of the program taking input from the console. The java.util package should be import while using Scanner class. It also converts the Bytes that is  from the input stream into characters using the platform’s default charset.

The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.

Advantages of Using Scanner

  • Easy to use the Scanner class.
  • Easy input of numbers (int, short, byte, float, long and double).
  • Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
  • Is able to read lines, white spaces, and regex-delimited tokens

In order to use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

Example

import java.util.Scanner;  // This statement is Import the Scanner class
class ExampleMain {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);  // This statement is Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine();  // This statement is Read user input
System.out.println("Username is: " + userName);  // This statement is Output user input
}
}

 

OUTPUT

Enter username
Harun
Username is: Harun

If you are not well known what a package is, read our Java Packages/API Tutorial.

Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

Method               Description
nextBoolean() It is used to scan Reads a Boolean value from the user
nextByte() It is used to scan Reads a byte value from the user
nextDouble() It is used to scan Reads a double value from the user
nextFloat() It is used to scan Reads a float value from the user
nextInt() It is used to scan Reads an int value from the user
nextLine() It is used to scan Reads a String value from the user
nextLong() It is used to scan Reads a long value from  the user
nextShort() It is used to scan Reads a short value from the user
int nextInt() It is used to scan the next token of the input as an integer.
nextBigInteger() It is used to scan the next token of the input as a BigInteger.
nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.

In the example below, we use different methods to read data of various types:

Example

import java.util.Scanner;
class ExampleMain {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name age and salary:");
String name = myObj.nextLine(); // This statement is String input
int age = myObj.nextInt(); // This statement is Numerical input
double salary = myObj.nextDouble();
System.out.println("Name: " + name); // This statement is Output input by user
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

 

OUTPUT

Enter name, age and salary:

Harun
22
40000

Name: Harun
Age: 22
Salary: 40000

Example of integer input from user. The following example allows user to read an integer form the System.in.

import java.util.*;
class ExampleMain
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);    //System.in is a standard input stream
System.out.print("Enter first number: ");
int a= sc.nextInt();
System.out.print("Enter second number:");
int b= sc.nextInt();
System.out.print("Enter third number: ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}

 

Output:

How to get input from user in Java

Example of String Input from user

Let’s see another example, in which we have taken string input.

import java.util.*;
class ExampleMain
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();              //This statement is read string
System.out.print("You have entered: "+str);
}
}

 

Output:

How to get input from user in Java. If you enter wrong input (for example, text in a numerical input), you will get an exception/error message ( such as “InputMismatchException”).

Part 24: List of Java Keywords with real Example

Part 7: Java Inheritance with real time example

Java Inheritance

Subclass and Superclass contains in inheritance mainly. In Java, it is possible to inherit attributes and methods from one class to another.  It contains of two categories:

subclass (child) – the class that inherits from another class

superclass (parent) – the class being inherited from

To inherit from a class, use the extends keyword. In the example below, the Car class (subclass) inherits the attributes and methods from the Vehicle class (superclass):

Example

class Tree {
protected String leavesColor = “Green”;        // attribute
public void branch() {                    // method
System.out.println(“Tree !”);
}
}
class Fruits extends Tree {
private String fruitsName = “Mango”;    // attribute
public static void main(String[] args) {
// Create a myFruit object
Fruits myFruits = new Fruits();
// Call the () method (from the Vehicle class) on the myCar object
myFruits.branch ();
// Display the value of the brand attribute (from the Tree class) and the value of the fruitsName from the Fruits class
System.out.println(myFruits.branch + ” ” + myCar.fruitsName);
}
}

Did you notice the protected modifier in Vehicle? Here, set the brance attribute in Tree to a protected access modifier. If it was set to private, the Fruits class would not be able to access it. Why and when to Use “Inheritance”? It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.

The final Keyword

If you don’t want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Tree {

}
class Fruits extends Tree {

}
The output will be something like this:

Main.java:9: error: cannot inherit from final Tree
class Main extends Tree {
^
1 error)

Java inheritance refers to the capability in Java for one class to inherit from another class. In Java this is also called extending a class. One class can extend another class and thereby inherit from that class. When one class inherits from another class in Java, the two classes take on certain roles. The class that extends (inherits from another class) is the subclass and the class that is being extended (the class being inherited from) is the superclass. In other words, the subclass extends the superclass. Or, the subclass inherits from the superclass. Another commonly used term for inheritance is specialization and generalization. A subclass is a specialization of a superclass, and a superclass is a generalization of one or more subclasses.

Inheritance is a Method of Code Reuse:  Inheritance can be an effective method to share code between classes that have some traits in common, yet allowing the classes to have some parts that are different.

Class Hierarchies

In java, Superclasses and subclasses form an inheritance structure which is also called a class hierarchy. At the top of the class hierarchy you have the superclasses. At the bottom of the class hierarchy you have the subclasses. A class hierarchy may have multiple levels, meaning multiple levels of superclasses and subclasses. A subclass may itself be a superclass of other subclasses etc.

Java Inheritance Basics

When a class inherits from a superclass, it inherits parts of the superclass methods and fields. The subclass can also override (redefine) the inherited methods. Fields cannot be overridden, but can be “shadowed” in subclasses. How all this works is covered later in this text.

What is Inherited?

When a subclass extends a superclass in Java, all protected and public fields and methods of the superclass are inherited by the subclass. By inherited is meant that these fields and methods are part of of the subclass, as if the subclass had declared them itself. protected and public fields can be called and referenced just like the methods declared directly in the subclass.

Fields and methods with default (package) access modifiers can be accessed by subclasses only if the subclass is located in the same package as the superclass. Private fields and methods of the superclass can never be referenced directly by subclasses. They can, however, be referenced indirectly via methods reachable from the subclass e.g default (package), protected and public methods. Constructors are not inherited by subclasses, but a subclass constructor must call a constructor in the superclass. This will be explained in detail in a later section.

Java Only Supports Singular Inheritance

The Java inheritance mechanism only allows a Java class to inherit from a single superclass (singular inheritance). In some programming languages, like C++, it is possible for a subclass to inherit from multiple superclasses (multiple inheritance). Since multiple inheritance can create some weird problems, if e.g., the superclasses contain methods with the same names and parameters, multiple inheritance was left out in Java.

Declaring Inheritance in Java

In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition. Here is Java inheritance example using the extends keyword:

public class Tree {
protected String color = null;
public void colorSet (String colors) {
this.color = colors;
}
}
public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOftree() {
return this. numberOftree;
}
}

The Fruits class in this example extends the Tree class, meaning the Fruits class inherits from the Tree class. Because the Fruits class extends the Tree class, the protected field numberOftree from the Tree class is inherited by the Fruits class. When the numberOftree field is inherited, it is accessible inside a Fruits instance. The numberOftree field is not actually being referenced from the Fruits class in the code above, but it could if we wanted to. Here is an example that shows how that could look:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}

The referencing happens inside the getnumberOftree () method. In many cases it would have made sense to place the getnumberOftree () method in the Tree class where the numberOftree field is located. I just placed the getnumberOftree () method in the Fruits class to show that it is possible.

Inheritance and Type Casting

It is possible to reference a subclass as an instance of one of its superclasses. For instance, using the class definitions from the example in the previous section it is possible to reference an instance of the Fruits class as an instance of the Tree class. Because the Fruits class extends (inherits from) the Tree class, it is also said to be a Tree. Here is a Java code example:

Fruits    f     = new Fruits ();
Tree tree = f;

First a Fruits  instance is created. Second, the Fruits  instance is assigned to a variable of type Tree. Now the Tree variable (reference) points to the Fruits  instance. This is possible because the Fruits class inherits from the Tree class.Because, it is possible to use an instance of some subclass as if it were an instance of its superclass. That way, you don’t need to know exactly what subclass the object is an instance of. You could treat e.g. Fruits instances as Tree instances.

The process of referencing an object of class as a different type than the class itself is called type casting. You cast an object from one type to another.

Upcasting and Downcasting

You can always cast an object of a subclass to one of its superclasses. This is referred to as upcasting (from a subclass type to a superclass type).

It may also be possible to cast an object from a superclass type to a subclass type, but only if the object really is an instance of that subclass (or an instance of a subclass of that subclass). This is referred to as downcasting (from a superclass type to a subclass type). Thus, this example of downcasting is valid:

Fruits    f     = new Fruits ();
// upcast to Tree
Tree tree = f;
// downcast to f again
Fruits    f     = (Fruits)tree;

However, the following downcast example is not valid. The Java compiler will accept it, but at runtime when this code is executed the code will throw a ClassCastException.

Truck   truck   = new Truck();
// upcast to Tree
Tree tree = truck;
// downcast to f again
Fruits    f     = (Fruits) tree;

The Truck object can be upcast to a Tree object, but it cannot be downcast to a Fruits object later. This will result in a ClassCastException.

Overriding Methods

In a subclass you can override or redefine the methods defined in the superclass. Here is a Java method override example:
public class Tree {
String treePlate = null;
public void setLicensePlate(String treePlate) {
this. treePlate = treePlate;
}
}
public class Fruits extends Tree {
public void settreePlate (String treeP) {
this.treePlate = treeP.toLowerCase();
}
}

Notice how both the Vehicle class and the Car class defines a method called settreePlate (). Now, whenever the settreePlate () method is called on a Fruits object, it is the method defined in the Fruits class that is called. The method in the superclass is ignored.

To override a method the method signature in the subclass must be the same as in the superclass. That means that the method definition in the subclass must have exactly the same name and the same number and type of parameters, and the parameters must be listed in the exact same sequence as in the superclass. Otherwise the method in the subclass will be considered a separate method.

In Java you cannot override private methods from a superclass. If the superclass calls a private method internally from some other method, it will continue to call that method from the superclass, even if you create a private method in the subclass with the same signature.

The @override Annotation

If you override a method in a subclass, and the method is accidently removed or modified in the superclass, the method in the subclass no longer overrides the method in the superclass. But how do you know? It would be nice if the compiler could tell you that the method being overridden no longer overrides a method in the superclass, right?

This is what the Java @override annotation is for. You place the Java @override annotation above the method that overrides a method in a superclass. Here is Java @override example:

public class Fruits extends Tree {
@Override
public void settreePlate (String treeP) {
this.treePlate= treeP.toLowerCase();
}
}

Calling Superclass Methods

If you override a method in a subclass, but still need to call the method defined in the superclass, you can do so using the super reference, like this:

public class Fruits extends Tree {
public void settreePlate (String treeP) {
super.settreePlate (treeP);
}
}

In the above code example the method settreePlate() in the Car class, calls the settreePlate() method in the Tree class. You can call superclass implementations from any method in a subclass, like above. It does not have to be from the overridden method itself. For instance, you could also have called super.treePlate() from a method in the Car class called updatetreePlate() which does not override the settreePlate() method.

The instanceof Instruction

Java contains an instruction named instanceof. The instanceof instruction can determine whether a given object is an instance of some class. Here is a Java instanceof example:

Fruits f = new Fruits ();
boolean isFruits = f instanceof Fruits;

After this code has been executed the isFruits variable will contain the value true.
The instanceof instruction can also be used determine if an object is a instance of a superclass of its class. Here is an instanceof example that checks if a Car object is an instance of Vehicle:

Fruits f = new Fruits ();
boolean isTree = f instanceof Tree;

Assuming that the Fruits class extends (inherits from) the Tree class, the isTree variable will contain the value true after this code is executed. A Fruits object is also a Tree object because Fruits is a subclass of Vehicle.
As you can see, the instanceof instruction can be used to explore the inheritance hierarchy. The variable type used with the instanceof instruction does not affect its outcome. Look at this instanceof example:

Fruits f = new Fruits ();
Tree tree = f;
boolean isFruits  = tree instanceof Fruits;

Even though the tree variable is of type Tree, the object it ends up pointing to in this example is a Fruits object. Therefore the tree instanceof Fruits instruction will evaluate to true. Here is the same instanceof example, but using a Truck object instead of a Fruits object:

Truck truck = new Truck();
Tree tree = truck;
boolean isFruits = tree instanceof Fruits;

After executing this code the isFruits will contain the value false. The Truck object is not a Fruits object.

Fields and Inheritance

As mentioned earlier, in Java fields cannot be overridden in a subclass. If you define a field in a subclass with the same name as a field in the superclass, the field in the subclass will hide (shadow) the field in the superclass. If the subclass tries to access the field, it will access the field in the subclass. If, however, the subclass calls up into a method in the superclass, and that method accesses the field with the same name as in the subclass, it is the field in the superclass that is accessed. Here is Java inheritance example that illustrates how fields in subclasses shadow (hides) fields in superclasses:

public class Fruits extends Tree {
int numberOftree = 0;
public String getNumberOfTrees() {
return this. numberOftree;
}
public String getnumberOftrees () {
return this.numberOftree;
}
}
public class Tree {
String treeP = null;
public void settreeP(String treePlate) {
this. treePlate = treePlate;
}
public String getTreeP() {
return treeP;
}
}
public class Fruits extends Tree {
protected String treeP = null;
@Override
public void setTreeP(String tp) {
super.setTreeP(tp);
}
@Override
public String getTreeP () {
return super.getTreeP();
}
public void updateTreeP(String tp){
this.TreeP = tp;
}
}

Notice how both classes have a TreeP field defined. Both the Tree class and Fruits class has the methods setTreeP() and getTreeP(). The methods in the Fruits class calls the corresponding methods in the Tree class. The result is, that eventually both set of methods access the treeP field in the Tree class.

The updateTreeP() method in the Car class however, accesses the treeP field directly. Thus, it accesses the treeP field of the Fruits class. Therefore, you will not get the same result if you call setTreeP() as when you call the updateTree() method.

Look at the following lines of Java code:
Fruits f = new Fruits ();
f.setTreeP(“123”);

car.updateTreeP(“abc”);

System.out.println(“tree p: ” + f.getTreeP ());

This Java code will print out the text 123.

The updateTreeP () method sets the license plate value on the TreeP field in the Fruits class. The getTreeP() method, however, returns the value of the TreeP field in the Tree class. Therefore, the value 123 which is set as value for the TreeP field in the Vehicle class via the setTreeP() method, is what is printed out.

Constructors and Inheritance

The Java inheritance mechanism does not include constructors. In other words, constructors of a superclass are not inherited by subclasses. Subclasses can still call the constructors in the superclass using the super() contruct. In fact, a subclass constructor is required to call one of the constructors in the superclass as the very first action inside the constructor body. Here is how that looks:

public class Tree {
public Tree() {
}
}
public class Fruits extends Tree{
public Fruits() {
super();
//perform other initialization here
}
}

Notice the call to super() inside the Car constructor. This super() call executes the constructor in the Vehicle class. You may have seen Java classes where the subclass constructors did not seem to call the constructors in the superclass. Maybe the superclass did not even have a constructor. However, the subclass constructors have still called superclass constructors in those case. You just could not see it. Let me explain why: If a class does not have any explicit constructor defined, the Java compiler inserts an implicit non arg constructor. Thus, a class always has a constructor. Therefore, the following version of Vehicle is equivalent to the version shown just above:
public class Tree {

}

Second, if a constructor does not explicitly call a constructor in the superclass, the Java compiler inserts an implicit call to the no-arg constructor in the superclass. That means that the following version of the Car class is actually equivalent to the version shown earlier:
public class Fruits extends Tree {
public Fruits () {
}
}

In fact, since the constructor is now empty, we could leave it out and the Java compiler would insert it, and insert an implicit call to the non arg constructor in the superclass. This is how the two classes would look then:
public class Tree {

}

public class Fruits extends Tree{

}

Even though no constructors are declared in these two classes, they both get a no-arg constructor, and the no-arg constructor in the Fruits class will call the no-arg constructor in the Vehicle class.

If the Tree class did not have a no-arg constructor, but had another constructor which takes parameters, the Java compiler would complain. The Fruits class would then be required to declare a constructor, and inside that constructor call the constructor in the Vehicle class.

Nested Classes and Inheritance

The same Java inheritance rules apply to nested classes. Nested classes which are declared private are not inherited. Nested classes with the default (package) access modifier are only accessible to subclasses if the subclass is located in the same package as the superclass. Nested classes with the protected or public access modifier are always inherited by subclasses.

Here is a nested class inheritance example:
class FruitsClass {
class MyFruitsClass {
}
}

public class MyFruitsSubclass extends MyFruitsClass {
public static void main(String[] args) {
MyFruitsSubclass subclass = new MyFruitsSubclass();
MyFruitsClass nested =  subclass.new MyFruitsClass ();
}
}

Notice how it is possible to create an instance of the nested class MyFruitsClass which is defined in the superclass (MyFruitsClass) via a reference to the subclass (MyFruitsSubclass). Final Classes and Inheritanc. A class can be declared final. Here is now that looks:
public final class MyFruitsClass {
}

A final class cannot be extended. In other words, you cannot inherit from a final class in Java.

Part 24: List of Java Keywords with real Example

Part 12: Enums in java with uses example code.

Enums in java

An enum is a group of constants. To create an enum, use the enum keyword instead of class or interface. Also separate the constants with a comma. It is use when you have values that you know aren’t going to change such as month days, days, colors, deck of cards, etc. They should be in uppercase letters:

Example
enum Days {
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

You can access enum constants with the dot syntax:

Days myVar = Days.MON;
Enum is short for “enumerations”, which means “specifically listed”. Enum inside a Class example:

Example

public class Month

{
enum Level

{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

public static void main(String[] args)

{
Days myVar = Days.MON;
System.out.println(myVar);
}
}

The output will be:

MON

Enums in a Switch Statement:

Enums are often used in switch statements to check for corresponding values:

Example
enum Level

{
SAT,
SUN,
MON,
TUE,
WED,
THU,
FRI
}

public class Main {
public static void main(String[] args) {
Days myVar = Days.MON;

switch(myVar) {
case SAT:
System.out.println("This is Saturday");
break;
case MON:
System.out.println("This is Monday");
break;
case SUN:
System.out.println("This is Sunday");
break;
}
}
}

 

The output will be:

This is Monday

Loop Through an Enum:

The enums type has a values() method where they returns an array of all enums constants. This method is useful when you want to loop through the constants of an enums:

Example
for (Days myVar : Days.values()) {
System.out.println(myVar);
}
The output will be:

SAT
SUN
MON

Difference between Enums and Classes

An enums is like a class which have attributes and methods. The only difference is that enum constants are public, static and final that is unchangeable also cannot be overridden. An enum cannot be used to create objects, and it cannot extend other classes though it can implement interfaces.

Part 24: List of Java Keywords with real Example

Java 6: Java Packages and API in programming

Java Packages & API

In Java, a package is group related classes or a folder in a path (file directory).  Generally, packages are used to avoid name conflicts and to write a better supportable code.

Packages are divided into two categories:

  1. User-defined Packages (create your own packages)
  2. Built-in Packages (packages from the Java API)

Built-in Packages

The Java API is a library of classes free to use in the Java Development Environment. The library contains components for input, database, programming and so on.

For more details, application programming interface (API) is a list of all classes. These classes are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, with their methods, fields, and constructors. These are pre-written classes provide a great amount of functionality to a programmer. A programmer should be aware of these classes and should know how to use them.

Some examples of Java API can be found at Oracle’s website: http://docs.oracle.com/javase/7/docs/api/.

In order to use a class from Java API, one needs to include an import statement at the start of the program.

The API library is divided into packages and classes either import a single or a whole package. When import single package contain class along with its methods and attributes. Also, for a whole package import, contain all the classes that belong to the definite package. To use a class or a package from the library, you need to use the import keyword such as Syntax

import package.name.Class;   //for  import a single class

import package.name.*;   //for import the whole package

Import a Class

When want to use a class, for sample, Scanner class, which is used to get user input, example code:
Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package. In order to use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.

What is util?

In Java Package java.util Contains the collections framework, legacy of the collection of various classes, event model, date and time facilities, internationalization, and miscellaneous utility classes,  for example, a string tokenizer, a random-number generator, and a bit array.

In our example, we will use the nextLine() method, which is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class Sclass {

  public static void main(String[] args) {

    Scanner sObj = new Scanner(System.in);

    System.out.println("Enter User name");

    String userName = sObj.nextLine();

    System.out.println("Username is: " + userName);

  }

}

OUTPUT

Enter username

hey

Username is: hey

Java Application Programming Interface (API)

For example, in order to use the Scanner class, which allows a program to accept input from the keyboard, one must include the following import statement:

import java.util.Scanner;

The above import statement allows the programmer to use any method listed in the

Scanner class. Another choice for including the import statement is the wildcard option

shown below:

import java.util.*;

This version of the import statement imports all the classes in the API’s java.util package and makes them available to the programmer. If check the API and look at the classes written in the java.util package, you will observe that it includes some of the classes that are used often, such as Arrays, ArrayList, Formatter, Random, and many others. Another Java package that has several commonly used classes is the java.lang package. This package includes classes that are fundamental to the design of Java language. The java.lang package is automatically imported in a Java program and does not need an explicit import statement.

Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes. To import a whole package, end the sentence with an asterisk sign (*). The below example will import all the classes in the java.util package:

Example

import java.util.*;

User-defined Packages

To create own package, Java uses a file system directory to store them. Just like folders on a computer:

Example

└── root

└── mypack

└── MyPackClass.java

To create a package, use the package keyword:

MyPackClass.java

package mypack;

class MyPackClass {

  public static void main(String[] args) {

    System.out.println("Oh! This is my package !");

  }

}

Save the file as MyPackageClass.java, and compile it:

C:\Users\Pc Name>javac MyPackClass.java

Then compile the package:

C:\Users\ Pc Name>javac -d. MyPackClass.java

From this path create notepad to practice your java code until expert.

Part 24: List of Java Keywords with real Example

Part 4: Java Scope and Recursion use with Example.

Java Scope and Recursion use

Java Scope

In Java, variables are only accessible inside the region they are created. This is called scope.In Method Scope Variables declared directly inside a method.

Example

public class Tree{
public static void main(String[] args) {

// Code here CANNOT use numTree

int numTree = 100;

// Code here can use numTree
System.out.println(numTree );
}
}

output

100

Besides, Block Scope means a block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces.

Example

public class Tree{
public static void main(String[] args) {

// Code here CANNOT use numTree

{ // This is a block

// Code here CANNOT use numTree

int numTree = 100;

// Code here CAN use numTree
System.out.println(numTree );

} // The block ends here

// Code here CANNOT use numTree

}
}
output

100

Java Recursion

In, java programming the technique of making a function call itself is Recursion. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.

Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:

Example

//Use recursion to add all of the numbers up to 10.

public class Tree {
public static void main(String[] args) {
int result = sum(5);
System.out.println(result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}

output

15

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:

5 + sum(4)
5 + ( 4 + sum(3) )
5 + ( 4 + ( 3 + sum(2) ) )

5 + 4 + 3 + 2 + 1 + sum(0)
5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.

Halting Condition

In java, like loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when end is not greater than start:

Example
Use recursion to add all of the numbers between 5 to 10.

public class Tree {
public static void main(String[] args) {
int result = sumTree(5, 10);
System.out.println(result);
}
public static int sumTree(int start, int end) {
if (end > start)
{
return end + sumTree(start, end - 1);
}
else
{
return end;
}
}
}

output

45

 Factorial of a Number Using Recursion

#Factorial of a Number Using Recursion in java
public class Factorial {

    public static void main(String[] args) {
        int num = 6;
        long factorial = multiplyNumbers(num);
        System.out.println("Factorial of " + num + " = " + factorial);
    }
    public static long multiplyNumbers(int num)
    {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}

Output

Factorial of 6 = 720

Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument.

Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed. Since, it is called from the same function, it is a recursive call.

In each recursive call, the value of argument num is decreased by 1 until num reaches less than 1.

When the value of num is less than 1, there is no recursive call.

And each recursive calls returns giving us:

6 * 5 * 4 * 3 * 2 * 1 * 1 (for 0) = 720.

Draftsbook is a learning base blog. The blog share Article series based on Subject. For example:

    1. JAVA : JAVA  is a object-oriented programming(OOP) language. This language classes and objects are the two main aspects of OOP. The blog content discuss below principles of OOP:
      1. Encapsulation
      2. Inheritance
      3. Abstraction
      4. Polymorphism
  1. Data Structure: Data structure refers a several way of organizing data in a computer system.
  2. Android : Android software development  apps can be written using Kotlin, Java, and C++ languages” using the Android software development kit (SDK). This blog contains  android feature Navigation drawer implementation and its usage are mention.
  3. IELTS : IELTS  Four module with strategies are written hereby

5.Problem Solving : Problem solution on various online platform tips and solution are given here following platform.

Part 24: List of Java Keywords with real Example

Part 1: Java OOP and its feature with example

What is Java OOP?

OOP stands for Object-Oriented Programming where java is a procedural programming. It is about writing procedures or methods to perform operations on the data. OOP is concerns creating objects that contain both data and methods.

Draftsbook goals For JAVA Teach:

  1. Java OOP 
  2. Classes and objects
  3. Class Attributes
  4. Class Methods
  5. Method Parameters
  6. Method Overloading
  7. Scope
  8. recursion
  9. Constructor
  10. Modifiers
  11. Encapsulation
  12. Packages or API
  13. Inheritance
  14. Polymorphism
  15. Inner class
  16. Abstraction
  17. Interface
  18. Enums
  19. User Input
  20. Date and Time
  21. ArrayList
  22. LinkedList
  23. HashSet
  24. Iterator
  25. Wrapper Class
  26. Exceptions
  27. Threads
  28. Lambda
  29. Create read write file or Java File Handling 
  30. Keyword
  31. string Methods
  32. String, StringBuffer and StringBuilder
  33. Overload vs Override

Object-oriented programming (OOP) has several advantages over procedural programming:

  • is faster method or procedure
  • and easier to execute code
  • provides a clear structure for the programs
  •  helps to keep the Java code  easier to maintain, modify and debug
  •  makes it possible to create full reusable applications with less code and shorter development time.
  • easier to maintain flexibility.

What are Java Classes and Objects?

Classes and objects are the two main aspects of OOP (object-oriented programming). Look at the theoritical illustration to see the following  difference between class and objects:

class

  • Fruits

objects

  • Apple
  • Banana
  • Mango

So, a class is a frame for objects, and an object is an instance of that class. When the individual objects or a single object is created, they inherit all the variables and methods from the class. Actually verything in Java is associated with classes and objects, along with its attributes and methods. For a Everything in Java is associated with classes and objects, along with its attributes and methods. For a real life example , a Tree is an object.  example: leaves, leave_color, fruits_color etc are attributes of Tree.

Create a Class

To create a class, use the keyword”class”:
Tree.java
Create a class named “Tree” with a variable treeNumber:
public class Tree{
int treeNumber= 5;
}

Create an Object

In Java, an object is created from a class. We have already created the class named MyTreeClass, so now we can use this to create objects. To create an object of MyTreeClass, we specify the class name, followed by the object name, and use the keyword new:
Example

Create an object called “treeObj” and print the value of treeNumber:
public class Tree {
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj= new Tree();
System.out.println(treeObj.treeNumber );
}
}

Multiple Objects

You can create multiple objects of one class:
Example
Create two objects of Tree:
public class Tree {
int treeNumber = 5;
public static void main(String[] args)
{
Tree treeObj1 = new Tree();  // Object 1
Tree treeObj2 = new Tree();  // Object 2
System.out.println(treeObj1.treeNumber );
System.out.println(treeObj2.treeNumber );
}
}

Using Multiple Classes

Multiple Classes  means you can also create an object of a class and access the object in another class. This is frequently used for better decoration of classes. That is one class has all the attributes and methods, while the other class holds the main() method. Actually code to be executed. This is important to name the java file should be matched with the class name. In this example, we have created two files in the same directory/folder:

  1. Tree.java
  2. Treeotherclass.java

Tree.java

public class Tree
{
int treeNumber = 5;
}
Treeotherclass.java

class Treeotherclass {
public static void main(String[] args) {
Tree treeObj = new Tree();
System.out.println(treeObj.treeNumber );
}
}

Java Class Attributes

In the above class Tree.java we used the term “treeNumber ” for treeNumber in the example. It is actually an attribute of the class. Or you could define attribute as  class attributes are variables within a class.

Example
Create a class called “Tree ” with two attributes: treeNumber and treeNumber_2:
public class Main {
int treeNumber= 5;
int treeNumber_2= 3;
}

Another term for class attributes is fields.

Accessing Attributes

You can access attributes by creating an object of the class, and by using the dot syntax (.):
The following example will create an object of the Main class, with the name treeObj. We use the treeNumber attribute on the object to print its value:

Example

Create an object called “treeObj” and print the value of treeNumber :
public class Tree {
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj = new Tree ();
System.out.println(treeObj .treeNumber );
}
}

Modify Attributes

You can also modify attribute values:

Example
Set the value of treeNumber to 10:
public class Tree {
int treeNumber;
public static void main(String[] args) {
Tree myObj = new Tree();
treeObj.treeNumber = 10;
System.out.println(treeObj.treeNumber);
}
}

Or override existing values:

Example
Change the value of treeNumberto 20:
public class Tree{
int treeNumber = 10;
public static void main(String[] args) {
treeNumber treeObj = new treeNumber();
treeObj.treeNumber = 20; // treeNumber is now 20
System.out.println(treeObj.treeNumber);
}
}

Final keyword

If you don’t want the ability to override existing values, declare the attribute as final:

Example
public class Tree
{
final int treeNumber = 10;
public static void main(String[] args)
{
Tree treeObj = new Tree();
treeObj.treeNumber = 20; // will generate an error: cannot assign a value to a final variable
System.out.println(treeObj.treeNumber);
}
}

Multiple Objects

TO create multiple objects of one class, you can change the attribute values in one object, without changing the attribute values in the other:

Example
Change the value of treeNumber to 20 in treeObj2, and leave Tree in treeObj1 unchanged:
public class Tree
{
int treeNumber = 5;
public static void main(String[] args) {
Tree treeObj1 = new Tree();  // Object 1
Tree treeObj2 = new Tree();  // Object 2
treeObj2.treeNumber = 20;
System.out.println(treeObj1.treeNumber );  // Outputs 5
System.out.println(treeObj2.treeNumber );  // Outputs 20
}
}

Multiple Attributes

You can specify as many attributes as you want:

Example

public class Tree
{
String fname = “John”;
String lname = “Joe”;
int age = 21;
public static void main(String[] args) {
Tree myObj = new Tree();
System.out.println(“Name: ” + myObj.fname + ” ” + myObj.lname);
System.out.println(“Age: ” + myObj.age);
}
}

Java Constructors

In Java, a constructor is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Example
Create a constructor:
// Create a Main class
public class Tree
{
int treeNumber = 5;  // Create a class attribute
// Create a class constructor for the Main class
public Tree() {
treeNumber = 5;  // Set the initial value for the class attribute x
}
public static void main(String[] args) {
Tree myObj = new Tree(); // Create an object of class Tree. This will call the constructor.
System.out.println(myObj.x); // Print the value of treeNumber
}
}

// Outputs 5

It is keep to mind  that the constructor name must match the class name, and it cannot have a return type (like void). Also note that the constructor is called when the object is created.  Even if, all classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. But, then you are not able to set initial values for object attributes.

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes. The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

Example
public class Tree{
int x;
public Tree(int y) {
x = y;
}

public static void main(String[] args) {
Tree myObj = new Tree(5);
System.out.println(myObj.x);
}
}

// Outputs 5

Java Modifiers

Modifiers  are quite familiar with the public keyword that appears in almost all of our examples:

public class Main

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors. We divide modifiers into two groups:

  1. Access Modifiers – controls the access level
  2. Non-Access Modifiers – do not control access level, but provides other functionality Access Modifiers

For classes, you can use either public or default:

Modifier       Description
public The class is accessible by any other class
default The class is only accessible by classes in the same package. This is used when you don’t specify a modifier.

For attributes, methods and constructors, you can use the one of the following:

Modifier       Description
public The code is accessible for all classes
private The code is only accessible within the declared class
default The code is only accessible in the same package. This is used when you don’t specify a modifier.
protected The code is accessible in the same package and subclasses and superclasses in the Inheritance.

Non-Access Modifiers

For classes, you can use either final or abstract:

Modifier       Description
final The class cannot be inherited by other classes
abstract The class cannot be used to create objects . To access an abstract class, it must be inherited from another class.

For attributes and methods, you can use the one of the following:

Modifier       Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass or inherited from other class.
transient Attributes and methods are skipped when serializing the object containing them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read from the “main memory” final.

If you don’t want the ability to override existing attribute values, declare attributes as final:
Example
public class Main {
final int x = 10;
final double PI = 3.14;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 50; // will generate an error: cannot assign a value to a final variable
myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

Static

A static method means that it can be accessed without creating an object of the class, unlike public:

Example
An example to demonstrate the differences between static and public methods:

public class Main {
// Static method
static void myStaticMethod() {
System.out.println(“Static methods can be called without creating objects”);
}

// Public method
public void myPublicMethod() {
System.out.println(“Public methods must be called by creating objects”);
}

// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method
}
}

Abstract

An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass:

Example
// abstract class
abstract class Tree {
public String fname = “Leaves”;
public int age = 24;
public abstract void study(); // abstract method
}

// Subclass (inherit from Tree )
class Green extends Tree{
public int plantYear = 2018;
public void plant() { // the body of the abstract method is provided here
System.out.println(“Planting all the year long”);
}
}
// End code from filename: Tree .java
// Code from filename: TreeSecond.java

class TreeSecond {
public static void main(String[] args) {
// create an object of the Student class (which inherits attributes and methods from Tree )
Green  myObj = new Green ();
System.out.println(“Name: ” + myObj.fname);
System.out.println(“Age: ” + myObj.age);
System.out.println(“Plantation Year: ” + myObj.plantYear );
myObj.plant(); // call abstract method
}
}

See more Topic on Java OOP with real-time example

Nested class in JAVA with EXAMPLES

What is the defference between String, StringBuffer and StringBuilder.

Java Interface tutorials with Example.

JAVA abstract class with EXAMPLES

What Does Method Signature Mean in Java?

URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (To Carry or not to Carry) 1026:
To Carry or not to Carry is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 15, 2016
 * @Time : 4:22:27 PM
 */
public class Uri1026 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long x, y, answer;
        while (sc.hasNext()) {
            x = sc.nextLong();
            y = sc.nextLong();
            answer = x ^ y;
            System.out.println(answer);
        }
    }
}

Please read question carefully.
First of all we have to take two 32 bit decimal numbers as input, and produce an unsigned 32 bit decimal number as the output.
– In above program we take x and y as input and answer as output.
– We have to take x and y value from user and convert them into 32 bit binary.
– And then we have to XOR them and convert to decimal number.  
– And after that we put it in answer variable and print it.

In java programming there is bitwise XOR operator which is ^ . We solved this problem very easily using this bitwise XOR operator.

URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Right Area) 1190 Solution in Java

URI Problem (Right Area) 1190:
Right Area is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date   : Oct 28, 2016
 * @Time   : 4:04:11 PM
 */
public class Uri1190 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;
                if (j > m.length - i - 1 && i < j) {
                    sum += x;
                    count++;
                }
            }

        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Left Area) 1189 Solution in Java

URI Problem (Left Area) 1189:
Left Area is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:57:00 PM
 */
public class Uri1189 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;
                if (j < m.length - i - 1 && i > j) {
                    sum += x;
                    count++;
                }
            }

        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Inferior Area) 1188 Solution in Java

URI Problem (Inferior Area) 1188:
Inferior Area is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:45:36 PM
 */
public class Uri1188 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;

                if (j < i && j > (m.length - i - 1)) {
                    sum += x;
                    count++;
                }
            }

        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Top Area) 1187 Solution in Java

URI Problem (Top Area) 1187:
Top Area is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:32:36 PM
 */
public class Uri1187 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;

                if (j > i && j < (m.length - i - 1)) {
                    sum += x;
                    count++;
                }
            }
        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Below the Secundary Diagonal) 1186 Solution in Java

URI Problem (Below the Secundary Diagonal) 1186:
Below the Secundary Diagonal is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:29:44 PM
 */
public class Uri1186 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;

                if (j > (m.length - i - 1)) {
                    sum += x;
                    count++;
                }
            }
        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Above the Secundary Diagonal) 1185 Solution in Java

URI Problem (Above the Secundary Diagonal) 1185:
Above the Secundary Diagonal is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:23:06 PM
 */
public class Uri1185 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;

                if (j < (m.length - i-1)) {
                    sum += x;
                    count++;
                }
            }
        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Below the Main Diagonal) 1184 Solution in Java

URI Problem (Below the Main Diagonal) 1184:
Below the Main Diagonal is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 3:14:38 PM
 */
public class Uri1184 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;
                if (i > j) {
                    sum += x;
                    count++;
                }
            }
        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}
URI Problem (To Carry or not to Carry) 1026 Solution in Java

URI Problem (Above the Main Diagonal) 1183 Solution in Java

URI Problem (Above the Main Diagonal) 1183:
Above the Main Diagonal is a basic problem on URI online judge for novice problem solver.
You can find details on this Link.

import java.util.Scanner;

/**
 * @Author : Muhammad Harun-Or-Roshid
 * @Date : Oct 28, 2016
 * @Time : 2:51:24 PM
 */
public class Uri1183 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double m[][] = new double[12][12];
        double sum = 0;
        int count = 0;
        String v = sc.next();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                double x = sc.nextDouble();
                m[i][j] = x;
                if (i < j) {
                    sum += x;
                    count++;
                }
            }
        }
        if (v.equals("S")) {
            System.out.printf("%.1f\n", sum);
        } else {
            System.out.printf("%.1f\n", (sum / count));
        }
    }
}