How to create csv file in java using filewriter

  • We can create CSV file and fill some data in to it using java program.
  • We can create CSV file and write data int to CSV file using java.io.FileWriter class.
  • Creating object of java.io.FileWriter class by giving output filename.
  • After creating object of java.io.FileWriter append data by calling append("data") method of FileWriter class object.
  • Use append('\n'); for enter data in new row.
  • Lets see a java example program on how to create csv file and write data in to it using FileWriter Class.



Program #1: Java program to create CSV file using FileWriter class

  1. package com.java.createcsvfile;

  2. import java.io.FileWriter;
  3. import java.io.IOException;

  4. public class CreateCsvFile {

  5. private static void generateCsvFile(String fileName) {

  6.       FileWriter writer = null;

  7.  try {

  8.      writer = new FileWriter(fileName);
  9.      writer.append("Name");
  10.      writer.append(',');
  11.      writer.append("Number");
  12.      writer.append('\n');

  13.      writer.append("interview questions");
  14.      writer.append(',');
  15.      writer.append("001");
  16.      writer.append('\n');

  17.   writer.append("interview programs");
  18.   writer.append(',');
  19.   writer.append("002");
  20.   writer.append('\n');

  21.   System.out.println("CSV file is created...");

  22.   } catch (IOException e) {
  23.   e.printStackTrace();
  24.   } finally {
  25.         try {
  26.    writer.flush();
  27.    writer.close();
  28.         } catch (IOException e) {
  29.    e.printStackTrace();
  30. }
  31. }
  32. }

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

  34. String location = "E:\\newCsvFile.csv";
  35. generateCsvFile(location);

  36. }

  37. }

 Output:


create csv file in java

Creating array of objects in java example program

  • Array is collection of similar data types.
  • Arrays can hold collection of data with indexes
  • We already know that we can hold group of primitive variables
  • Arrays can hold referenced variables also like Strings and objects
  • So we can say it is possible to store or create array of objects in java



Declaring arrays in java:

  •  One dimensional array can be created like
  • int[] singlearray;
  • Two dimensional array can be created like 
  • int[][] intdoubleArray;       
  • double[][] doubleArray;

Instantiation and Initialization of Arrays

Program #1: Java example program to store string object in array
  1. package arraysofobjectsinjava;
  2. public class ArrayOfObjects {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      *  creating and assigning values to arrays in java
  7.      */
  8.    public static void main(String[] args) {
  9.         
  10.         int[] a= new int[2];
  11.         a[0]=1;
  12.         a[1]=2;
  13.         
  14.         System.out.println(a[0]);
  15.         System.out.println(a[1]);
  16.         
  17.         int[] var= {1,2,3,4,5};
  18.         
  19.         
  20.         for (int i = 0; i < var.length; i++) {
  21.             System.out.println(var[i]);
  22.         }      
  23. int[][] array=new int[2][2];       
  24.         
  25.         array[0][0]=1;
  26.         array[0][1]=2;
  27.         array[1][0]=3;
  28.         array[1][1]=4;
  29.         
  30.   for(int i=0; i<array.length; i++) {
  31.  
  32.                for(int j=0; j<array[1].length; j++)
  33.                    System.out.print(array[i][j] + " ");
  34.                System.out.println();
  35. }  
  36.  
  37. }
  38.  
  39. }

 Output:


  1. 1
  2. 2
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 1 2 
  9. 3 4

Array of objects in java:

Program #2: Java example program to store string object in array


  1. package arraysofobjectsinjava;
  2. public class ArrayofStringObjects {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      * Storing String objects in String array
  7.      */
  8.     public static void main(String[] args) {
  9.         
  10.         
  11.         String a[]= new String[5];
  12.         a[0]="array of objects";
  13.         a[1]="object array in java";
  14.         a[2]="array of objects in java example program";
  15.         a[3]="array of objects in java tutorial";
  16.         a[4]="how to make array of objects in java";
  17.         
  18.         for (int i = 0; i < a.length; i++) {
  19.             System.out.println(a[i]);
  20.         }
  21.  
  22. }
  23.  
  24. }

Output:
  1. array of objects
  2. object array in java
  3. array of objects in java example program
  4. array of objects in java tutorial
  5. how to make array of objects in java

Creating custom array of objects in java
  •  We can also store custom objects in arrays .
  • Create a employee class.
  • Create multiple objects of employee class and assign employee objects to array.
  • Arrays can store objects but we need to instantiate each and every object and array can store it

Program#3: java example program to create custom objects and store in array


