Finding Factorial of a Number in Java

  • One of the famous java interview program for freshers is finding factorial of a number using java program
  • Calculating the factorial of a number using java example program with recursion.

  • Factorial number means multiplication of all positive integer from one to that number.
  • n!=1*2*3.......*(n-1)*n.
  • Here ! represents factorial.
  • Two factorial:   2!=  2*1=2
  • Three factorial: 3!= 3*2*1=6.
  • Four factorial :  4!= 4*3*2*1=24.
  • Five factorial:    5!= 5*4*3*2*1=120.
  • Six factorial:      6!= 6*5*4*3*2*1=720
  • Seven factorial: 7!= 7*6*5*4*3*2*1=5040
  • Eight factorial:   8!= 8* 7*6*5*4*3*2*1=40320.
  • By using loops we can find factorial of given number.
  • Lets how can we find factorial of a number using java program without recursion.

Program #1: Java program to find factorial of a number using for loop


  1. package interviewprograms.instanceofjava;

  2. import java.util.Scanner;

  3. public class FactiorialProgram {

  4. public static void main(String args[]){
  5. Scanner in = new Scanner(System.in);
  6. System.out.println("Enter a number to find factorial");
  7. int n= in.nextInt();
  8. int fact=1;

  9. for (int i = 1; i < n; i++) {
  10. fact=fact*i;
  11. }

  12. System.out.println("Factorial of "+n+" is "+fact);

  13. }
  14. }

Output:

  1. Enter a number to find factorial
  2. 5
  3. Factorial of 5 is 120


Program #2: Java program to find factorial of a number using recursion.

  1. package interviewprograms.instanceofjava;

  2. import java.util.Scanner;

  3. public class FactiorialProgram {

  4. public static void main(String args[]){
  5. Scanner in = new Scanner(System.in);
  6. System.out.println("Enter a number to find factorial");
  7. int n= in.nextInt();
  8. int fact=1;

  9. for (int i = 1; i < n; i++) {
  10. fact=fact*i;
  11. }

  12. System.out.println("Factorial of "+n+" is "+fact);

  13. }
  14. }

Output:


  1. Enter a number to find factorial
  2. 5
  3. Factorial of 5 is 120

Program #3: Java program to find factorial of a number using recursion (Eclipse)

factorial number method java


Setter and getter methods in java with example program


  • If we want to access variables inside a class we can access them using object. object.variable_name; and if we want to change the value of variable we will assign using object.variable_name=value;
  • By using constructor we can assign some values to the class variables whenever object is created but this is one time initialization.

  • To assign some value to variable directly assigning value or get value of variable using object   is not recommended. 
  • Actually we need to use methods to perform any task. And to assign and to get values of a object we have setter and getter methods concept in java.
  • Getter and setter methods are like normal methods in java. but to initialize new value and get the value of instance variables we will use use these methods that is the reason behind specialty of these methods
  • We can set as well as get value from variables so these are called setter and getter methods.
  • so declare variables as private to prevent from accessing directly using object of the class. and use get and set methods in java like
  • setXXX() and getXXX  to assign values and access variables . SetXXX() and getXXX() here set and get are naming conventions to be used. where as XXX represent variable names.
  • If we observe this it is pure encapsulation in java.


Set Method  /  Setter method in java:

  • Purpose of Setter method is to set new value or assign new value to instance variable .
  1. Method name should follow naming convention setVARIABLENAME().
  2. It should accept some value as an argument. here method argument should be of type of variable.
  3. It should have a statement to assign argument value to corresponding variable.
  4. It does not have any return type. void should be the method return type.
  5. In order to set some value to variable we need to call corresponding setter method  by passing required value.



  1. package settterandgettermethods;

  2. public class SetAndGet {
  3.  private String name;
  4.  private int id;
  5.  

  6. public void setName(String name) {
  7. this.name = name;
  8. }

  9. public void setId(int id) {
  10. this.id = id;
  11. }

  12. }



Get method / Getter  method in java:

  • Purpose of Getter method is to get the value of the instance variable.

  1. Method name should follow naming convention getVARIABLENAME().
  2. It should not have any arguments.
  3. It should return corresponding variable value.
  4. So return type must be of type of variable we are returning from the method.
  5. In order to get the variable value we need to call corresponding getter method of variable.

  1. package settterandgettermethods;

  2. public class SetAndGet {
  3.  
  4.  private String name;
  5.  private int id;

  6. public String getName() {
  7.  return name;
  8. }

  9. public void setId(int id) {
  10.  this.id = id;
  11. }

  12. public static void main(String args[]){
  13.  
  14.  SetAndGet obj = new SetAndGet();
  15.  String name =obj.getName();
  16.  
  17. }

  18. }


