8 different ways to convert int to String in java

  • How to convert string to int or integer to string in java?
  • When we are working on a project we will be having some scenarios of expecting a string from int or integer from string.
  • Now we will be discussing on how to convert Integer to String in java with example java programs.



8 different ways to convert int to String in java

1.Convert Integer to String using Integer.toString() method: 
2.Convert Integer to String using String.valueOf() method.
3.Convert Integer to String / int to String using new Integer(int).toString() 
4.Convert Integer to String / int to String using String.format() method 
5.Convert Integer to String / int to String using DecimalFormat 
6.Convert Integer to String/ int to String using StringBuffer / StringBuilder 
7.Convert Integer to String / int to String directly by adding to "" 
8.Convert Integer to String / int to String using Special radix. 


1.Convert Integer to String using Integer.toString() method:

  •  Integer is a wrapper class in java which is mainly used to represent or convert primitive int value to object.
  • And Integer class having some predefined methods.
  • Integer class has special predefined method to convert integer value to string toString();
  • toString is a static method in Integer class so that by using class name itself we can call that method to convert Integer to corresponding string value.
Program #1: Java Example program to convert Integer to String by using toString() method:


 Output:


  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.         
  9.         
  10.  Integer i = new Integer(64);
  11.         
  12.  //converting integer to string by calling toString() method on integer object
  13.  
  14.   String str= i.toString();
  15.   // also we can use like String str= Integer.toString(i);

  16.  System.out.println(str);
  17.  
  18. }
  19.  
  20. }
 Output:


  1. 64

2.Convert Integer to String using String.valueOf() method.

  •  Integer class have toString() method to convert integer to string value same way String class also has valueOf() method to convert int or integer to string.
  • String class has a static method valueOf() which takes int as argument and converts into string.

Program #2: Java Example program to convert int to string using valueOf() method.

  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.   Integer i = new Integer(64);       
  10.  
  11.  //converting integer to string by calling valueOf() method on String clas
  12.   String str= String.valueOf(i);
  13.         
  14.   System.out.println(str);
  15.         
  16.         
  17.   int number=123;
  18.   String numberstr= String.valueOf(number);
  19.         
  20.   System.out.println(numberstr);     
  21.      
  22. }
  23.  
  24. }
 Output:


  1. 64
  2. 123


3.Convert Integer  / int to String using new Integer(int).toString()
  •  And here by creating Integer object and directly calling tostring method.
  • We can convert into to string directly with one statement this will be done by using Integer(int).toString()


Program #3: Java Example program to convert int to string using new Integer(int ).toString()

  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.   int number=23;
  10.  
  11.  String numberstr=    new Integer(number).toString();
  12.         
  13.  System.out.println(numberstr);
  14.      
  15. }
  16.  
  17. }
 Output:


  1. 23

4.Convert Integer  / int to String using String.format() method

  •  Another alternative way to convert int t string is by calling String.format method.
  • String.format ("%d", number);
 
Program #4: Java Example program to convert int to string using String.format() method


  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.   int number=23;
  10.  
  11.  String numberstr=   String.format ("%d", number);
  12.         
  13.  System.out.println(numberstr);
  14.      
  15. }
  16.  
  17. }
 Output:


  1. 23

 5.Convert Integer  / int to String using DecimalFormat

  •  Another alternative way to convert int t string is by java.text.DecimalFormat
  • DecimalFormat class mainly used to represent numbers in formats.
  • Decimal format class providing format() method to convert int to string with specified format.

Program #5: Java Example program to convert int to string using DecimalFormat class


  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.   int number=23;
  10.        
  11.   DecimalFormat obj= new DecimalFormat("#");
  12.         
  13.   String numberstr=    obj.format(number);
  14.         
  15.   System.out.println(numberstr);
  16.         
  17.         
  18. DecimalFormat objct= new DecimalFormat("#,###");
  19.         
  20. String numberstr1=    objct.format(3400);
  21.         
  22. System.out.println(numberstr1);
  23.      
  24. }
  25.  
  26. }
 Output:


  1. 23
  2. 3,400