Employee.java

  1. package arraysofobjectsinjava;
  2. public class Employee {
  3.  
  4.     String name;
  5.     int id;
  6.     
  7.     Employee(String name, int id){
  8.         this.name=name;
  9.         this.id=id;
  10.         
  11.     }
  12.  
  13. }


array of objects in java

Tower of hanoi recursive solution using Java

  • Towers of  Hanoi is a famous game.
  • In this game there are three poles and N number of disks placed one over another in increasing in size from top to bottom.

  • Objective of this game is to move disks from first pole to last pole.
  • And the condition is we can not place bigger disk on top of smaller disk.
  • Initially all disks placed in first pole smaller disk will be on top and bigger disk will be on bottom.
  • We need to move all the disks from from first pole to last pole.

Rules of tower of  Hanoi:
  • We can move only one disk at a time.
  • At any poi of time larger disk can not be placed on smaller disk.
  • In order to solve this problem we have given a second pole so we can use second pole and move disks from  first pole to third pole.
  • We can solve this using rec recursive procedure.
Tower of  Hanoi with Single disk: N=1
  • Three poles are A , B ,C
  • And a disk is present at A we need to move from A to C
  • As it its single disk we can directly move disk A - > C 
tower of hanoi recursive solution

 Tower of  Hanoi with Two disks : N=2
  • Three poles are A , B ,C
  • And two disks are placed in pole A, Disk 1 and Disk2 top to bottom.( assume Disk 2 is smaller and Disk 1 bigger)
  • Move Disk2 from A to  B 
  • Move Disk1 From A to C.
  • Move Disk2 from B to C.
tower of hanoi in data structure program


Tower of  Hanoi with Three disks : N=3

  • Three poles are A , B ,C
  • And three disks are placed in pole A, Disk 1  top to bot, Disk2 and Disk 2 top bottom to .( assume Disk 3 is smaller and Disk 1 bigger)
  • In this firs we need to move two disk from  A to B which we already done in above procedure
  • So we need to repeat that here.
  • Move Disk1 from A to C.
  • Now Moving two disks from B to C we have already seen in above procedure so its recursive.


Tower of Hanoi Recursive Algorithm:

N = number of disks

If  N == 1
  • Move Single disk from A to C
If   N >1

  1. 1.Move n-1 disks from start A to B  TowersofHanoi(n-1,start, end , aux)
  2. Move last Disk from A to C
  3. Move n-1 disks from B to C.             TowersofHanoi(n-1,start, aux, end )
  • Step 1 and 3 are recursive procedures.
  • Lets see hoe to write  java recursive program for this towers of  Hanoi problem
  • Here B as auxiliary pole.

Program #1: Java Example program on towers of  Hanoi:

  1. package towersofhanoi;
  2. import java.util.Scanner;
  3.  
  4. public class TowersofHanoi {
  5.  
  6. public void TOH(int n, String start, String aux, String end) {
  7.  
  8.            if (n == 1) {
  9.                System.out.println(start + " -> " + end);
  10.            } else {
  11.                TOH(n - 1, start, end, aux);
  12.                System.out.println(start + " -> " + end);
  13.                TOH(n - 1, aux, start, end);
  14.            }
  15. }
  16.  
  17. public static void main(String[] args) {
  18.  
  19.            TowersofHanoi towersOfHanoi = new TowersofHanoi();
  20.  
  21.            System.out.print("Enter number of discs: ");
  22.            Scanner scanner = new Scanner(System.in);
  23.            int discs = scanner.nextInt();
  24.            towersOfHanoi.TOH(discs, "A", "B", "C");
  25. }
  26.  
  27. }

 Output:

  1. Enter number of discs: 
  2. 3
  3. A -> C
  4. A -> B
  5. C -> B
  6. A -> C
  7. B -> A
  8. B -> C
  9. A -> C

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. }





How to open notepad using java program

  • Notepad is a text editor from windows operating system. We use notepad for writing text files.
  • We can open a new notepad using java code.
  • By using the concept of running another application by Runtime class in java.
  • By creating object of runtime and calling  exec() method by passing application name.
  • Lets see how to open a notepad using java code




Program #1: Java example program to open notepad


  1. package interestingJavaprograms;
  2. import java.io.IOException;
  3.  
  4. public class NotepadJava {
  5.  
  6.     /**
  7.      * @ www.instanceofjava.com
  8.      * @ how to open a new notepad using java program
  9.      */
  10. public static void main(String[] args) {
  11.        
  12.           Runtime rt = Runtime.getRuntime();
  13.           
  14. try {
  15.       rt.exec("notepad");
  16. }
  17.  catch (IOException ex) {
  18.  
  19.  System.out.println(ex);
  20.  
  21. }  
  22.  
  23. }
  24.  
  25. }

 Output:

open notepad using java


Program #2: Java example program to open notepad and after 2 seconds close it.


  1. package interestingJavaprograms;
  2. import java.io.IOException;
  3.  
  4. public class NotepadJava {
  5.  
  6.     /**
  7.      * @ www.instanceofjava.com
  8.      * @ how to open a new notepad using java program
  9.      */
  10. public static void main(String[] args) throws InterruptedException, IOException {
  11.         
  12. Runtime runTime = Runtime.getRuntime();
  13. System.out.println("Opening notepad");
  14. Process process = runTime.exec("notepad");
  15.           
  16. try {
  17.  
  18.  
  19. Thread.sleep(200); 

  20.  process.destroy();
  21.  System.out.println("Closing notepad");
  22.  
  23. }
  24.  catch (Exception ex) {
  25.  
  26.  System.out.println(ex);
  27.  
  28. }  
  29.  
  30. }
  31.  
  32. }

  • We can open already existing notepad also for that we need to specify notepad.exe location and path of the destination file.
  • We need to pass these two parameters  to exec method of runtime class.
  • runTime.exec("C:\\Windows\\System32\\notepad.exe E:\\Samplenotepad.txt");

Program #3: Java example program to open exiting notepad txt file.


  1. package interestingJavaprograms;
  2. import java.io.IOException;
  3.  
  4. public class NotepadJava {
  5.  
  6.     /**
  7.      * @ www.instanceofjava.com
  8.      * @ how to open a new notepad using java program
  9.      */
  10. public static void main(String[] args) {
  11.        
  12.           Runtime rt = Runtime.getRuntime();
  13.           
  14. try {
  15.    runTime.exec("C:\\Windows\\System32\\notepad.exe E:\\Samplenotepad.txt");
  16. }
  17.  catch (IOException ex) {
  18.  
  19.  System.out.println(ex);
  20.  
  21. }  
  22.  
  23. }
  24.  
  25. }

Java program to reverse vowels of a string


Program : Java example program to Reverse Vowels  in a String



  1. package inheritanceInterviewPrograms;
  2. /*
  3.  * @www.instanceofjava.com
  4.  */
  5. public class ReverseVowels {
  6.     public static String reverseVowels(String string) {
  7.  
  8.         String vowelsStr = "aeiouAEIOU";
  9.  
  10.         int lo = 0;
  11.         int hi = string.length() - 1;
  12.         char[] ch = string.toCharArray();
  13.  
  14.  while (lo < hi) {
  15.  
  16.      if (!vowelsStr.contains(String.valueOf(string.charAt(lo)))) {
  17.                 lo++;
  18.                 continue;
  19.        }
  20.  
  21.     if (!vowelsStr.contains(String.valueOf(string.charAt(hi)))) {
  22.                 hi--;
  23.                 continue;
  24.        }
  25.  
  26.     // swaping variables
  27.      swap(ch, lo, hi);
  28.             lo++;
  29.             hi--;
  30.       }
  31.  
  32.         return String.valueOf(ch);
  33.     }
  34.  
  35. private static void swap(char[] ch, int lo, int hi) {
  36.  
  37.         char temparray = ch[lo];
  38.         ch[lo] = ch[hi];
  39.         ch[hi] = temparray;
  40.  
  41.  }
  42.     
  43. public static void main (String args[]) {
  44.         
  45.          
  46.  System.out.println("After reversing vowels in a string="reverseVowels("InstanceOfjava"));
  47.         
  48.          
  49. }
  50.  
  51. }
Output:


  1. After reversing vowels in a string=anstancOefjavI


Core java online programming test on inheritance

  • Inheritance means getting properties from one class object to another.
  • So in sub class we can use or access super class variables and method : re usability
  • There are some interesting and important points to discuss about inheritance
  • In major java interviews and java online test on core java there is more chance of getting programming questions from inheritance
  • So let us see some java test questions. java test online to practice
  • If you want explanations then visit below topic
  • Top 16 Java Inheritance Interview questions for freshers and experienced  




5 Points to know about inheritance:

Program #1: Java test on inheritance:
  • Creating object for super class and calling super class methods and accessing super class variables.

  1. package interviewprograms.instanceofjava;
  2. public class Super{
  3.  
  4.  int a, int b;
  5.  
  6. void show(){
  7.  System.out,println("Inside Show method");
  8. }
  9.  
  10. }



  1. package interviewprograms.instanceofjava;
  2. public class Sub extends Super{
  3.  int a, int b;
  4. public static void main(String[] args) {
  5.         
  6. Super obj= new Super();
  7. obj.a=10;
  8. System.out,println(obj.a);
  9.  obj.show();
  10. }
  11. }






Program #2: Core Java online test on inheritance:
  • Creating object for sub class and calling sub class methods and accessing sub class variables.

  1. package interviewprograms.instanceofjava;
  2. public class Super{
  3.  
  4.  int a, int b;
  5.  
  6. void show(){
  7.  System.out,println("Inside Show method");
  8. }
  9.  
  10. }

  1. package interviewprograms.instanceofjava;
  2.  
  3. public class Sub extends Super{
  4.  int x;
  5.  
  6.  
  7. void show(){
  8.  System.out,println("Inside Sub class Show method");
  9. }
  10. public static void main(String[] args) {
  11.         
  12. Sub obj= new Sub ();
  13. obj.x=10;
  14. System.out,println(obj.x);
  15.  obj.show();
  16. }
  17. }





Program #3: core java online test for beginners and experienced on inheritance
  • Creating object for sub class accessing super class members and sub class members.

  1. package interviewprograms.instanceofjava;
  2. public class Super{
  3.  
  4.  int a, int b;
  5.  
  6. void show(){
  7.  System.out,println("Inside Show method");
  8. }
  9.  
  10. void print(){
  11.  System.out,println("Inside super class print method");
  12. }
  13.  
  14. }

  1. package interviewprograms.instanceofjava;
  2.  
  3. public class Sub extends Super{
  4.  int x;
  5.  
  6.  
  7. void show(){
  8.  System.out,println("Inside Sub class Show method");
  9. }
  10. void msg(){
  11.  System.out,println("Inside Sub class msg method");
  12. }
  13. public static void main(String[] args) {
  14.         
  15. Sub obj= new Sub ();
  16. obj.x=10;
  17. System.out,println(obj.x);
  18.  obj.show();
  19. obj.print();
  20. }
  21. }







Program #4: core java online test for beginners and experienced on inheritance
  • Creating object for sub class and assigning to super class reference.

  1. package interviewprograms.instanceofjava;
  2. public class Super{
  3.  
  4.  int a, int b;
  5.  
  6. void show(){
  7.  System.out,println("Inside Show method");
  8. }
  9.  
  10. void print(){
  11.  System.out,println("Inside super class print method");
  12. }
  13.  
  14. }


core java online test for beginners






Program #5: core java online test for beginners and experienced on inheritance

  • Creating object for sub class and assigning to super class reference and calling sub class method.
  1. package interviewprograms.instanceofjava;
  2. public class Super{
  3.  
  4.  int a, int b;
  5.  
  6. void show(){
  7.  System.out,println("Inside Show method");
  8. }
  9.  
  10. void print(){
  11.  System.out,println("Inside super class print method");
  12. }
  13.  
  14. }


  1. package interviewprograms.instanceofjava;
  2.  
  3. public class Sub extends Super{
  4.  int x;
  5.  
  6.  
  7. void show(){
  8.  System.out,println("Inside Sub class Show method");
  9. }
  10.  
  11. void msg(){
  12.  System.out,println("Inside Sub class msg method");
  13.  
  14. public static void main(String[] args) {
  15.         
  16. Super obj= new Sub (); 
  17. obj.msg();
  18. }
  19. }





EnJoY LeArNinG  WitH Us...

Java programming interview questions and answers for experienced

  • Here some of the java programming interview questions and answers for experienced on different topics.
  • Java interview programs and answers for experienced.
  • Java Coding interview Questions
  • Java tricky interview programs to practice.




 Program #1: what will happen if we try to print null using system.out.println

  1. package interviewprograms.instanceofjava;
  2. public class InterviewProgram {
  3.  
  4.     /**
  5.      * @java programming interview questions and answers for freshers and experienced
  6.      */
  7.     public static void main(String[] args) {
  8.         
  9.         System.out.println(null);
  10.  
  11.     }
  12.  
  13. }






Program #2: Java Interview program :Can we create object for abstract class in same class

  1. package interviewprograms.instanceofjava;
  2. public abstract class AbstractDemo {
  3.  
  4. public static void main(String args[]){
  5.         
  6.         AbstractDemo obj = new AbstractDemo();
  7.         
  8.  }
  9.  
  10. }





Program #3: Java Interview program : what will be the output of below java program


Java programming interview questions and answers for experienced





 Program #4: Guess the order of execution of constructors

  1. package interviewprograms.instanceofjava;
  2. public class ConstructorDemo {
  3.  
  4. ConstructorDemo(){
  5.         this(1);
  6.         System.out.println("Zero argument constructor");
  7. }
  8.     
  9. ConstructorDemo(int a){
  10.         this("Hi",1);
  11.         System.out.println("One argument constructor");
  12. }
  13.  
  14. ConstructorDemo(String str, int x){
  15.     
  16.         System.out.println("Two argument constructor");
  17. }
  18.  
  19. public static void main(String[] args) {
  20.  
  21.         ConstructorDemo obj =new ConstructorDemo();
  22.  
  23.     }
  24.  
  25. }





How to find Biggest Substring in between specified character or String

1. Java Program to find biggest substring in between specified character or string

String: i am rajesh kumar ravi

in between: 'a'

 

  1. package com.instaceofjava;
  2.  
  3. public class BiggestSubString{
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String str="i am rajesh kumar ravi";
  8.  
  9.  String longest="";
  10.  int maxlength=0;
  11.  
  12.  String arr[]=str.split("a");
  13.  
  14. for (int i = 1; i < arr.length-1; i++) {
  15.  
  16.    System.out.println(arr[i]); // printing substrings
  17.  
  18.           if(arr[i].length() > maxlength){
  19.                maxlength = arr[i].length();
  20.                 longest = arr[i];
  21.             }   
  22.  
  23.    }      
  24.   
  25. System.out.println("Longest substring is: "+longest);
  26.  
  27. }
  28. }