Java program to get and set variable values without setter and getter methods

  1. package settterandgettermethods;

  2. public class SetAndGet {
  3.  
  4.  private String name;
  5.  private int id;


  6. public static void main(String args[]){
  7.  
  8.  SetAndGet obj = new SetAndGet();
  9.  
  10.  obj.name="setting some value";
  11.  obj.id=1;
  12.  System.out.println(obj.name);
  13.  System.out.println(obj.id);
  14. }


  15. }


Output:


  1. setting some value
  2. 1

Java program to get and set variable values with setter and getter methods

  1. package settterandgettermethods;

  2. public class SetAndGet {
  3.  
  4.  private String name;
  5.  private int id;


  6. public String getName() {
  7.  return name;
  8. }

  9. public void setName(String name) {
  10.  this.name = name;
  11. }

  12. public int getId() {
  13.  return id;
  14. }

  15. public void setId(int id) {
  16.  this.id = id;
  17. }


  18. public static void main(String args[]){
  19.  
  20.  SetAndGet obj = new SetAndGet();
  21.  
  22.  obj.setName("java");
  23.  obj.setId(1);
  24.  System.out.println(obj.getName());
  25.  System.out.println(obj.getId());
  26. }


  27. }

Output:


  1. java
  2. 1


set and get methods in java

Find top two maximum numbers in a array java

  • Hi Friends today we will discuss about how to find top two maximum numbers in an array using java program.
  • For this we have written separate function to perform logic
  • findTwoMaxNumbers method takes integer  array as an argument
  • Initially take two variables to find top to numbers and assign to zero.
  • By using for each loop iterating array and compare current value with these values
  • If our value is less than current array value then assign current value to max1 
  • And assign maxone to maxtwo because maxtwo should be second highest.
  • After completion of all iterations maxone will have top value and maxtwo will have second maximum value.
  • Print first maximum and second maximum values.
  • So from main method create array and pass to findTwoMaxNumbers(int [] ar).


Program #1: Java interview programs to practice: find top two maximum numbers in an array without recursion 

  1. package arraysInterviewPrograms.instanceofjava;
  2. public class FindTopTwo {
  3.  
  4. public void findTwoMaxNumbers(int[] array){
  5.        
  6.  int maxOne = 0;
  7.  int maxTwo = 0;
  8.  
  9. for(int i:array){
  10.  
  11.     if(maxOne < i){
  12.            maxTwo = maxOne;
  13.            maxOne =i;
  14.      } else if(maxTwo < i){
  15.                 maxTwo = i;
  16.      }
  17. }
  18.         
  19.  
  20.   System.out.println("First Maximum Number: "+maxOne);
  21.   System.out.println("Second Maximum Number: "+maxTwo);
  22. }
  23.      
  24. public static void main(String a[]){
  25.  
  26.         int num[] = {4,23,67,1,76,1,98,13};
  27.         FindTopTwo obj = new FindTopTwo();
  28.         obj.findTwoMaxNumbers(num);
  29.         obj.findTwoMaxNumbers(new int[]{4,5,6,90,1});
  30.  
  31. }
  32.  
  33. }


Output:


  1. First Maximum Number: 98
  2. Second Maximum Number: 76
  3. First Maximum Number: 90
  4. Second Maximum Number: 6

Program #2:Java program to find top two maximum numbers in an array using eclipse IDE

top two maximum number in array java


How to run jsp program in eclipse using tomcat server

  • Hi friends today we will see basic example of how to run jsp (java server pages) program using tomcat server in eclipse IDE.
  • For this we need to create dynamic web project in eclipse
  • Lets see how to run jsp program in tomcat server step by step.
  • Print hello world using jsp program


Required software: 



  • After downloading eclipse and tomcat server. open eclipse and add server and select tomcat version and giver downloaded tomcat folder path.

Step 1: Open eclipse and create dynamic web project:

  • Now we need to create dynamic web project for this in eclipse 
  • New => other=> web=> Dynamic web project


how to run jsp program in tomcat server eclipse



Step 2 : Create a dynamic web project

  • Click on next => and give MyFirstJsp as project name.
  • Click on Next=> click next here select generate xml deployment descriptor check box
  • And click on finish.
  • So now project will be created and with default xml file.


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javae
  4. /web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  6.   <display-name>MyFirstJsp</display-name>
  7.   <welcome-file-list>
  8.     <welcome-file>index.html</welcome-file>
  9.     <welcome-file>index.htm</welcome-file>
  10.     <welcome-file>index.jsp</welcome-file>
  11.     <welcome-file>default.html</welcome-file>
  12.     <welcome-file>default.htm</welcome-file>
  13.     <welcome-file>default.jsp</welcome-file>
  14.   </welcome-file-list>
  15. </web-app>

Step 3: Create a JSP page


run jsp on eclipse


  • Right click on web content folder and select new => JSP file => give index.jsp


Step 4 : Edit Jsp page

  • Edit the JSP page and give Page title and in the body section create one paragraph tag and write some text like Hello world.


  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.or
  4. /TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Welcome</title></head>
  9. <body>
  10. <p>Hello World</p>
  11. </body>
  12. </html>


