logo

Method Reference

int[] nums => nums.length;
String str => str.length();
ArrayList<Integer> a => a.size();

Boolean Logic (if statement, switch)

return (a > b && (a-b) >= 2);
         is equivalent to 
if (a > b && (a-b) >= 2){         
    return true; 
}

For Loop Traps

  • for (int i = 0; i < arr.length; i = i+2){ …} // if lenght = 9, loop will run 0,2,4,6.. 8 is never included.
  • for (int i = 1; i < num.length; i++) if (num[i-1] == num[i]) return true;
  • for (int i = 0; i < num.length – 1; i++) if (num[i] == num[i+1]) return true;
  • for (char i = ‘a’; i <= ‘z’; i++){ sout(i); //Prints alphabets from ‘a’ to ‘z’ }

Arrays

  1. int[] a; 
    a = new int[3]; //notice []. NOT () to be used
  2. int[] a = new int[3]; //single line declaration
  3. a.length ; //Length is a "field" in Array, while a method in Strings
  4. int[] a = new int[] {1,2,3};
  5. int[] b = {1,2,3};
  6. sysout(Arrays.toString(num));

The Arrays Class

Import java.util.ArrayList;

  • ArrayList<Integer> b = new ArrayList<Integer>;
  • Arrays.toString(a);//o/p [1,2,3]
  • Arrays.asList(a);
  • Arrays.asList.contains("a");//boolean true/false

String Functions (Most Important)

  1. + ⇒ concatenation
  2. str.chatAt(i);
  3. str.length(); //Method in String, Field in Arrays;
  4. str.substring(i,j);//j not included
  5. str.substring(i);//from i till end str.substring(i,str.length());String Index begins from ZERO, thus lenght = max Index + 1
  6. For Equality str.equals();//DO NOT USE == (will compare objects)
  7. str.indexOf("er");//2 if "er" begins from index 1, -1 if not Found
  8. str.indexOf("er", 2); //start the search from index 2
  9. str.lastIndexOf("ew");//searches right to left
  10. str.lastIndexOf("ew", 5);//right to left, from index 5
  11. str.toLowerCase() / str.toUpperCase()
  12. str.compareTo("");
  13. str.replace("old","new");
  14. String[] ransomWords = ransom.split(" ");//Cut the Strings from spaces into a words

Java Input

Key Board Input

import java.util.Scanner;
Scanner in = new Scanner(System.in);
 int n = in.nextLine();
 in.nextLine(); //To avoid INPUT Problem
 String str = in.nextLine();
/* Input Problem occurs when a mix of int and strings are given
 The extra invocation is done to get rid of previous \n 

16\n 1000\n Joe\n
/n Extra in.nextLine()
 in.nextInt; //reads next integer
 in.nextDouble();
 in.nextLine();//reads entire line of in
 in.next();//next character upto but not including space
/* NO METHOD TO READ A SINGLE CHARACTER */
 char a = in.nextLine.charAt(0);

File Input

//Open the File
File myFile = new File("/nitin/a.txt");
 Scanner in = new Scanner(myFile; //Instead of System.in, take the file to read
//Read from the File
 String str = in.nextLine();
//OR
 while (in.hasNext());
 System.out.println(in.nextLine());
 //Close the File
 in.close();

Output File Handling

Writing text to File
import java.io.PrintWriter;
 final String FILENAME = "nitin.txt";
//Surrounding with try catch!! OR
 PrintWriter output = new PrintWriter(FILENAME); 
 PrintWriter output = new PrintWriter("nitin.txt");
output.println("Nitin"); output.println("Chaurasia");
//To avoid erasing files that already exist
 PrintWriter pw = new PrintWriter(new FileWriter("nitin.txt", true));
Appending Text to file
FileWriter fw = new FileWriter("Names.txt", true);
PrintWriter pw = new PrintWriter(fw);

OR

PrintWriter pw = new PrintWriter(new FileWriter("Names.txt, true"));
Reading Data from a file
File myFile = new File("customer.txt");
Scanner ipFile = new Scanner(myFile); //instead of System.in

Reading, Parsing and Type Checking Command Line Inputs.

/*Assuming 2 command line arguments <Nitin 29>*/

if (args.length == 0 || args.length > 2) {
     System.err.println("Incorrect Number of arguments passed");
     System.exit(-1);
  }
String name = args[0];
  int age = Integer.parseInt(args[1]);

Running time of a method

System.currentTimeMillis();//type long , from Jan 1 1970 
System.nanoTime();

Random

import java.util.Random

  • Random generator = new Random(); //or new Random(123), 123 being the seed
  • generator.nextInt(5);//range 0 to 5, add 1 to get range 1 to 6 (dices)
  • generator.nextInt(); // 2^31 to 2^31 -1
  • generator.nextDouble();//Range: 0.0 to 1.1

Eg: int throw = generator.nextInt(6) + 1;

Array and Linked List

Capture
 
 for (int i = 0; i < arr.length; i++){
      System.out.prinln(arr[i]);
 }
 for (ListNode runner = head; runner != null; runner = runner.next){
      System.out.println(runner.data);
 }

Linked List

 LinkNode runner = front;//head
 while (runner.next != null){//Runner stops at the last node, else runner will end up pointing null!!
 runner = runner.next;

Add in the List

    1. Add in the front

front = new ListNode(value, front);

    1. Add at ‘index’
if (index == 0)
front = new ListNode(value, front);
else{
ListNode runner = front;
for (int i = 0; i < index - 1; i++)//Stop at an index one before the desired
current = current.next;
}
current.next = new ListNode(value, current.next); //old current.next is assigned to the new node which in turn is assigned to current.next
    1. Add in the end

if (front == null)
  front = new ListNode(value, front);
else{
  ListNode runner = front;
  while (runner.next != null) // Go till the last node
      runner = runner.next;
  runner.next = new ListNode(value); //this constructor has .next as null  
}

For Each Loop (Read Only Loop)

for (type name : collection){
 }
Eg: Set<Double> grades = new HashSet<Double>();
for (double g: grades){
   System.out.println(g);
 

Iterator itr (for some collection)

Iterator itr = c.iterator();
 itr.remove(i);
 itr.hasNext();
 itr.next();

The XOR Trick

  • Same variables cancels the effect of each other if the bitwise XOR is used.


a = a^b;
b = a^b; //a^b^b yields a
a = a^b;//a^b^a = b(b is recently converted to a)
(Works only with integer, in its native form, for others change it into its equivalent binary representation)
The logic is used for finding a unique element among duplicates (Stolen Drone problem (21) in Interview cake)

  • Use of XOR (both flags are boolean)


if (flag2 ^ flag4)
is equivalent to
(flag2 && !flag4) || (!flag2 && flag4);

HashMap

Map<String, Integer> ret = new HashMap<String, Integer>();
for (int key : map.keySet()){
ret.put(map.get(key),key);
}

ArrayList

  • Declaration (Child of List Interface)

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

  • Insert element

for (int i = 0; i < list.size(); i++){
list.add(i);
list.get(i);
}

  • Common methods

add(value), add(index, value)
set(index. value)
clear()
indexOf(value)
lastIndexOf()
toString(), toArray();

HASHMAP (IMPLEMENTATION OF HASHTABLE)

Map<String, Integer> ret = new HashMap<String, Integer>();
for (int key : map.keySet()){
ret.put(map.get(key),key);

Java interview Questions

  1. final
    • constant –> modifier (can’t be changed once declared)
    • a method –> no over riding in child class
    • a class –> no extend (inheritance), no child class
  2. finally (Associated with try catch block)
    • try {keep risky code}
    • catch (Exception e) {Handling Code}
    • finally {Clean up code}
  3. finalize() : Method in Object Class
    • Always invoked by Garbage Collector just before destroying the object
    • to perform cleanup activities (like database connection close, socket close)
  4. *** finally cleanup activities for try catch, finalize() cleanup activities for related to objects.

  1. String objects are immutable (every equality with string object creates a new object)
    • String a = “Nitin”; a.concate(Chaurasia);
    • sop(a);// Nitin
    • 2 strings are created (Nitin and Nitin Chaurasia). NC not referenced
  2. StringBuffer objects are mutable
    • StringBuffer sb = new StringBuffer(“Nitin”);
    • sb.append(“Chaurasia”)
    • sop(sb);//nitin chaurasia
  3. StringBuffer (since java 1.0)
    • Synchronized, thus thread safe, thus low performance (only one thread operates on the object at a time, others has to wait)
  4. StringBuilder (from 1.5)
    • same as StringBuffer (constructors and methods) except…
    • non-synchronized, thus no thread safety, thus Relatively high performance.
  5. Conclusion :
    • String : fixed content (wont change frequently)
    • StringBuffer : content not fixed and thread safety is required.
    • StringBuilder : content not fixed and thread safety is NOT required.

  1. == reference comparison (address comparison)
  2.  .equals() is used for content comparison (in general). Can be overridden to comp. ref. if needed
  3. All Wrapper Classes + String Classes, .equals() is overridden for content comparison

Modifiers in java : https://www.youtube.com/watch?v=1MmietzIteA&list=PLYPjPMiw3_YsVockWfuuhoP86YPDUXp4f&index=4

Anything can be declared inside anything!!

  • Access Specifiers (public, private, protected and <default>) vs Access Modifiers
  • Old language constructs… In java there is no terminology. All (12) are considered and modifiers

Interface vs Abstract vs Concrete class

  1. Interface (100% abstraction): No idea of implementation, just requirement spoecification, eg. Servlet
    • All methods must be public abstract
  2. Abstract : Partial implementation
    • concrete classes can be written
  3. Concrete Class : Ready to use service

Capture


Class MySystem{
static string out = “nitin”;
}
MySystem.out.length(); //Compare it to
System.out.println(out);

  • System is a Class
  • out is a static variable of type PrintStream in System class
  • println() is a method present in PrintStream.

  • Main method name can be set to a desired name by configuring JVM [JVM Customization]

JVM {
public static void nitin(String[] a)
}

  • public : to be called by JVM from anywhere
  • static : even without existing Object, JVM can call the main method. Also main method is not related to any object.
  • void : no return to JVM.
  • main : configured JVM
  • String[] args : command line argument.
  • overloading is possible (PSVM (int b)), but JVM will only call string args method (method hiding)
  • Inheritance is also applicable. the JVM first search main in child class or else it will execute the main method from the parent class.
  • If both Parent and child methods are same and “static”, this is method hiding… not overriding (only child class method is executed). Appears that overriding is applicable, but because of the static nature, its method hiding.
    • Inheritance and overloading is applicable
    • overriding is not, instead method hiding.
  • Java 1.7 enhancements
    • earlier “NoSuchMethodError : main”, now a more meaningful error
    • main method is mendatory, even though class has static block. Before, static block will be executed (and if System.exit(0), the program will terminate as well), and then NoSuchMethodError will be flashed.
    • if both static block followed by main method is present, then everything works as normal in both cases
    • Thus without even writing main, until Java 1.6, something can be printed on the console. from 1.7 onwards, main in compulsory.

  • Overloading
    • methods same name but different argument.
    • Compile time polymorphism, static polymorphism, early binding.
    • Method resolution is done by compiler based on reference type
  • Overriding :
    • When child class redefinition different than parent class (eg: marriage() method in example)
    • Runtime polymorphism, dynamic polymorphism, late binding
    • Method resolution is done by JVM based on runtime onject
    • co-varient return types are allowed (return can be same as Parent’s method, after Java 1.5)

*** In overloading check only method name (same) and argument type (different, at least order). Return types, access modifiers are not required.

**** In overriding: EVERYTHING should be same.

  • Parent p = new Child();
    • can invoke only parents methods
    • can use parent reference to hold any child class object.
    • polymorphism call
  • Child c = new Child();
    • can invoke both parent and child methods
    • can hold only child type of object
    • non polymorphic call

  • Control Flow in try catch block
    • (after jumping from try, rest of statements of try wont be executed. Thus keep the length of try block be be as small as possible)
    • there may be chances of exception in catch or finally block as well, and it will then be an abnormal termination.
    • if no exception, try and finally will execute
    • if abnornal termination due to exception in try or catch block, then also finally will execute.
  • Throwable (Class) has two child classes
    • Exception
      • Programming faults
      • Recoverable (file not found, catch {use local file and continue..})
    • Error
      • lack of system resources (out of memory etc)
      • system admin or server admin is responsible to increase heap memory
      • Non recoverable
  • Checked Exception :
    • Checked by compiler for smooth execution of the program at runtime (Menmonics : HallTicketMissingException, PenNotWorkingException, FileNotFoundException)
    • if programmer doesn’t handle checked exceptions, compile time error.
    • Mush be caught (try catch) or thrown (throws clause in the method definition)
    • Throwable -> Exception ->)Runtime exception and its child classes, (Throwable->)Error and its child classes are unchecked exceptions. Rest all are checked.
    • Further classified as fully checked or partially checked
  • Unchecked Exception
    • not checked by Compiler (bonmBlast exception, arithmatic, nullpointer)
    • Compiler won’t check if the programmer handled the exception.

*** Both occur at runtime.

  • FullyChecked exception
    • iff all the child classes are checked
  • PrtiallyChecked exception
    • if some of child classes are Unchecked
    • Only possible partially checked in Java
      1. Exception
      2. Throwable

Java Multithreading

  • Multitasking
    1. Process based multitasking (typing program while listening to music from the same system) Eack task is separate independent process(OS level)
    2. Thread based multitasking Separate independent task of same program (Programmer based)
  • Java Threading
    • strong API Support
    • 2 ways of defining
      1. By extending Thread class
        • override run() method;
        • everything within run() is called a job.
        • after instantiating t.start(), job from run() begins
        • both main thread and child thread runs simultaneously
        • no fixed flow of execution between main and child
        • Thread scheduler is part of JVM
      2. By implementing Runnable Interface (in java.lang and only method is run()) (Best approach)
        • class A implements Runnable{ public void run(){ … }
        • after instantiating, Thread t = new Thread(target Runnable object) and t.start();
  • Thread Life cycle

New Doc 1_1

Essential WordPress Plugins

For Free portfolio pictures : https://unsplash.com
Online Photo Editing  : http://www.picmonkey.com
Online Logo Editing : http://logomakr.com
The Logo/icons site : http://thenounproject.com/

Theme : Vantage

Plugins :

  1. Page Builder, for visual addition of html elements.
  2. LightBox Plus ColorBox : Lightbox Plus Colorbox permits users to view larger versions of images without having to leave the current page.
  3.  Black Studio Tiny MCE : For feature rich text editor
  4. Contact Form 7 :

Widget:

  1. Social Media Widget

Themify Builder : Stumbled upon themify builder as a part of Theme customization for wordpress 2013 theme. The tool is great to define a layout by drag and drop feature. Also Theme customization  and why child theme is created was understood with theses videos.

https://www.youtube.com/watch?v=giawHh0RztI

Themify Builder

https://www.youtube.com/watch?v=_AsoMMYqf_g

Programming Nirvana (Journey From Novice to Expert)

  • Inspired by 5 stages of Dreyfus Model of Skill Acquisition.
  • Novices, Advanced Beginner, Competent, Proficient, Expert
  • Step 1 : Learning to write codes less than 10 lines, but inclusive good logic. Gave me a good practice to set my hands on Java without using Google or any IDE. Writing logic of a method without bothering about the execution of a fully functional program. Also Test cases teaches the faults in the logic. The site takes away the burden of setting/installing Java or any other IDE’s. In short :

It teaches Thinking in Java

Taking Baby Steps CodingBat.

  • Step 2 : Learning to write fully functional programs (with 3 to 4 classes), with object creation, keeping in mind when to use static etc. JAVA 101 type assignments, which gives a clue of how the language is used to solve problems. A brief overview on OOP.
    • Assignment 1 :(Based on) Class String, Keyboard input, Console output
    • Assignment 2 : Defining Classes and methods, Encapsulation, boolean if & switch
    • Assignment 3 : Loops and Math. Random(), Objects and References (equals, toString())
    • Assignment 4 : Constructors, Static variables & methods, Overloading
    • Assignment 5 : Aggregation, exceptions
    • Assignment 6 : File Handling and Arrays
  • Step 3 : Learning Object Oriented Concepts (Later)
  • Step 4: Practice of elementary concepts of Collections from BJP

Strings, Arrays uses for loop as cursor

Arralylist, LinkedList, Vector and Stack uses ListIterator (most powerful Cursor)

All Collections use Iterator as Cursor

 

D&C/Greedy/Dynamic

The Divide and Conquer Approach

  1. Divide the problem into Subproblems that are smaller instances of the same problem.
  2. Conquer the subproblem by solving them recursively. Use “base case” for the simplest subproblem. (Recursion is bottom up)
  3. Combine the solutions to the subproblems into the solution for the original problem.

Divide and Conquer usually generates brand-new problem at each step of recursion.

Elements of Dynamic Programming

For any optimization Problem, to be considered for the Dynamic Programming Problem, TWO key elements are needed.

  1. Optimal substructure : Problem exhibits optimal substructure, and optimal solution is built from optimal solutions to subproblem.
  2. Overlapping subproblems : space of subproblems must be small. The total number of distinct subproblems is polynomial in the input size.

Dynamic programming algorithm typically take advantage of overlapping subproblem by solving each subproblem once and then storing the solution in a table where it can be looked up when needed.

A bottom-up dynamic-programming algorithm usually outperforms the corresponding top-down memoized algorithm by a constant factor, because the bottom-up algorithm has no overhead for recursion and less overhead for maintaining the table.

Elements of Greedy Strategy

A greedy algorithm makes choice that seems best at the moment.

This heuristic strategy does not always produce an optimal solution but sometimes it does.

  1. Determine the optimal substructure of the problem.
  2. Develop a recursive solution.
  3. Show that if we make the greedy choice, then only one subproblem remains.
  4. Prove that it is always safe to make the greedy choice. (Steps 3 and 4 can occur in either order.)
  5. Develop a recursive algorithm that implements the greedy strategy.
  6. Convert the recursive algorithm to an iterative algorithm.

Git (for Projects)

Place .gitignore file in the project’s root directory. (It can be version-ed). The .git/info/exclude can be configured to ignore personal project settings. The .git folder carries settings adjusted for the local user.

git config credential.helper store
git push -u origin master
Username:
Password:

Git will then not ask for username and password again and again.

The GIT Primer

Pulling a fresh Project from a repository first time

git fetch (to sync the project between different machines)

 

Create a file -> Add the file to staging area by commit –> modify the file and  add the file to staging area commit and –> Push

git clone https://nitinc@bitbucket.org/nitinc/eclipseinitialtest.git (for HTTPS…easier and more intuitive!!)

git log (shows all committed logs…AFTER CLONING)
git branch (showed only master…not r2….SEE)

DO GLOBAL GIT SETTINGS (for commits to recognize you)
git config –global user.name “Nitin Chaurasia VM”
git config –global user.email nitinc@bgsu.edu
git config –global color.ui tru

Networking

  • Switch –> Firewall –> Router –> Modem ———->INTERNET!!
  • Switch has Wireless Access Points (WAP) to allow wireless devices to be connected to it, and various computers are connected physically through wires to the switch.
  • Physical v/s Logical connection -> within a switch we can have logical connection.
  • Speed –> 12Mbps = 1.5 MBps (vendors talk in terms of bits to make it look bigger, divide by 8 and check)

The Modem

converts the signals into

Skip to toolbar