Output:

  1. m r
  2. jesh kum
  3. r r
  4. Longest substring is: jesh kum


Java Basic Interview Programming Questions on Constructors

  • Below programs are the basic programs frequently asking in java quizzes  try to test your java programming skills by answering the questions. if you are having any doubts feel free to ask us.
  • Java Coding Questions on constructors.


1.What will be the Output of this program.

  1. public class Test1{
  2.  
  3. Test1(int i){
  4.  
  5. System.out.println("Test1 Constructor "+i);
  6.  
  7.  } 
  8. }

  1. public class Test2{
  2.  
  3. Test1 t1= new Test1(10);
  4.  
  5. Test2(int i){
  6.  
  7.  System.out.println("Test2 Constructor "+i);
  8.  

  9. public static void main(String[] args) {
  10.  
  11.         Test2 t2= new Test2(5);
  12.  
  13.     }
  14. }







2.What will be the Output of this program.

  1. public class A{
  2.  
  3. A(){
  4.  
  5.   System.out.println("A Class Constructor ");
  6.  
  7. }
  8.  
  9. }

  1. public class B extends A{
  2.  
  3. B(){
  4.  
  5.   System.out.println("B Class Constructor ");
  6.  
  7. }
  8. public static void main(String[] args) {
  9.  
  10.         B ob= new B();
  11.  
  12.     }
  13. }







3.What will be the Output of this program.

  1. public class  A{
  2.  
  3. A(){

  4. this(0);
  5. System.out.println("Hi ");
  6.  
  7.  
  8. A(int x){

  9. this(0,0);
  10. System.out.println("Hello");
  11.  
  12. }
  13.   
  14. A(int x, int y){
  15.  
  16. System.out.println("How are you");
  17.  
  18. }
  19. public static void main(String[] args) {
  20.  
  21.         A ob= new A();
  22.  
  23.     }
  24. }




Bubble sort algorithm in java with example

  Java Program to sort array using bubble sort

  1. package com.instaceofjava; 

  2. public class BubbleSortExample{
  3.   
  4. int[] array={4,2,5,6,9,1};
  5.  
  6. int n = array.length;
  7. int k;
  8.  
  9. for (int m = n; m>= 0; m--) {
  10.  
  11. for (int j = 0; j < n-1; j++) {
  12.  
  13.    k = j + 1;
  14.  
  15.  if (array[j] > array[k]) {
  16.  
  17.        int temp;
  18.        temp = array[j];
  19.        array[j] = array[k];
  20.        array[k] = temp;
  21.  
  22. }
  23. }
  24.            
  25. for (int x = 0; x < array.length; x++) {
  26.  
  27. System.out.print(array[x] + ", ");
  28.  
  29.  }
  30.  
  31. System.out.println();
  32. }  
  33.  
  34. }
  35.  
  36. }



Output:

  1. 2, 4, 5, 6, 1, 9, 
  2. 2, 4, 5, 1, 6, 9, 
  3. 2, 4, 1, 5, 6, 9, 
  4. 2, 1, 4, 5, 6, 9, 
  5. 1, 2, 4, 5, 6, 9, 
  6. 1, 2, 4, 5, 6, 9, 
  7. 1, 2, 4, 5, 6, 9,



AtomicInteger in Java


  • Java.util.concurrent.atomic package provides very useful classes that support lock free and thread safe programming.
  • The main use of this class is an int value that may be updated automatically.
  • AtomicInteger has some useful methods. Before that lets see the some points about this class.
  • Commonly we will use this AtomicInteger to handle the counter that is accessible by different threads simultaneously.

Java.util.concurrent.atomic.AtomicInteger:

  1. public class AtomicInteger
  2. extends Number
  3. implements Serializable

AtomicInteger Class Constructors:


  • public AtomicInteger(): Creates a new AtomicInteger object with default value 0.
  1. AtomicInteger atomicInteger = new AtomicInteger();
  • public AtomicInteger(int initialValue): Creates a new AtomicInteger object with given initial  value.
  1. AtomicInteger atomicInteger = new AtomicInteger(10);


 AtomicInteger Class Methods:


 1.public final void set(int newValue):
  •  Sets given value to the object.

  Java Program to create AtomicInteger class object and sets some value.

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.   System.out.println(atomicInteger);
  12.   atomicInteger.set(10);
  13.   System.out.println(atomicInteger);
  14.  
  15. }
  16.  
  17. }

