Coding Cheatsheets

Coding Cheatsheets

C, Java, Unix, Git, Oracle SQL — practical reference guides for developers

7 topics · ~15 min read · Updated Jun 2026

Coding Cheatsheets

 | 

Programming Best Practices

Coding and problem-solving skills are essential for delivering high-quality software applications. Some good practices:

  1. Modular and Efficient Code — Reuse code by writing common functions. Helps with code optimization.
  2. Null checks — Guard clause for validation: check null and return. Proper variable names, null & length checks, set default values wherever possible.
  3. Memory handling — Needs to be done in C programming code.
  4. Initialize/Reset variables — Especially in nested while loops.
  5. Write Code Comments — Makes it easy to read and understand logic. Helps maintain defect-free code.
  6. Make code configurable — For attributes whose values might change.
  7. Refer cache — In order to reduce database calls for better performance.
  8. Code reviews by peers — Helps us learn from each other and improve skills.
  9. Analyse log files — To troubleshoot issues.
  10. Happy Coding — Write great code and use great languages.

Other tips:

  • Embrace simplicity and avoid unnecessary complexity
  • Use built-in features and libraries
  • Be mindful of performance
  • Prioritize human readability; write comments for understanding
  • Use meaningful variable names
  • VSCode is an excellent code editor. GitHub Copilot can be enabled for AI-assisted coding.

Important Functions in C Programming

Function NameDetails
strcmp(str1, str2)Compares two strings and returns zero if they are identical.
strstr(haystack, needle)Find first occurrence of substring needle in haystack.
sprintf(dest, format, ...)Formats and stores output in a character string buffer.
sscanf(str, format, ...)Reads formatted input from a string into provided variables.
strcpy(dest, src)Copies a string from one location to another.
strlen(str)Calculates the length of a given string (excluding the null character).
localtime(timep)Converts time_t variable to a structure of type tm.
mktime(tm_info)Converts structure of type tm to a time_t variable.
strptime(time_str, format, tm_info)Converts time stored in string variable to struct tm according to the given format.
strftime(time_str, size, format, tm_info)Converts struct tm to string for printing to log.
atoi_64(str)Converts string to numeric value.
malloc(size)Dynamically allocates memory on the heap.
free(strp)Deallocates memory previously allocated by malloc(). Prevents memory leaks.

Code snippets for strcmp(), sprintf():

if(str1 && str2 && strcmp(str1, str2) == 0)
{
    sprintf(printbuff, "str1 and str2 are same: %s and %s\n", str1, str2);
}

strstr() & sscanf():

if(str1 && str2 && strstr(str1, str2) != NULL) {
    sprintf(printfbuff, "str2 is present in str1\n");
    sscanf(str1, "%2d", strmmdd); //read first 2 chars from str1 into integer strmmdd
}

The struct tm represents date and time information — used for manipulating and formatting time-related data:

time_t epoch_time = <time-unixtimestamp>
struct tm new_tm = localtime(&epoch_time); //store unix timestamp into struct tm

//Adjust new_tm
new_tm->tm_mon  = <month>;
new_tm->tm_year = <year>;
new_tm->tm_mday = <dayofmonth>;
new_tm->tm_hour = 0;
new_tm->tm_min  = 0;
new_tm->tm_sec  = 0;
new_tm->tm_isdst = -1;

time_t new_unixtime = mktime(&new_tm); //convert struct tm back to epoch

Java Annotations

Annotations help avoid writing boilerplate code and improve coding efficiency. Common Java Annotations:

AnnotationDetails
@AutowiredFacilitates dependency injection — automatically injects Spring beans without explicit instantiation.
@OverrideOverrides the default implementation.
@LogExecutionTimeLogs time taken in execution of function.
@ComponentDesignates a Java class as a Spring-managed component.
@Slf4jLogging annotation for Spring Boot applications.
@RepositoryIndicates a class is a Data Access Object (DAO) or repository for database interaction.
@EntityTreats a Java class as a persistent entity, making database operations easier.
@Getter / @SetterCreates getter and setter functions automatically without explicit definitions.
@ToStringCurrent state of the object is returned as a String when toString() is called.
@IdSpring Data JPA — marks a field as the primary key of an entity.

Note: Lombok is a Java library that generates known patterns of code, allowing us to reduce boilerplate.

Essential Unix Commands

Search string/pattern using grep commands:

