Shallow copy in java example program

  • We create exact copy of the object using Cloneable in java.
  • We need to override object class clone() method.
  • This is also called clone of the object.
  • So we can create copy of object using two different way
    1. Shallow copy
    2. Depp copy




Shallow copy / Shallow cloning in java

  • In Shallow copy object reference will be copied instead of copying whole data of the object.
  • So the newly created object will be another reference for existing with same data means shallow copy of the object.
  • Whenever we change data in the original object same changes made to new object also because both are pointing to same object.

shallow copy in java


Program #1: Java example program to demonstrate shallow copy / shallow cloning



Example:
  1. package com.shallowcopyvsdeppcopy;

  2. public class Example{
  3. int a;
  4. int b;

  5. Example(int a, int b){
  6.     this.a=a;
  7.     this.b=b;
  8. }

  9. }


Empclone :

  1. package com.shallowcopyvsdeppcopy;

  2. public class Empclone implements Cloneable {

  3.     Example e;
  4.     int a;
  5.    
  6.     Empclone (int a, Example es){
  7.         this.a=a;
  8.         this.e=e;
  9.       
  10.     }
  11.    
  12.  public Object clone()throws CloneNotSupportedException{
  13.       
  14.         return super.clone();
  15.  }
  16.           
  17.    
  18. public static void main(String[] args) {
  19.     
  20.         Empclone a= new Empclone (2, new Example(3,3));
  21.         Empclone b=null;
  22.    
  23.         try {
  24.              b=(Empclone )a.clone();
  25.           
  26.         } catch (CloneNotSupportedException e) {
  27.             
  28.             e.printStackTrace();
  29.         }
  30.         System.out.println(a.e.a);
  31.         System.out.println(b.e.a);
  32.       
  33.         a.e.a=12;
  34.         System.out.println(a.e.a);
  35.         System.out.println(b.e.a);
  36.     }

  37. }

Output:


  1. 3
  2. 3
  3. 12
  4. 12

Print Pascals triangle using java program

  • Pascals triangle means arranging numbers in pascal triangle format.
  • First row starts with number 1.
  • Here is the pascal triangle with 8 rows.



  •  The sum of all numbers in each row will be double the sum of all numbers in above row
  •  The diagonals adjacent to the border diagonals of 1's contains natural numbers in order


 Program #1: Java example program to print  numbers in pascals triangle pattern.

  1. package interviewprograms.instanceofjava;

  2. import java.util.Scanner;
  3. /*
  4.  * www.instanceofjava.com
  5.  */
  6. public class PasclasTriangleProgram {

  7. public static void main(String args[]){
  8. Scanner in = new Scanner(System.in);
  9. System.out.println("Enter number of rows ");

  10. int rows= in.nextInt();

  11.  for(int i =0;i<rows;i++) {

  12.         int number = 1;
  13.   
  14.   System.out.format("%"+(rows-i)*2+"s","");

  15.  for(int j=0;j<=i;j++) {

  16.     System.out.format("%4d",number);

  17.       number = number * (i - j) / (j + 1);

  18. }

  19.   System.out.println();

  20. }

  21. }
  22. }        

Output:

  1. Enter number of rows 
  2. 8
  3.                    1
  4.                  1   1
  5.                1   2   1
  6.              1   3   3   1
  7.            1   4   6   4   1
  8.          1   5  10  10   5   1
  9.        1   6  15  20  15   6   1
  10.      1   7  21  35  35  21   7   1

1.Pattern Programs in java Part-1

2.Pattern Programs in java Part-2

3.Pattern Programs in java Part-3 

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

Select Menu