How to subtract X days from a date using Java calendar and with java 8

  • To subtract "X" days from a date in java of calendar class object.
  • calendar.add(Calendar.DAY_OF_MONTH, -X);
  • add method of calendar has a option to subtract days from given date.
  • Lets see and example program on how to subtract days from a date in java 



 Program #1: Java Example program to subtract 2 days from current date using calendar class.

  1. package com.javadate;
  2.  
  3. import java.util.Calendar;
  4. /**
  5. * how to subtract date in java
  6. * @author www.instanceofjava.com
  7. */
  8. public class SubtractDateJava {
  9.  
  10.     public static void main(String[] args) {
  11.         
  12.         Calendar calendar = Calendar.getInstance(); // this would default to now
  13.         
  14.         System.out.println(calendar.getTime());
  15.         //subtract  two days from todays date.
  16.         calendar.add(Calendar.DAY_OF_MONTH, -2);
  17.         
  18.         System.out.println(calendar.getTime());
  19.         
  20.     }
  21.  
  22. }

Output:

  1. Sun May 07 22:17:22 IST 2017
  2. Fri May 05 22:17:22 IST 2017

Java 8 subtract dates

  • We can subtract days from given date in java without using calendar class also.
  • Now in Java 8 we have LocalDateTime class. and it provides a method to subtract days from given date.
  • LocalDateTime.now().minusDays(30);

Program #2: Java Example program to subtract 2 days from current date without using calendar class. (Use Java 8)


  1. package com.javadate;
  2.  
  3. import java.time.LocalDateTime;
  4. import java.time.ZoneOffset;
  5. import java.util.Date;
  6. /**
  7. * how to subtract date in java using example program
  8. * @author www.instanceofjava.com
  9. */
  10. public class SubtractDateJava {
  11.  
  12.     public static void main(String[] args) {
  13.         
  14.         
  15.         System.out.println(LocalDateTime.now());
  16.         LocalDateTime dateBefore20Days = LocalDateTime.now().minusDays(20);
  17.         
  18.         System.out.println(dateBefore20Days);
  19.         
  20.         Date date = Date.from(dateBefore20Days.toInstant(ZoneOffset.UTC));
  21.         System.out.println(date);
  22.     }
  23.  
  24. }

Output:

  1. 2017-05-07T22:30:22.308
  2. 2017-04-17T22:30:22.308
  3. Tue Apr 18 04:00:22 IST 2017

Program #3: Java Example program to subtract 2 days from current date without using calendar class. (Use Java 8) Using Eclipse IDE.
 
subtract days from date java

Top 100 java interview questions

  • Now its time to practice some java programs.
  • Here we provided some java interview programs and basic programs with solutions to practice.
  • Java programming exercises for beginners and experienced programmers.
  • We have also provided some java multiple choice questions and answers.
  • Lets see what are the top 100 java interview questions we have listed




java programs to practice

 1.Restricting a class from creating more than three objects.
  •  Restring a class from creating multiple objects or restricting class from creating not more than three objects this type of interview questions will come for experience interview or written tests.

 2.Print message without using System.out.println() method.


3.What happens when we try to print null?


4.Constructor Chaining in java

  • Constructor chaining in java with example programs to practice for freshers [Solution]

5.Fibonacci series with recursion


6. Print pascals triangle.

  •  Java example program to print pascals triangle [Solution]

7.Get top two maximum numbers in an array
  • How to get top two maximum numbers in java [Solution]


8.Merge sort algorithm in java
  • Merge sort algorithm with an example program to practice [Solution]

9.Java Interview Programming questions on this keyword.
  • Here we have provided some java programs and you need to find out the output of the program.
  • Practice and get the output check the programs on this keyword [Solution]

10. Abstract class interview Programming questions


11.Multiple choice interview programs and questions to practice.

  • Multiple choice java interview programs on this keyword [Check here]
  • Core java multiple choice questions with answers on method overloading [Check here]
  • Multiple choice programs to practice on static keyword [Check here]
  • Constructors java interview programs for freshers [Check here]
  • Mentioned questions are top java interview questions and programs