grep CommandDetails
grep -n "string" <file>Search string with line numbers displayed.
grep -i "string" <file>Case-insensitive search.
grep -r "string"Recursive search in folders/sub-folders.
grep -E -w "Enter|Exit" <file>-w word match, -E regular expression.
grep "lines.*empty" <file>Matches patterns starting with "lines" and ending with "empty".
grep -A <N> "string" <file>N lines displayed after the match.
grep -B <N> "string" <file>N lines displayed before the match.
grep -C 2 "Example" <file>2 lines from both before and after the match.
grep -c "pattern" <file>Count how many lines match.
grep -v "pattern" <file>Display lines which do NOT match.
grep -v -e "p1" -e "p2" <file>Does not match any of the given patterns.
grep -l "pattern" <file>Display only file names which match.
grep "post_rating.*entering\|post_rating.*exiting" <file>Check for function entry/exit.

Other important Unix commands:

CommandDetails
ps -ef | grep cm | awk -F ' ' '{print $2}'ps to check running processes; awk to select column 2 (delimiter: space).
sed -n -e '18120,18130p' <file>sed to copy lines 18120–18130 from a file.
sed -n '/2024-01-01 10:00/,/2024-01-01 11:00/p' <file>Filter logs by time range.
sed -i 's/bill/invoice/g' <file>Replace word "bill" with "invoice" in a file.
sed -i '/bill/d' <file>Delete lines containing "bill".
grep -n "string" <file> | awk '{print $1}' | cut -d ':' -f1cut to delimit output by colon and print first field.
netstat -a | grep <port>Check if a given port number is in use.
topDisplays CPU usage, memory usage, running processes.
df or duDisplays disk space usage.
jobsLists active jobs running.
nohup <command> &Executes script/command in background (runs even if terminal is terminated).
kill, pkillTerminate process by PID (kill) or by name (pkill).
tailPrints data from the end of a specified file.
vi <file>Widely used text editor in Unix.

Commonly Used Git Commands

Git is widely used as a version control system. Below commands help in managing files in Git:

git CommandDetails
git add <filename>Add one or more files to be checked in.
git add -uAdds all tracked files for staging/committing.
git commit -m "comment"Commit the staged files to the git branch.
git push origin <branchname>Push or check in the commit into the branch.
git statusProvides information about the Git branch and file status.
git branchLists git branches and the current branch checked out.
git checkout <branchname>Checkout/move to a different Git branch.
git checkout <branchname> -- <filename>Get a file from a particular branch.
git pullFetch all the latest files from current branch.
git fetchFetch new branches created from the Git repository.
git reset --hard <branchname>Forceful checkout to a branch if git checkout fails.

Oracle SQL Performance Tuning

Key points to consider for Oracle SQL tuning:

  1. SELECT query tuning — Validate using "Explain Plan" in SQL Developer.
    • Parallel hint (/*+ parallel(8) */) with increased thread count for faster processing.
    • Use columns with index in WHERE clause.
    • Use DB partitions to query data.
    • Use WITH clause for queries to make future changes easier.
    • Use EXISTS instead of COUNT.
    • Leverage Oracle JSON functions (JSON_ARRAYAGG, JSON_VALUE) for multiple column selection.
  2. PL/SQL Performance — Use BULK COLLECT and FORALL for bulk DML updates to reduce context switching.
  3. Oracle SQL Developer shortcuts:
    • Ctrl+F7: Format SQL query
    • Shift+F4: Opens describe window for current object/table at cursor
    • F10: SQL cost estimate (Explain Plan)
    • Export data to XLS or clipboard
    • Import data using sqlldr utility from Unix (faster than insert queries)

Oracle DB Long-Running Queries

If any Oracle Database transaction is taking longer than expected, the DB query processing is likely stuck or waiting for another session to complete.

  • Fetch blocking sessions due to table lock:
    select (select username from v$session where sid=a.sid) blocker, a.sid,
           ' is blocking ',
           (select username from v$session where sid=b.sid) blockee, b.sid
    from v$lock a, v$lock b
    where a.block = 1 and b.request > 0 and a.id1 = b.id1 and a.id2 = b.id2;
  • Percentage completion of long-running sessions:
    select sid, to_char(start_time,'hh24:mi:ss') stime, message,
           (sofar/totalwork) * 100 percent
    from v$session_longops where sofar/totalwork < 1;
  • Fetch active DB sessions:
    select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
    from v$sqltext_with_newlines t, V$SESSION s
    where t.address = s.sql_address and t.hash_value = s.sql_hash_value
      and s.status = 'ACTIVE' and s.username <> 'SYSTEM'
    order by s.sid, t.piece;
  • Kill DB session (if needed):
    select username, sid, serial# from v$session where sid=xxxx;
    alter system kill session 'sid#,serial#';
Please share feedback on this blog at learnbillsoft@gmail.com to help improve it.

Recordings: YouTube channel videos