Tuesday, February 12, 2019

Factorial Program in Java with examples.

Factorial Program in Java

Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:
  1. 4! = 4*3*2*1 = 24  
  2. 5! = 5*4*3*2*1 = 120  
Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shrieks".
The factorial is normally used in Combinations and Permutations (mathematics).
There are many ways to write the factorial program in java language. Let's see the 2 ways to write the factorial program in java.
  • Factorial Program using loop
  • Factorial Program using recursion

Factorial Program using loop in java

Let's see the factorial Program using loop in java.
  1. class FactorialExample{  
  2.  public static void main(String args[]){  
  3.   int i,fact=1;  
  4.   int number=5;//It is the number to calculate factorial    
  5.   for(i=1;i<=number;i++){    
  6.       fact=fact*i;    
  7.   }    
  8.   System.out.println("Factorial of "+number+" is: "+fact);    
  9.  }  
  10. }  
Output:
Factorial of 5 is: 120

Factorial Program using recursion in java

Let's see the factorial program in java using recursion.
  1. class FactorialExample2{  
  2.  static int factorial(int n){    
  3.   if (n == 0)    
  4.     return 1;    
  5.   else    
  6.     return(n * factorial(n-1));    
  7.  }    
  8.  public static void main(String args[]){  
  9.   int i,fact=1;  
  10.   int number=4;//It is the number to calculate factorial    
  11.   fact = factorial(number);   
  12.   System.out.println("Factorial of "+number+" is: "+fact);    
  13.  }  
  14. }  
Output:
Factorial of 4 is: 24

Monday, February 4, 2019

Java if Else with Examples and programs

Java Conditions and If Statements

Java supports the usual logical conditions from mathematics:
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to a >= b
  • Equal to a == b
  • Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the statementif to specify a block of Java code to be executed if a condition is.true

Syntax

if (condition) {
  // block of code to be executed if the condition is true
}
Note that isif in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is,true print some text:

Example

if (20 > 18) {
  System.out.println("20 is greater than 18");
}
Run example »
We can also test variables:

Example

int x = 20;
int y = 18;
if (x > y) {
  System.out.println("x is greater than y");
}
Run example »

Example explained

In the example above we use two variables, x, and y, to test whether x is greater than y (using the operator>). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

Use the statementelse to specify a block of code to be executed if the condition is.false

Syntax

if (condition) {
  // block of code to be executed if the condition is true
} else { 
  // block of code to be executed if the condition is false
} 

Example

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."
Run example »

Example explained

In the example above, time (20) is greater than 18, so the condition is false, so we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day".

The else if Statement

Use the statementelse if to specify a new condition if the first condition is.false

Syntax

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}

Example

int time = 22;
if (time < 10) {
  System.out.println("Good morning.");
} else if (time < 20) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
// Outputs "Good evening."
Run example »

Example explained

In the example above, time (22) is greater than 10, so the first condition is.false The next condition, in the statementelse if, is also,false so we move on to the conditionelse since condition1 and condition2 is both false- and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."

Short Hand If...Else (Ternary Operator)

If you have only one statement to execute, one for,if and one for,else you can put it all on the same line:

Syntax

variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:

Example

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
Run example »
You can simply write:

Example

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
Run example »

Test Yourself With Exercises

Exercise:

Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
 (x  y) {
  System.out.println("Hello World");
}

Polymorphism in Java with example

Java Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Java Polymorphism Example

Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −
  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal −

Example

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.

Virtual Methods

In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

Example

/* File name : Employee.java */
public class Employee {
   private String name;
   private String address;
   private int number;

   public Employee(String name, String address, int number) {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }

   public void mailCheck() {
      System.out.println("Mailing a check to " + this.name + " " + this.address);
   }

   public String toString() {
      return name + " " + address + " " + number;
   }

   public String getName() {
      return name;
   }

   public String getAddress() {
      return address;
   }

   public void setAddress(String newAddress) {
      address = newAddress;
   }

   public int getNumber() {
      return number;
   }
}
Now suppose we extend Employee class as follows −
/* File name : Salary.java */
public class Salary extends Employee {
   private double salary; // Annual salary
   
   public Salary(String name, String address, int number, double salary) {
      super(name, address, number);
      setSalary(salary);
   }
   
   public void mailCheck() {
      System.out.println("Within mailCheck of Salary class ");
      System.out.println("Mailing check to " + getName()
      + " with salary " + salary);
   }
   
   public double getSalary() {
      return salary;
   }
   
   public void setSalary(double newSalary) {
      if(newSalary >= 0.0) {
         salary = newSalary;
      }
   }
   
   public double computePay() {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}
Now, you study the following program carefully and try to determine its output −
/* File name : VirtualDemo.java */
public class VirtualDemo {

   public static void main(String [] args) {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
      System.out.println("Call mailCheck using Salary reference --");   
      s.mailCheck();
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
   }
}
This will produce the following result −

Output

Constructing an Employee
Constructing an Employee

Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.
mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

Java String Interview Questions and Answers

1) What is String in Java? Is String is data type? String in Java is not a primitive data type like int, long or double. The string is a ...