6.Convert Integer  / int to String using StringBuffer / StringBuilder

  •  StringBuffer and StringBuilder classes also providing toString() method to convert int to string

Program #6: Java Example program to convert int to string using StringBuffer and StringBuilder


  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.     int number=234;     
  10.    
  11.     StringBuffer sf=new StringBuffer();
  12.     sf.append(number);
  13.     String numberstr=    sf.toString();
  14.         
  15.    System.out.println(numberstr);
  16.         
  17.         
  18.     StringBuilder sb=new StringBuilder();
  19.     sb.append(number);
  20.     String nstr=    sb.toString();
  21.             
  22.     System.out.println(nstr);     
  23. }
  24.  
  25. }
 Output:


  1. 234
  2. 234

7.Convert Integer  / int to String directly by adding to ""

  • We can convert a number to string simply by concatenating to "".
  • But it is not recommended to use.

Program #7: Java Example program to convert int to string by concat to ""



  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.   int number=8538;
  10.  
  11.  String numberstr=   ""+number;
  12.         
  13.  System.out.println(numberstr);
  14.      
  15. }
  16.  
  17. }
 Output:


  1. 8538

8.Convert Integer  / int to String using Special radix.


Program #8: Java Example program to convert int to string using special radix


  1. package convertintegertostring.java;
  2. public class IntegerToString {
  3.  
  4.     /**
  5.      * @ website: www.InstanceOfJava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.  int number=536;
  10.  
  11.    String binaryString = Integer.toBinaryString(number);
  12.    System.out.println(binaryString);
  13.         
  14.    String octalString = Integer.toOctalString(number);
  15.    System.out.println(octalString);
  16.     
  17.    String hexString = Integer.toHexString(number);
  18.    System.out.println(hexString);
  19.         
  20.    String customString = Integer.toString(number, 7);
  21.    System.out.println(customString);
  22.  

  23. }
 Output:


  1. 1000011000
  2. 1030
  3. 218
  4. 1364

8 different ways to convert int to string in java


convert int to string in java example

 Output:


  1. 64
  2. 64
  3. 536
  4. 536
  5. 3,400
  6. 536
  7. 536
  8. 1000011000

Deep copy in java example program

  • Creating a copy of the object can be done in two ways 
  • Shallow copy and deep copy. we have already discussed about shallow copy
  • Shallow copy in java example program
  • In shallow copy of object only object reference will be copied and if we change any data inside object changes will reflect in cloned object also this means both are referring to same object.
  •  


Deep copy / Deep cloning in  Java

  • In deep copy completely a new object will be created with same data.
  • If we change the data inside original object wont reflect in deeply cloned object.

deep cloning vs shallow cloning in java



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

Sample :

  1. package com.shallowcopyvsdeppcopy;

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

  5. Sample (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.  
  4.     Sample s;
  5.     int a;
  6.     
  7.     empclone(int a, Sample s){
  8.         this.a=a;
  9.         this.s=s;
  10.        
  11.     }
  12.      
  13. public Object clone()throws CloneNotSupportedException{ 
  14.        return new empclone(this.a, new Sample(this.s.a,this.s.a));
  15. }  
  16.            
  17.     
  18. public static void main(String[] args) {
  19.      
  20.         empclone a= new empclone(2, new Sample(3,3));
  21.         empclone b=null;
  22.     
  23.  try {
  24.              b=(empclone)a.clone();
  25.            
  26.  } catch (CloneNotSupportedException e) {
  27.             // TODO Auto-generated catch block
  28.             e.printStackTrace();
  29.         }
  30.         System.out.println(a.s.a);
  31.         System.out.println(b.s.a);
  32.        
  33.         a.s.a=12;
  34.         System.out.println(a.s.a);
  35.         System.out.println(b.s.a);
  36. }
  37.  
  38. }

OutPut:
  1. 3
  2. 3
  3. 12
  4. 3

What is the difference between shallow copy and deep copy:
  • When we create a shallow copy of the object only reference will be copied
  • When we create deep copy of the object totally new object with same data will be created. 
  • Shallow copy and deep copy will be done by using Cloneable  interface in java. 

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


Select Menu