Output:

  1. 0
  2. 10

2, public final void get():

  • Used to get current value.

Java Program to create AtomicInteger class object and sets some value and get.

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.   System.out.println(atomicInteger.get());
  12.   atomicInteger.set(10);
  13.   System.out.println(atomicInteger.get());
  14.  
  15. }
  16.  
  17. }

Output:

  1. 0
  2. 10
3.public final int getAndSet(int newValue):
  • Automatically sets the given value and returns old value.

  Java Program which explains getAndSet(int x) method of AtomicInteger class

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.    System.out.println(atomicInteger.get());
  12.  
  13.    atomicInteger.set(10);
  14.  
  15.    System.out.println(atomicInteger.get());
  16.  
  17.    System.out.println(atomicInteger.getAndSet(12));
  18.  
  19.    System.out.println(atomicInteger.get());
  20.  
  21. }
  22.  
  23. }

Output:

  1. 0
  2. 10
  3. 10
  4. 12



4.public final int incrementAndGet()
  • Automatically increments the value one and returns updated value

  Java Program which explains incrementAndGet() method of AtomicInteger class

  1. package com.instaceofjava;
  2.  
  3. import java.util.concurrent.atomic.AtomicInteger;
  4.  
  5. public class AtomicIntegerExample{
  6.  
  7. public static void main(String[] args) {
  8.  
  9. AtomicInteger atomicInteger = new AtomicInteger();
  10.  
  11.    System.out.println(atomicInteger.get());
  12.  
  13.    atomicInteger.set(10);
  14.  
  15.    System.out.println(atomicInteger.get());
  16.  
  17.    System.out.println(atomicInteger.incrementAndGet());
  18.  
  19.  
  20. }
  21.  
  22. }

Output:

  1. 0
  2. 10
  3. 11


How to create immutable class in java

  • In Java String and all wrapper classes are immutable classes.
  • So how to create custom immutable class in java?
  • Lets see how to make a class object immutable.

  Immutable class:

  • Make class final so that it should not be inherited.
  • All the variables should be private so should not be accessible outside of class. 
  • Make all variables final so that value can not be changed.
  • A constructor to assign values to variables in class.
  • Do not add any setter methods.