13. Oops concepts Programming questions to practice : Java beginner practice problems

  • Constructor in interface ? [Solution]
  • Can we create private constructor in java ? [Solution]
  • Super keyword in java inheritance ? [Solution]
  • Can we override static methods in java? [Solution] 
  • Can we overload static methods in java? [Solution]  
  • Can we call sub class methods using super class object ? [Solution]

14.Java programming exercises with solutions on java Strings

15.java programming practice questions and answers on collections


16. Exception handling interview questions and programs.

Benefits of arraylist in java over arrays


Disadvantages of arrays:




Advantages / Benefits of arraylist in java:

  • We have some disadvantages of arrays like arrays are fixed in length. and we need to mention size of the array while creation itself.
  • So we have some advantages of arraylist when compared to arrays in java.
  • Here  the major advantages of arraylist over arrays.

1.ArrayList is variable length
  • One of the major benefit of arraylist is it is dynamic in size. we can increase as well as decrease size of the arraylist dynamically.
  • Resizable.
Program #1: Java example program to explain the advantages of ArrayList: resizable


  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.  public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list.size());      
  21.         list.add(4);
  22.         list.add(5);
  23.  
  24.         System.out.println(list.size());     
  25.         list.remove(1);
  26.  
  27.         System.out.println(list.size());    
  28.     }
  29. }

Output:

  1. 3
  2. 5
  3. 4
  • In the above program by using add and remove methods of ArrayList we can change the size of the ArrayList

2.Default initial capacity is 10.
  • One of the major benefit of arraylist is by default it will assign default size as 10.
  • Whenever we create object of ArrayList constructor of ArrayList assign default capacity as 10.

3.Insert and remove elements also at particular position of  ArrayList
  • Another advantage of ArrayList is it can add and remove elements at particular position.

Program #2: Java example program to explain the advantages of ArrayList:Add and remove elements at particular position.

  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<Integer> list = new ArrayList<Integer>();
  13.          
  14.         list.add(1);
  15.  
  16.         list.add(2);
  17.  
  18.         list.add(3);
  19.  
  20.         System.out.println(list);
  21.  
  22.         list.add(0,4);
  23.         
  24.         System.out.println(list);
  25.         
  26.         list.add(2,5);
  27.  
  28.       
  29.         System.out.println(list);
  30.         list.remove(3);
  31.         
  32.         System.out.println(list);
  33.         System.out.println(list.size());    
  34.     }
  35. }

Output:

  1. [1, 2, 3]
  2. [4, 1, 2, 3]
  3. [4, 1, 5, 2, 3]
  4. [4, 1, 5, 3]
  5. 4


4.Add any type of data into ArrayList.
  • We can add different type of objects in to the ArrayList.
  • In this scenario avoid mentioning generics while declaring ArrayList.

Program #3: Java example program to explain the advantages of ArrayList: Add any type of Object.

arrayList advantages in java

5.Traverse in both directions.
  • We can traverse both direction using List Iterator.

Program #4: Java example program to explain the advantages of ArrayList: Traverse in both directions.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.ListIterator;
  5.  
  6. public class ArrayListExample {
  7.     /**
  8.     * Advantages of arrayList over arrays in java
  9.     * @author www.instanceofjava.com
  10.     */
  11.     public static void main(String[] args) {
  12.         
  13.         ArrayList<String> list = new ArrayList<String>();
  14.          
  15.         list.add("ArrayList Advantages");
  16.  
  17.         list.add("ArrayList benefits");
  18.         
  19.         list.add("ArrayList in java");
  20.  
  21.         ListIterator iterator = list.listIterator();
  22.         
  23.         System.out.println("**ArrayList Elements in forward direction**");
  24.          
  25.         while (iterator.hasNext())
  26.         {
  27.             System.out.println(iterator.next());
  28.         }
  29.          
  30.         System.out.println("**ArrayList Elements in backward direction**");
  31.          
  32.         while (iterator.hasPrevious())
  33.         {
  34.             System.out.println(iterator.previous());
  35.         } 
  36.     }
  37. }
 Output:

  1. **ArrayList Elements in forward direction**
  2. ArrayList Advantages
  3. ArrayList benefits
  4. ArrayList in java
  5. **ArrayList Elements in backward direction**
  6. ArrayList in java
  7. ArrayList benefits
  8. ArrayList Advantages

6.ArrayList allows Multiple null values
  • We can add multiple null elements to ArrayList

