Java Log and StackTrace

log method using stackTrace in Java

   A custom log() method can used to print a message with a details like which class which function
   called the log at which line number. It is useful for debugging.


  1 public class Main {
2 public static void func() {
3 Log.log("\"log msg\"");
4 }
5
6 public static void main(String[] args) {
7 func();
8 Log.log("printing log in main");
9 }
10 }
11
12 class Log {
13
14 public static void log(String s) {
15 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
16 String className = stackTrace[2].getClassName();
17 String caller = stackTrace[2].getMethodName();
18 int lineNo = stackTrace[2].getLineNumber();
19 System.out.println("[class-name : " + className + "], [caller-function : "
20 + caller + "], [ line-no : "+ lineNo+ "], " + s);
21 }
22 }
Output:
[class-name : Main],  [caller-function : func], [ line-no : 3], “log msg”
[class-name : Main],  [caller-function : main], [ line-no : 8], printing log in main

Java Date and Calendar Class.

Get the Current Date:

Date today = new Date();
System.out.println(“Current date: “ + today);
OUTPUT:
date: Sat May 04 02:29:59 IST 2019

Difference between dates:

Date currentTime = new Date(); Thread.sleep(3000); //Waits for 3 seconds. Date newTime = new Date();
//diferrence in ms. long msDelay = newTime.getTime() currentTime.getTime();

Check Whether Time Interval has Passed:

public static void main(String[] args) throws Exception { Date startTime = new Date(); long deadLine = startTime.getTime() + 3000; // +3 seconds
Date deadLineDate = new Date(deadLine); Date currentTime = new Date();
int secondsCount = 0;
while(!currentTime.after(deadLineDate))// Check whether currentTime is after deadLineDate {
Thread.sleep(1000); // Sleep for 1 sec.
secondsCount++;
System.out.println(secondsCount + ” seconds have passed.”);
currentTime = new Date();
}
System.out.println(“Reached DeadLine!”);}

Output:
1 seconds have passed. 2 seconds have passed. 3 seconds have passed. Reached DeadLine!

Using getTime()
public class Main { public static void main(String[] args) {


Date startTime = new Date();

long deadLine = startTime.getTime() + 3000; // +3 seconds
Date deadLineDate = new Date(deadLine); Date currentTime = new Date();
int secondsCount = 0;
while(currentTime.getTime() < deadLineDate.getTime())// Check whether currentTime is after deadLineDate {
Thread.sleep(1000); // Sleep for 1 sec.
secondsCount++;
System.out.println(secondsCount + ” seconds have passed.”);
currentTime = new Date();
}
System.out.println(“Reached DeadLine!”);

}}

before()
equals()
also work with same syntax as after()

Various get and set methods:

get methods
Date currentTime = new Date();int hours = currentTime.getHours(); // hours passed since midnight. 
int mins = currentTime.getMinutes(); // hours passed since midnight.int secs = currentTime.getSeconds(); // seconds passed since midnight.

set methods
Date yearStartTime = new Date(); 
yearStartTime.setHours(0); 
yearStartTime.setMinutes(0); 
yearStartTime.setSeconds(0); 
yearStartTime.setDate(1); // First day of month
yearStartTime.setMonth(0); // January (months are indexed from 0 to 11)

Calendar class:

Calendar calendar = new GregorianCalendar(2017, 0 , 25);
GregorianCalendar calendar = new GregorianCalendar(2017, Calendar.JANUARY , 25);

set the time 10:30:15 1 Jan 2019

public static void main(String[] args) { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.YEAR, 2019); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 15); System.out.println(calendar.getTime());}

Output:

Tue Jan 01 10:30:15 IST 2019
—————————————————————-

public static void main(String[] args) { Calendar calendar = new GregorianCalendar(2019, Calendar.JANUARY , 1); calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 15); calendar.add(Calendar.MONTH, 2); // Date will automatically adjust into 2018. System.out.println(calendar.getTime());}

output:
Thu Nov 01 10:30:15 IST 2018
——————————————————————
roll() : This method will make change only in particular part, In this example
only Month will be reduced to Nov but years and other time will not be changed.