Step 5: Run dynamic web project using tomcat server

  • So index.jsp is present in welcome file list of web.xml file then whenever server starts it loads welcome file i.e index.jsp
  • We can give any name t our jsp but it should present in web.xml as welcome file
  • <welcome-file>index.htm</welcome-file> . no need of other files which names are created by default we can delete those things.
  • Right click on the project and => run as => run on server=> select tomcat version = >add our project if not added click on finish. 
how to compile jsp program in tomcat

Java interface programming questions

  • We can develop interfaces by using "interface" keyword. 
  • A class will implements all the methods in an interface.
  • By default interface methods are abstract.
  • Lets see some interesting java programming interview questions on interfaces.
  • Interface programming questions in java




Java interface interview programs part 1: interface programming java

Program #1: what will happen if we define normal methods in interface

  1. package interfaceinverviewprograms.instanceofjava;
  2. public interface A{
  3.  
  4. /**
  5. * @java interface  interview programming  questions and answers for freshers and experienced
  6.  */
  7.   
  8. void show() {
  9.         
  10.         System.out.println("Hello world");
  11.  
  12.     }
  13. }





Program #2:java interview programs to practice: Non static variables in interface

  1. package interfaceinverviewprograms.instanceofjava;
  2. public interface A{
  3.  
  4. /**
  5. * @java interface  interview programming  questions and answers for freshers and experienced
  6.  */
  7.   
  8. int a,b;

  9. }





Program #3:java interview programs to practice: which modifiers interface allows

  1. package interfaceinverviewprograms.instanceofjava;
  2. public interface A{
  3.  
  4. /**
  5. * @java interface  interview programming  questions and answers for freshers and experienced
  6.  */
  7.   
  8. private int x;
  9. protected int y;

  10. }





Program #4:java interview programs to practice: interface allows constructor?

  1. package interfaceinverviewprograms.instanceofjava;
  2. public interface A{
  3.  
  4. /**
  5. * @java interface  interview programming  questions and answers for freshers and experienced
  6.  */
  7. A(){
  8.  
  9. }

  10. }





Exception handling in method overriding in java

  • Defining multiple methods with same name and same signature in super class and sub class known as method overriding.
  • When Overriding a method there is a chance of having statements which may cause exceptions so we need to handle those inside method.
  • Otherwise simply we can give responsibility of handling exceptions to calling method.
  • We can give the responsibility of handling exceptions of a method to calling place by using throws keyword in java.
  • Now we are going to discuss about exception handling in method overriding in java.
  • When am method is overridden in sub class and super class method having throws exception. Then we have some scenarios to discuss.



1.Super class method not throwing any exceptions.
2.Super class method  throws exceptions.


1.Super class method  Not throwing any exceptions.
  • When super class method not throws ant exception,
  • We can add throws unchecked exception in sub class overridden method.
  • We can not add throws checked exception.

Program #1: When super class method does not have any throws exception then we can add throws un checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show(){
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws NullPointerException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {
  14.  
  15.    Sub obj = new Sub();
  16.     obj.show();
  17.  
  18. }
  19.  
  20. }
Output:

  1. Sub class show() method


Program #2: When super class method does not have any throws exception then we can not add throws checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show(){
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

Exception handling in method overriding throws



2.Super class method  throws exceptions.

  • If super class method throws checked exceptions sub class overridden method can throw same exception , sub class exception or no exception but can not declare parent exception.
  • If super class method throws unchecked exceptions then no rules.


Program #3: When super class method  throws checked exception then we can add throws  checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws IOException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws IOException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {

  14.  
  15.    Sub obj = new Sub();
  16.  
  17.  try {
  18.             obj.show();
  19. } catch (IOException e) {
  20.          
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }
Output:

  1. Sub class show() method

Program #4: When super class method  throws unchecked exception then we can not add throws  checked exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws ArithmeticException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }


throws in method overriding java


Program #5: When super class method  throws checked exception then we can not add throws its  parent exception in subclass overridden method.

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Super {
  3.  
  4.     /**
  5.      * @author www.instanceofjava.com
  6.      * @category throws in method overriding java
  7.      */
  8.     
  9.     
  10. public void show() throws FileNotFoundException{
  11.         
  12.  System.out.println("Super class show() method");
  13.  
  14. }
  15.  
  16. }

  1. package exceptionhandlingmethodoverridingjava;
  2. public class Sub extends Super {
  3.  
  4. /**
  5. * @author www.instanceofjava.com
  6. * @category throws in method overriding java
  7. */
  8.     
  9. public void show() throws IOException{
  10.         
  11.         System.out.println("Sub class show() method");
  12.  }

  13. public static void main(String[] args) {

  14.  
  15. Sub obj = new Sub();
  16.  
  17. try {
  18.            obj.show();
  19. } catch (Exception e) {
  20.           
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }
Select Menu