Program #5: Java example program to explain the benefits of ArrayList: Add null elements
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.         arraylist.add(null);
  15.  
  16.         arraylist.add(null);
  17.         
  18.         arraylist.add(null);
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [null, null, null]

7.ArrayList allows to add duplicate elements
  • We can add duplicate elements into arrayList
Program #6: Java example program to explain the advantages of ArrayList: Add any type of Object.
  1. package collections;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. public class ArrayListExample {
  6.     /**
  7.     * Advantages of arrayList over arrays in java
  8.     * @author www.instanceofjava.com
  9.     */
  10.     public static void main(String[] args) {
  11.         
  12.         ArrayList<String> arraylist = new ArrayList<String>();
  13.          
  14.        arraylist.add("ArrayList");
  15.  
  16.         arraylist.add("ArrayList");
  17.         
  18.         arraylist.add("ArrayList");
  19.  
  20.         System.out.println(arraylist);
  21.     }
  22. }

Output:

  1. [ArrayList, ArrayList, ArrayList]

8.ArrayList has many methods to manipulate stored objects.
  • ArrayList has many methods to manipulate stored objects.
  • addAll(), isEmpty(). lastIndexOf() etc.

Advantages and disadvantages of arrays in java


Disadvantages of array in java
  • Arrays are Strongly Typed.
  • Arrays does not have add or remove methods.
  • We need to mention the size of the array. Fixed length.
  • So there is a chance of memory wastage.
  • To delete an element in an array we need to traverse through out the array so this will reduce performance.
  • Arrays have a fixed size, which means that their size cannot be changed once they are created. This can be a disadvantage when working with dynamic data sets that need to grow or shrink in size.
  • Arrays are not suitable for storing large numbers of different types of elements, it is best used when the data is of a single type.
  • Insertion and deletion operations on arrays can be slow, as they require shifting elements to make room for new elements or close the gap left by deleted elements.
  • Accessing an element in an array can be slow if the array is large, and the index of the element is not known in advance.



Advantages of arrays:


  • We can access any element randomly by using indexes provided by arrays.
  • Primitive type to wrapper classes object conversion will not happen so it is fast.
  • Array can store many number of elements at a time.
  • Arrays have a fixed size, which means that their size cannot be changed once they are created. This can make it easier to manage memory usage and avoid runtime errors caused by dynamic memory allocation.
  • Arrays are relatively fast and efficient. They have a constant time complexity for basic operations such as accessing and updating elements, which makes them suitable for large data sets.
  • Arrays are easy to understand and use, and they are supported by many built-in methods in the Java API, such as Arrays.sort(), Arrays.binarySearch(), and Arrays.toString().



Arrays in java   InstanceOfJava

Java interview programs on arrays:

  • Check below for some of the interesting java interview programs on arrays.

Five different ways to print arrays in java:



Creating array of objects in java:



Java program to find missing numbers in an array:



Find second highest number in java arrays:




Convert arrayList to array:

Copy all elements of  hash set to Object array:


Java xor operator with example programs


Java Bitwise XOR operator:

In Java, you can use the ^ operator to perform a bitwise exclusive or (XOR) operation on two integers. The XOR operation compares each bit of the first number to the corresponding bit of the second number. If the bits are the same, the corresponding result bit is set to 0.  
The matching result bit is set to 1 if the bits vary.
Here's an example:

int a = 12; // binary: 1100
int b = 25; // binary: 11001
int result = a ^ b;
System.out.println("Result of XOR operation: " + result);

In this example, the XOR operation compares the bits of the integers a and b. Since the bits at positions 2 and 3 are different, the corresponding result bits are set to 1. Therefore the binary representation of result is 01101 which decimal representation is 13
This will output:

Result of XOR operation: 13

It's important to note that XOR operation is not only limited to integers. You can also perform it on bytes or even on bytes of an array, by applying the operation on each element of array.


byte[] array1 = {0, 1, 2, 3, 4, 5};
byte[] array2 = {5, 4, 3, 2, 1, 0};
byte[] result = new byte[6];

for (int i = 0; i < 6; i++) {
    result[i] = (byte) (array1[i] ^ array2[i]);
}