1. Java Program to create custom immutable class object in java.

  1. package com.instaceofjava;

  2.  
  3. public final class ImmutableClass{
  4.   
  5. private final int a;
  6. private final int b;
  7.  
  8. ImmutableClass( int x, int y){
  9.  
  10.  a=x;
  11.  b=y; 

  12.  
  13. public getA(){
  14.  
  15.  return a;

  16. }
  17.  
  18. public getB(){
  19.  
  20.  return b;

  21. }
  22.  
  23. public static void main(String[] args) {
  24.  
  25. ImmutableClass obj= new ImmutableClass(10,20);
  26.  
  27. System.out.println("a="+obj.getA());
  28.  
  29. System.out.println("b="+obj.getB());
  30.  
  31. }
  32. }
Output:

  1. a=10
  2. b=20


String class in java: Immutable


  1. public final class String
  2.         implements java.io.Serializable, Comparable<String>, CharSequence
  3. {  
  4.   
  5. //String class variables

  6.   private final char value[];
  7.   private final int offset;
  8.   private final int count;
  9.   private int hash; // Default to 0
  10.   private static final ObjectStreamField[] serialPersistentFields =
  11.       new ObjectStreamField[0];
  12.   
  13. //String class constructor
  14. public String(String original) {
  15.  
  16.             int size = original.count;
  17.              char[] originalValue = original.value;
  18.              char[] v;
  19.              if (originalValue.length > size) {
  20.                 // The array representing the String is bigger than the new
  21.               // String itself.  Perhaps this constructor is being called
  22.                 // in order to trim the baggage, so make a copy of the array.
  23.                  int off = original.offset;
  24.                 v = Arrays.copyOfRange(originalValue, off, off+size);
  25.             } else {
  26.                  // The array representing the String is the same
  27.                  // size as the String, so no point in making a copy.
  28.                  v = originalValue;
  29.            }
  30.             this.offset = 0;
  31.              this.count = size;
  32.             this.value = v;
  33.         } 

  34. }



Java Program to find Sum of Digits


1. Java Program to find sum of digits without using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. int number;
  9. Scanner in = new Scanner(System.in);
  10.  
  11. System.out.println("Please Enter a number");
  12.  
  13. number=in.nextInt(); 
  14.  
  15. int sum=0 ;
  16.  
  17. while(number!=0){
  18.  
  19. sum=sum+(number%10);
  20. number=number/10;
  21. }
  22.  
  23. System.out.println("Sum of Digits ="+sum);
  24.  
  25. }
  26. }
Output:

  1. Please Enter a number
  2. 123
  3. Sum of Digits=6


2. Java Program to find sum of digits using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. int sum;

  7. public int CalRecSum(int n){
  8.  
  9. if(n==0){
  10. return sum;
  11. }
  12. else{
  13.  
  14.  sum+=n%10;
  15.  CalRecSum(n/10);
  16.  
  17.  
  18. return sum;
  19. }

  20. public static void main(String[] args) {
  21.  
  22. int number;
  23. Scanner in = new Scanner(System.in);
  24.  
  25. System.out.println("Please Enter a number");
  26.  
  27. number=in.nextInt(); 
  28.  
  29. SumOfDigits   ob= new SumOfDigits();
  30. System.out.println("Sum of Digits ="+ob.CalRecSum(number));
  31.  
  32. }
  33.  
  34. }


Output:

  1. Please Enter a number
  2. 326
  3. Sum of Digits=11

Swap two numbers without using third variable

1. Java Interview Program to Swap two numbers without using third variable in java



  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1+number2;
  15. number2=number1-number2;
  16. number1=number1-number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20

2. Java Program to Swap two numbers by using division and multiplication.


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=20;
  8. int number2=30;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1*number2;
  15. number2=number1/number2;
  16. number1=number1/number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }


Output:

  1. Before Swapping
  2. Value of number1 is :20
  3. Value of number2 is :30
  4. After Swapping
  5. Value of number1 is :30
  6. Value of number2 is :20


3. Java Program to Swap two integers by using bit wise operators


  1. package com.instaceofjava;
  2.  
  3. public class SwapTwoNumbers {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int number1=2;
  8. int number2=4;
  9.  
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of number1 is :" + number1);
  12. System.out.println("Value of number2 is :" +number2); 
  13.  
  14. number1=number1^number2;
  15. number2=number1^number2;
  16. number1=number1^number2;
  17.  
  18. System.out.println("After Swapping");
  19. System.out.println("Value of number1 is :" + number1);
  20. System.out.println("Value of number2 is :" +number2);
  21.  
  22. }
  23. }
Output:

  1. Before Swapping
  2. Value of number1 is :2
  3. Value of number2 is :4
  4. After Swapping
  5. Value of number1 is :4
  6. Value of number2 is :2


Reverse words in a String

1. Java Interview Program to Reverse words in a string


  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String strng= "Instance of Java ";
  8.  
  9. String str[] =strng.split(" ");
  10.  
  11. String result="";
  12.  
  13. for(int i=str.length()-1;i>=0;i--){
  14.  
  15. result += str[i]+" ";
  16.  
  17. }
  18.  
  19. System.out.println(result );
  20. }
  21. }
Output:

  1. Java of Instance