public static void main(String[] args) { Calendar calendar = new GregorianCalendar(2019, Calendar.JANUARY , 1); calendar.set(Calendar.HOUR, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 15); calendar.roll(Calendar.MONTH, 2); // Date will automatically adjust into 2018. System.out.println(calendar.getTime());}
Output:
Fri Nov 01 10:30:15 IST 2019
——————————————————————

get and set:

calendar.set(Calendar.HOUR, 10);calendar.set(Calendar.MINUTE, 30);calendar.set(Calendar.SECOND, 15); System.out.println(“Year: “ + calendar.get(Calendar.YEAR));System.out.println(“Month: “ + calendar.get(Calendar.MONTH));
——————————————————————-

date format:

SimpleDateFormat dateFormat = new SimpleDateFormat(“EEEE, MMMM d, yyyy”);
Calendar calendar = new GregorianCalendar(2019, Calendar.JANUARY , 1);
System.out.println(dateFormat.format(calendar.getTime()));

output:
Tuesday, January 1, 2019

Difference of days between two dates:

long diff_ms = date1.getTime() – date2.getTime();
days = diff_ms / (24 * 60 * 60 * 1000);


Java Collections

Interface Class/implementation Description
List  ArrayList  List
 LinkedList  List
 Vector  Vector
 Stack  Stack
 Set    HashSet  Set
 TreeSet  Set
 SortedSet  Sorted set
Map  HashMap Map/dictionary
 TreeMap  Map/dictionary
 SortedMap  Sorted dictionary
 Hashtable  Hash-table


Declaration Syntax:

List<String> list = new ArrayList<String>();
Set<String> set = new HashSet<String>();
Map<String, String> map = new HashMap<String, String>();

ADD Elements Syntax:

list.add(“techBuddha”);
set.add(“techBuddha”);
map.put(“key”, “techBuddha”);

Traversing Collection Syntax:

Iterator<String> iterator = list.iterator();while (iterator.hasNext()) {
String text = iterator.next(); System.out.println(text);}
—————————————————-
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) { String text = iterator.next(); System.out.println(text);}
——————————————————
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();while (iterator.hasNext()){ Map.Entry<String, String> pair = iterator.next(); String key = pair.getKey(); String value = pair.getValue(); System.out.println(key + “:” + value);
}
—————————————————–

Traversing Collection with ShortHand Fast For Loop:

for (String text : list) { System.out.println(text); }
——————————————————-
for (String text : set) { System.out.println(text); }
——————————————————-
for (Map.Entry<String, String> pair : map.entrySet()){ String key = pair.getKey(); String value = pair.getValue(); System.out.println(key + “:” + value);}
——————————————————-

Methods for Set:

Operation Method
Add element(s) add(), addAll()
Remove element(s) remove(), removeAll()
Check for the presence of element(s) contains(), containsAll()


Methods for Map:
Operation Method
Get a set of all pairs entrySet()
Get a set of all keys keySet()
Get a set of all values values()
Add a pair put(key, value)
Get the value for the specified key get(key)
Check whether the specified key is present containsKey(key)
Check whether the specified value is present containsValue(value)
Check whether the Map is empty isEmpty()
Clear the Map clear()
Remove the value for the specified key remove(key)

Collection Methods:

ArrayList<Integer> list = new ArrayList<Integer>();

sort() : Collection.sort(list);
max() : Collection.max(list);
min() : Collection.min(list);
reverse() : Collection.reverse(list);
shuffle() : Collection.shuffle(list);
swap() : Collection.swap(list, i, j);


unmodifiableList() : creates immutable arrayList from an array.
List<String> weekEndDays = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(saturday, sunday)));

disjoint() : It checks whether two collections intersect, returns false if intersection is non null otherwise true.

ArrayList<String> list1 = new ArrayList<>(Arrays.asList(sunday, monday, tuesday));ArrayList<String> list2 = new ArrayList<>(Arrays.asList(saturday, sunday));
Collection.disjoint(list1, list2); // will return false, sunday is common.

Collection Initialization:

public static Set join(Set a, Set b)
{
/*Double braces initialization*/
    return new HashSet() {{ addAll(a); addAll(b); }}
}