It's also useful for some cryptographic algorithms for example the One Time Pad encryption, where the XOR operation is used to encrypt and decrypt the data.
  • Java bit wise Xor operator operates on bits of numbers.
  • It will be represented as "^".
  • XOR will return true if  both bits are different.
  •  For example 1 XOR 0 gives 1. Ex: 1^0=1.
  • 0^1=1.




Java Bitwise Xor:

Java bitwise XOR operator


Program#1:Java Example program on two integer numbers Xor operation.


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         int a=1;
  9.         int b=0;
  10.         int c= a^b;
  11.         
  12.         System.out.println(c);
  13.  
  14.     }
  15.  
  16. }
Output:

  1. 1

Program #2: java xor boolean expression : java example program


  1. package com.Xorinjava;
  2.  
  3. public class XOR {
  4.     /**
  5.     * Xor in java boolean Xor example program
  6.     * @author www.instanceofjava.com
  7.     */
  8. public static void main(String[] args) {
  9.         boolean a=true;
  10.         boolean b=false;
  11.         boolean c= a^b;
  12.         
  13.         System.out.println(c);
  14.         
  15.         System.out.println(false^false);
  16.         System.out.println(true^true);
  17.  
  18.     }
  19.  
  20. }

Output:


  1. true
  2. false
  3. false
Program #3: java xor boolean expression and integer : java example program Using Eclipse IDE.

java Xor operator

Java Xor Strings:

  • Gives compile time error.
  • The operator ^ is undefined for the argument type(s) java.lang.String, java.lang.String

Program #4: Java Xor of two strings


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java boolean Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         String str="a";
  9.         String str1="b";
  10.         System.out.println(str^str1);// compile time error: The operator ^ is undefined for the
  11. argument type(s) java.lang.String, java.lang.String
  12.  
  13.     }
  14.  
  15. }


 Xor of Binary Strings:

Program #5: Java xor of two binary strings.


  1. package com.Xorinjava;
  2. public class XOR {
  3.     /**
  4.     * Xor in java String bits Xor example program
  5.     * @author www.instanceofjava.com
  6.     */
  7.     public static void main(String[] args) {
  8.         String str1="1010100101";
  9.         String str2="1110000101";
  10.         StringBuffer sb=new StringBuffer();
  11.         
  12.         for (int i = 0; i < str1.length(); i++) {
  13.             
  14.             sb.append(str1.charAt(i)^str2.charAt(i));
  15.             
  16.         }
  17.        System.out.println(sb);
  18.     }
  19.  
  20. }
Output:


  1. 0100100000

How to get first two characters of a string in java

  • We can get first  two character of a string in java by using subString() method in java
  • To get first N numbers of a string s.substring(0,n);
  • Lets see an example java program on how to get first two characters or first N characters.
In Java, you can use the charAt() method to get the first character of a string. The charAt() method takes an index as a parameter and returns the character at that index. 
To get the first character of a string, you can pass in the index 0 to the charAt() method.

Here's an example:


String str = "Hello, World!";
char firstChar = str.charAt(0);
System.out.println("First character: " + firstChar);

This will output:
First character: H



Program #1: Java Program to get first two characters of a String.



  1.  package StringInterviewprograms;
  2.  
  3. public class GetFirstTwoCharacters {
  4.  
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9.  
  10. public static void main(String[] args) {
  11.         
  12.         String str="Get first two characters of a String";
  13.         
  14.         System.out.println(str.substring(0,2));
  15. }
  16.     
  17.     
  18. }
     
Output:

  1.  Ge

  Program #2:


  1. package StringInterviewprograms;
  2. import java.util.Scanner;
  3.  
  4. public class GetFirstTwoCharacters {
  5. /**
  6. * How to get First N characters in java 
  7. * @author www.instanceofjava.com
  8. */
  9. public static void main(String[] args) {
  10.         
  11.          Scanner sc= new Scanner(System.in);
  12.          
  13.          System.out.println("Please Enter a String");
  14.          
  15.          String str=sc.next();         
  16.         if(str.length()>=2){
  17.  
  18.             System.out.println(str.substring(0,2));
  19.         }else{
  20.             System.out.println("please enter a string with minimum length of 2.");
  21.         }
  22.         }
  23.  
  24.   }

 Output:


  1. Please Enter a String
  2. miss you
  3. mi


Get First Two characters String Java
Select Menu