2. Java Interview Program to Reverse words in a string


  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String strng= "Instance of Java ";
  8.  
  9. StringBuilder sb = new StringBuilder(strng.length() + 1);
  10.  
  11.   String[] words = strng.split(" ");
  12.  
  13.   for (int i = words.length - 1; i >= 0; i--) {
  14.          sb.append(words[i]).append(' ');
  15.    }
  16.     
  17.     sb.setLength(sb.length() - 1); 
  18.  
  19.    String result= sb.toString();  
  20.  
  21.     System.out.println(result);

  22. }
  23. }
Output:

  1. Java of Instance

Program Check even or odd without using modulus and division operators

write a progrma to check number is even or odd without using modulus or divition

  • Checking the number even or odd program is very easy. Anybody can solve this but there is a condition we need to see.
  • When we get this question in interview "write a program to check given number is even or odd" always continues with "without using modulus and division operators".
  • Before going to actual program lets see how to check a number is even or odd by using modulus and division operators.

 

 

Program to check number is even or odd by using modulus "%" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number % 2)==0){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 37
  3. 37 is Odd Number


Program to check number is even or odd by using division "/" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number / 2)*2==number){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 46
  3. 46 is Even Number


Without using modulus and division operators:

  • The above two programs will check number is even or odd and displays result. 
  • Now we need to write a program to check even or odd without using modulus and division operators.
  • It is very simple if you know about operators including "BIT WISE".
  • Yes using Bit Wise AND "&" operator we can check a number is even or odd.
  • Before starting our program lets see how this bit wise AND "&" operator will work.

Bitwise Operators :

  • Bit wise operators will work on bits at a time.
  • AND : 1 & 1=1
  • OR :     0 | 1= 1 , 1 | 0=1 , 1| 1= 1
  • XOR:   0 ^ 1= 1 , 1^ 0=1
  • NOT : !0=1
  • Take two number 2 and 3
  • 010 : 2
    011 : 3
    ------
    010 : 2
  • ------
  • Take two numbers 2 and 1
  • 010  :2
    001  :1
    -----
    000  :0
    -----
  • From above example we can say that on every even number & 1 gives 0.
  • So this is our logic to be implemented in our program  if "Number & 1==0" then its even number.

Program to check number is even or odd by using  "&" operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if((number & 1)==0){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }


Output:

  1. Enter a number to check even or odd
  2. 9
  3. 9 is Odd Number


Using Shift Operators:

  • We can check even or odd by using shift operators also may be it is not a better solution but  trying to cover alternative.
  • Lets see how shift operators will work
  • Lets do this 2 >> 1
  • 2 means 010 so now we need to shift right side by 1 place
  • 010
    -----
    001
  • Here we added one "0" to the left side to shift right 
  • So the value became 1
  • Now will try left shift  001 >> 1
    001
    ----
    010
  • 010<<1=001(1) and 001 >> 001=010(2)
  • By this we can say if a (number >>1)<<1 gives same then that is even number. result=input
  • Lets check for odd number 3
  • 011>>1=001 which is 1 and 001<<1=010 which is 2 so (3>>1)>>1=2 so result!=input

Program to check number is even or odd by using Shift operator

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class EvenorOdd {
  5.  
  6. public static void main(String []args )    {
  7.  
  8.     int number;
  9.     Scanner in= new Scanner(System.in);
  10.  
  11.     System.out.println("Enter a number to check even or odd");
  12.     number=in.nextInt();
  13.  
  14.     if( ( number >> 1) <<1==number){
  15.         System.out.println(+number+" is Even number");
  16.     }else{
  17.         System.out.println(+number+" is Odd Number");
  18.     }
  19.  
  20. }
  21. }

Output:

  1. Enter a number to check even or odd
  2. 64
  3. 64 is Even Number
Here is the another solution for this.

  1. package instanceofjava;
  2. import java.util.Scanner;
  3.  
  4. class EvenOrOddDemo
  5. {
  6.  
  7. public static void main(String[] args)
  8. {
  9.  
  10. Scanner sc=new Scanner(System.in);
  11.  
  12. System.out.println("Enter a number to check whether it is even or odd without using Modulus
  13. and Division: ");
  14.  
  15. int n=Integer.parseInt(sc.next());
  16. float f=(float)n/(float)2;
  17. int d=(int)f*2;
  18.  
  19. if(d==n)
  20. System.out.println(n+" is a even number");
  21. else
  22. System.out.println(n+" is a odd number");
  23. }

  24. }

Output:

  1. Enter a number to check whether it is even or odd without using Modulus and Division
  2. 4
  3. 4 is Even Number



You might like:

Select Menu