Tuesday, September 27, 2016

Java - How to Write to a File.

public class FileTrace implements Trace {
          
      private java.io.PrintWriter pw;
      private boolean debug;
      public FileTrace() throws java.io.IOException {
            // a real FileTrace would need to obtain the filename
            // somewhere for the example I'll hardcode it
            pw = new java.io.PrintWriter
                ( new java.io.FileWriter( "c:\trace.log" ) );
      }
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  pw.println( "DEBUG: " + message );
                  pw.flush();
            }
      }
      public void error( String message ) {
            // always print out errors
            pw.println( "ERROR: " + message );
            pw.flush();
      }
}

public class SystemTrace implements Trace {
      private boolean debug;
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  System.out.println( "DEBUG: " + message );
            }
      }
      public void error( String message ) {
            // always print out errors
            System.out.println( "ERROR: " + message );
      }
}

// To use the class
SystemTrace log = new SystemTrace();
log.debug( "entering log" );
Factory Method

// To use factory method
public class TraceFactory {
      public static Trace getTrace() {
            return new SystemTrace();
      }
}
Trace log = new TraceFactory.getTrace();

// A better factory method
public class TraceFactory {
      public static Trace getTrace() {
            try {
                  return new FileTrace();
            } catch ( java.io.IOException ex ) {
                  Trace t = new SystemTrace();
                  t.error( "could not instantiate FileTrace: " 
                          + ex.getMessage() );
                  return t;
            }
      }
}

Object Creation Initialization.

Initialization happens when,
  1. A class is loaded.
  2. A class is created/instantiated.
JVM does the following when it encounters class instantiation,
  1. Allocates memory space for a new object, with room for the instance variables.
  2. Process the constructor. If the constructor has parameters, JVM creates variables for the parameters and assigns them values passed in.
  3. If the invoked constructor begins with a call to another constructor by using "this" keyword, JVM processes the called constructor.
  4. Initialize instance and instance variable for this class. Undefined instance variables will be assigned default values.
  5. Executes the rest of the invoked constructor.
  6. Returns a reference variable that refers to the newly created object
Note:
  • Static initialization is performed first before any instantiation takes place, even if the code comes later in the program.

EXAMPLE
package mypackage;

public class MyClass {
    int x = 3;
    int y;

    // instance initialization code block
    {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass inst0 = new MyClass();
        MyClass inst1 = new MyClass();
    }
}


The instance initialization code can go unnoticed when the code gets bigger. A better practice to write initialization code is to put it in the constructor so it's more noticeable.
package mypackage;

public class MyClass2 {
    int x = 3;
    int y;

    // instance initialization code in the constructor
    public MyClass2 () {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass2 inst0 = new MyClass2();
        MyClass2 inst1 = new MyClass2();
    }
}


If you have more than one constructor and each calls the same block of code, wrap the common initialization code in a method and let the constructors call it.
package mypackage;

public class MyClass3 {
    int x = 3;
    int y;

    // Two constructors
    public MyClass3 () {
        init();
    }
    public MyClass3 (int x) {
        this.x = x;
        init();
    }

    // instance initialization code in a method
    private void init () {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass3 inst0 = new MyClass3();
        MyClass3 inst1 = new MyClass3();
    }
}


In C++, you must destroy objects after use. Java comes with a garbage collector which destroys unused objects and frees memory space.


Array Initialization.

Java:
// anArray = new int[10];
int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth

System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);


Python:
myList=[]
for i in range(10):
    myList[i]=1

for i in range(10):
    myList.append(1)

myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]

list_of4 = [3, "test", True, 7.4]

s = ["Lee", "Walsh", "Roberson"]
s2 = ["Williams", "Redick", "Ewing", "Dockery"]
s3 = [s, s2] # 2x2 list
s4 = s + s2; # concatenation two lists

list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
all_lists = sum([list1, list2, list3], [])
# all_lists == [1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

listanimal.append("cat")
listanimal.extend(["dog", "mouse"])

# This is tuple
b = ("Bob", 19, "CS")       # tuple packing
(name, age, studies) = b    # tuple unpacking

# data structure with lists and tuples
students = [
    ("John", ["CompSci", "Physics"]),
    ("Vusi", ["Maths", "CompSci", "Stats"]),
    ("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
    ("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
    ("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]

julia_more_info = ( ("Julia", "Roberts"), (8, "October", 1967),
                     "Actress", ("Atlanta", "Georgia"),
                     [ ("Duplicity", 2009),
                       ("Notting Hill", 1999),
                       ("Pretty Woman", 1990),
                       ("Erin Brockovich", 2000),
                       ("Eat Pray Love", 2010),
                       ("Mona Lisa Smile", 2003),
                       ("Oceans Twelve", 2004) ])



Perl:
my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @zeroes = (0) x 5; 
my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.
# To get the "length" or "size" of an array, simply use it in a scalar context. 
$count = @array;
# Get the highest index
$highest_index = $#array;


Ruby:
names = Array.new(20)
puts names.size  # This returns 20
puts names.length 

names = Array.new(4, "mac")
puts "#{names}"  # This returns "["mac", "mac", "mac", "mac"]"

nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}"   # This returns "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"

nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]

digits = Array(0..9)
num = digits.at(6)


JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];

// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};


C++:
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };

int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 
 
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
    for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++) {
            jimmy[n][m]=(n+1)*(m+1);
        }
}


SystemVerilog:

  • Fixed-size (multi-dimension)
  • dynamic (single dimension)
  • queue (single dimension)
  • associative (single dimension)

typedef enum {IDLE, TEST, START} state;
enum bit[2:0] {S0 = 'b001, S1 = 'b010, S2 = 'b100} st;
state cst, nst = IDLE;
$display ("st = %3b, nst = %s", st, nst.name;
// showing on screen: st = 0, nst = IDLE

typedef reg [7:0] octet;
octet b;
// same as reg [7:0] b;
typedef octet [3:0]
quadOctet;
quadOctet qBytes [1:10];
// same as 
// reg [3:0][7:0] qBytes [1:10];
typedef enum { circle, ellipse, freeform } ClosedCurve;
ClosedCurve c;
// same as
// enum { circle, ellipse, freeform } c;
struct {
  int x, y;
} p;
p.x = 1;
p = {1,2};
typedef struct packed {
  int x, y;
} Point;
Point p;

integer numbers[5]; // array of 5 integers, indexed 0-4
int b[2] = '{3,7};
int c[2][3] = '{{3,7,1},{5,1,9}};
byte d[7][2] = '{default:-1};
bit[31:0] a[3][2] = c;
for (int i=0; i<$dimensions(a);i++) begin
   $display ($size(a, i+1));
end

// queues
int j = 1;
int q[$] = {0,1,3,6}; // note, no' as in arrays
int b[$] = {4,5};   // no '
q.insert (2, j);    // {0,1,2,3,6}
q.insert (4, b);    // {0,1,2,3,4,5,6}
q.delete (1);       // {0,2,3,4,5,6}
q.push_front (7);   // {7,0,2,3,4,5,6}
j = q.pop_back();   // {7,0,2,3,4,5}   j = 6
q.push_back(8);     // {7,0,2,3,4,5,8}
$display($size(q)); // 7
q.delete();         // delete all elements
$display($size(q)); // 0

// Associative Arrays
integer aa[*];
integer aa_too[int];
// use aa.delete(), aa.first(), aa.next(), aa.prev(), aa.last()
// to traverse
byte ba[string], t[*], a[*];
int index;
ba["byte0"] = -8;
for (int i=0; i < 10; i++) 
   t[1<<i] = i;
a=t;
$display ("size of t array is: %0d", t.num()); // array size

// Array Methods
// num(), delete(), exists(), first(), last(), next(), prev()

byte ba[string], t[*], a[*];
int index;
ba["byte0"] = -8;
for (int i=0; i mmm 10; i++) begin
   t[1<<i] = i;
end
// t[1]=0, t[2]=1; t[4]=2, t[8]=3,...
a=t;
$display ("size of t array is: %0d", t.num()); // array size

// Array Loop : foreach (array[i]) 
// Array Methods:
// function array[$] array.find() with (item < 3) // returns {value}
// function int[$] array.find_index() with (item < 3) // returns {index}
// function array[$] array.find_first() [with (exp)]
// function int[$] array.find_first_index() [with (exp)]



Monday, September 26, 2016

Java Packages.


Import and Static import

There are some Java classes that contain static final fields. One of them is the java.util.Calendar class, that has the static final fields representing days of the week. To use a static final field in the Calendar class, you must first import the Calendar class.
import java.util.Calendar;
if (today == Calendar.SATURDAY) {
}

// You can also import static fields using the import static keywords.
import static java.util.Calendar.SATRDAY;

java.lang.Object

   Methods:
  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • wait, notify, notifyAll

java.lang.String
  • Java string is immutable object
  • String()
  • String (arrayName)
  • String (arrayName, intOffset, intLength)
  • String Array Methods:
    • length()
    • indexOf (StringName)
    • indexOf (StringName, startIndex)
    • lastIndexOf (StringName)
    • lastIndexOf (StringName, startIndex)
    • trim() // remove all whitespaces before and after the String, but not within between
    • substring (startIndex)
    • substring (startIndex, endIndex)
    • replace (oldChar, newChar)
    • split (delimiter)
    • charAt (index)
  • String Compare Methods
    • equals (String)
    • eqaulsIgnoreCase (String)
    • startsWith (String)
    • startsWith (String, startIndex)
    • endsWith (String)
    • isEmpty()
    • compareTo (String)
      • if returns '0': true equal
      • if returns positive: longer or greater
      • if returns negative: shorter or less
    • compreToIgnoreCase (String) 
      • ref to above
  • Two mutable String API:
    • StringBuilder
      • faster but not thread-safe
    • StringBuffer
      • dated, too slow, StringBuilder is faster
      • thread-safe
String message = new String ("Java is cool!");
String s1 = "Java";
String s2 = "Java";
if (s1 == s2) { // returns true
}

String s1 = new String ("Java");
String s2 = new String ("Java");
if (s1 == s2) { // returns false
}

// if s1 == null without checking, it will generate a runtime error
// also the order matters so is the use of "&&" logical operator
// using "&&" will prevent JVM to evaluate the s1.equals()
// second expression and generate an error

if (s1 != null && s1.equals("Java")) // returns true
{
}
// Another coding style, no need to check if "Java" is null
if ("Java".equals (s1)) {
}

// Create a string from an array of characters
char cityArray[] = {'D','a','l','l','a','s'}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);

// Create a string from an array of bytes
byte cityArray[] = {68, 97, 108, 108, 97, 115}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);


Java Exception

   Keyword:
  • try
  • catch
  • throw
  • throws
  • finally
import java.io.*;
import java.util.List;
import java.util.ArrayList;

void method1 () {
    try {
        method1();
    }
    catch (Exception e) {
    }
}
void method2 () throws Exception {
    method3();
}
void method3 () throws Exception {
    method4();
}
public static int getInput (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {
    throw new Exception();
}
class MyOutOfRangeException extends Exception {
    MyOutOfRangeException(String message){ 
        super(message); // call the base class constructor
    } 
}
public static int getInput2 (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {

    int userChoice = 0;

    if (in == null) {
        throw new NullPointerException("Null Scanner");
    }
    System.out.println(
        "Please enter a value between 1 to 5");
    userChoice = Integer.parseInt(in.next());
    if (userChoice < 1 || userChoice > 5) {
        throw new MyOutOfRangeException
            ("Please enter value between 1 to 5");
    }
    return userChoice;
}

// Code to prevent NullPointerException
if (customerType != null)
{
    if (customerType.equals("R"))
        discountPercent = .4;
}


java.lang.Scanner

  • getInt() 
  • getDouble() 
  • getDoubleWithRange() 
  • hasNext() 
  • hasNextInt() 
  • hasNextDouble() 
  • next() 
  • nextLine()

if (sc.hasNextDouble()) {
    subtotal = sc.nextDouble();
}
else {
    sc.nextLine();    // discard the entire line
    System.out.println(
        "Error! Invalid number. Try again.\n");
    continue;         // jump to the top of the loop
}

// Code to get a valid double value within range
Scanner sc = new Scanner(System.in);
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false) {
        // get a valid double value
        System.out.print("Enter subtotal: ");
        if (sc.hasNextDouble()) {
            subtotal = sc.nextDouble();
            isValid = true;
        }
        else
        {
            System.out.println(
                "Error! Invalid number. Try again.");
        }
        sc.nextLine();
                // discard any other data entered on the line

        // check the range of the double value
        if (isValid == true && subtotal <= 0) {
            System.out.println(
                "Error! Number must be greater than 0.");
            isValid = false;
        }
        else if (isValid == true && subtotal >= 10000)
        {
            System.out.println(
                "Error! Number must be less than 10000.");
            isValid = false;
        } 
}



Good Practices!

  • Organize your constants, put all constants in a class.
    This class most often does not have methods or other fields and is never instantiated.
package AllConstants;
public class Months {
public static final int JANUARY = 1;
public static final int FEBRUARY = 2;
public static final int MARCH = 3;
public static final int APRIL = 4;
public static final int MAY = 5;
public static final int JUNE = 6;
public static final int JULY = 7;
public static final int AUGUST = 8;
public static final int SEPTEMBER = 9;
public static final int OCTOBER = 10;
public static final int NOVEMBER = 11;
public static final int DECEMBER = 12;
}

// Get the representation of January by
int thisMonth = Months.JANUARY;


More About "javac" et cetera ...


javac - Java compiler
javac [ options ] [ sourcefile.java ] [ @filelist ]
  • For large number of source files, list all file names in @filelist
  • In <filelist>, separate files with space or line breaks.
  • Inner class definitions produce additional class files.
  • [ options ]
-classpath pathname Set the user class path
-d directory Set the destination directory for class files
-g Generate all debugging information, including local variables.
-g:none Does not generate any debugging information.
-g:source Generate source file debugging information
-help Prints a synopsis of standard options
-nowarn Disables warning messages. (Same as -Xlint:none)
-sourcepath path Specify the source code path to search for class or interface definitions
-verbose Verbose output.
-X Display information about non-standard options and exit.

EXAMPLE
// Create a file named "options" containing:
//
//    -d classes
//    -g
//    -sourcepath /java/pubs/src/share/classes
//
// Create a file named "classes" containing:
//
//    MyClass1.java
//    MyClass2.java
//    MyClass3.java
//
// Run javac as follows:
//    javac @options @classes
//    javac @path1/options @path2/classes
//
% ls path1
   options
% cat path1/options
   -d classes
   -g
   -sourcepath /java/pubs/src/share/classes
% ls path2
   classes
% cat path2/classes
   MyClass1.java MyClass2.java MyClass3.java
% javac @path1/options @path2/classes
% java -classpath classes MyClass1
...

JVM

  1. Invoking the class's main method.
  2. There are 3 things that JVM do:
    • Loading
    • Linking
      • Verification - Checks the binary code with Java's semantic requirements.
      • Preparation - Prepares the class for execution by allocating memory space for data and static variables.
      • Resolution (optional) - Checks if the class references other classes/interfaces and find/load them. Checks are done recursively.
    • Initialization
      • Initializes static variables and execute static initializers in static blocks. This is done before the main method is executed. Before the class can be initialized, its parent class has to be loaded, linked and initialized first so this process happens recursively to the top most class.

JDK
  • javac - Java compiler
  • jar - Java Archive
  • javap - Java Disassembler
  • jdb - Java Debugger

Sunday, September 25, 2016

Java Classes.


Terms
  • Local variable
  • Instance variable/members
  • Class variable/members
  • Fields (they are variables)
  • Methods (Functions in C++)
    • Method Overloading
    • Static Factory Methods
  • Constructor
  • Varargs (variable length of argument list)
  • Packages
  • Class Access Control Modifiers (public, private, default, protected)
Access Level Classes outside the package Classes in the same package Child Class Same Class
public yes yes yes yes
protected no yes yes yes
default no yes no yes
private no no no yes

Example
import java.io.FileReader;

class MyClassName {
    int localVar1;
    double localVar2;

    // public field name accessible by obj/reference
    public int instanceVar3; 
    // class field name available without obj creation
    // it is accessible by className.classVar
    static int classVar1;

    // Constructors
    public void MyClassName (int ageValue, double phoneNumber) {
    }
    // Method Overloading
    // 1. number of parameters 
    // 2. datatype 
    // 3. sequence of parameters
    public void MyClassName (char gender) {
    }

    void methodName1 (listOfArguments) {
        this.classVar1 = 0;
        this.localVar1 = 2;
        this.localVar2 = 3;
    }

    int methodName2 (int inputNumber, int a, int b) {
    }
    ClassName2 getData () {
        return new ClassName2(); // return a handle/reference
    }

    public static void main (String[] args) {
    }
}

// To create an object (an object reference to be precise)
// use: new MyClassName;
// without new to create and construct the object, 
// myInstanceName == null;
// public variable and method can be accessed by
// objectReference.methodName
// objectReference.fieldName
MyClassName myInstanceName = new MyClassName();
myInstanceName.instanceVar3 = 24;

if (book == null) {
    book = new Book(); // create the object/reference
}


Class member versus Instance member

Java supports the notion of static members, which are class members that can be called without first instantiating the class.
public static int a;
static public int b;
static final int NUMBER_OF_MONTHS = 12;
public static final float PI = (float) 22 / 7;

public static int add (int a, int b) {
    return a + b;
}

// You can't call non-static members from a static method
// Remember, if it is not declared to be static, it does not
// exist until you create/construct the object/instance

pub class StaticDemo {
    public int b = 9;
    public static void main (String[] args) {
        System.out.println (b); // will generate compile error!
    }
}

// To solve the above error, there are two solutions.
// 1. Make b static
// 2. Create an instance of the class and access b 
//    by the object reference

// You can only declare a static variable in a class level.
// You cannot declare local static variables even if the 
//    method is static.



Useful Packages
  • java.awt.Component
  • java.awt.Container
  • java.awt.Object
  • java.awt.Object
    • java.applet.Applet

  • java.io
  • java.io.File
  • java.nio.File
  • java.io.FileReader
  • java.io.PrintWriter
  • java.io.FileNotFoundException
  • java.io.PrintSteam
  • java.lang.annotation
  • java.lang.Boolean
  • java.lang.Integer
  • java.lang.Math
  • java.lang.Object (toString)
  • java.lang.reflect
  • java.lang.Runtime
  • java.lang.Scanner
  • java.lang.String
  • java.lang.StringBuffer
  • java.lang.StringBuilder
  • java.lang.System
  • java.math.BigDecimal
  • java.sql.Date
  • java.time.Clock
  • java.text.NumberFormat
  • java.util.ArrayList
  • java.util.Calendar
  • java.util.Date
  • java.util.LocalDate
  • java.util.Locale
  • java.util.Random
  • java.util.Scanner
  • java.util.*

EXAMPLE
// You cannot use new to instantiate an object when a class has a
// private constructor, such as java.util.LocalDate. Instead, use
// its static methods.

LocalData today = LocalDate.now ();

// such methods are called static factory methods.
// Often time this is because these private constructors define 
// constants and members that should stay intact by the class users.

// The static factory methods can invoke the private constructors 
// because they are in the same class. This way, the class creator 
// can restrict an object to contain only certain legitimate values 
// and make other values impossible.

import static java.lang.System.out;

...
out.print("id");
out.println ("whatever you want to print");




    Java Flow Control.

    Conditional Flow Control
    if (x > 4) y = x;
    if (y == 99 || y < 0) {
       z = x;
    } else if (y > 50) {
       z = y;
    } else {
       z = x + y;
    }
    
    //
    switch (count) {
        case 0:
        case 1:
            total = count * 0.5;
            break;
        case 2:
            total = count * 0.8;
            break;
        default:
            total = count * 1;
            break; // redundant, to prevent copy paste error when
                   // some like to put this in the beginning of switch
    }
    //
    // starting from Java 1.7, 
    // you can compare switch variable to String literals in case
    //
    

    Loop Control
    for (int i=0; i < 3; i++) { // Here ++i or i++ doesn't make a difference
        if (i%2 == 0) {
            System.out.println (i);
        }
    }
    int k = 0;
    for ( ; k < 3 ; ) { // It is okay.
        k++;
    }
    
    for ( ; ; ) {
        if (k > 4 ) break;
        k++;
    }
    start:
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 4; j++) {
            if (j == 2) {
                break start;
            } else { // redundant, to show continue usage
                continue start;
            }
        }
    }
    //
    int i = 0;
    // to produce three beeps with a 500 milliseconds interval 
    // between two beeps
    while (i < 5) { // without semicolon! 
                    // Compiler won't error out with it! Be cautious!
        java.awt.Toolkit.getDefaultToolkit().beep();
        try {
            Thread.currentThread().sleep(500);
        } catch (Exception e) {
        }
        i++;
        if (i > 2) break;
        else continue;
    }
    do {
        System.out.println (i);
        i++;
    } while (i < 3); // with semicolon
    

    JAVA Terms.


    General

    • abstraction
    • encapsulation
    • enum
    • inheritance
    • inner classes
    • polymorphism
    • precedence (answer)

    Operators
    - Unary Minus Operator
    + Unary Plus Operator
    ++ Increment Operator
    -- Decrement Operator
    ! Logical Complement Operator (Only takes boolean types as operands)
    ~ Bitwise Complement Operator
    + - * / % Arithmetic Operators (+ addition, - subtraction, * multiplication, / division, % modulus)
    == Equality Operator
    < >  <=  >= Relational Operator
    &&  || Conditional Operator
    ? : Ternary Operator
    (expression)? true_statements : false_statements ;
    <<  >>  Shift Operator (Only takes integer-convertible types as operands)
    >>> Unsigned Right Shift Operator
    (Only takes integer-convertible types as operands)
    = Assignment Operator (There are 12 of them and only integer-convertible types as operands)
    =  +=  -=  *=  /=  %=  <<=  >>=  >>>=  &=  ^=  |=
    &  |  ^ Integer Bitwise Operators


    Examples
    int j = 2;
    int k = ~j; // k = -3; j = 2;
    boolean z = x != y;
    //
    byte x = 5;
    byte z = -x; // error
    byte y = (byte) -x; // correct
    short x = 200;
    short y = 400;
    short z = x + y ; // error
    short z = (short) (x + y); // correct
    //
    // The casting is necessary or an integer will be assigned to pi
    final float pi = (float) 22 / 7; 
    //
    

    Saturday, September 24, 2016

    JAVA Questions.


    • What is a compiler?
    • How is Java different from traditional programming?
    • What is bytecode?
    • What is the difference between JRE and JDK?
    • If you had saved the code in a file named "whatever.java", would it have compiled without errors?
    • If you had used a file extension other than java when saving the code, would it have compiled?
    • In Java, how do you write to the console?
    • Write a Java class named HelloWorld that prints "Hello World!".


    • What does ASCII stand for?
    • Does Java use ASCII or Unicode?
    • What are reference type variables?
    • What are primitive type variables?
    • How are constants implemented in Java?
    • What is an expression?
    • How to assign the British pound symbol to a "char" if you know the Unicode for it is 00A3?
    • Name ten operators in Java.
    • What is the ternary operator in Java?
    • How to specify comments in Java?
    • What is operator precedence?
    • Consider the following code. What are the values of result 1 and result2? Why the difference?
    int result1 = 1 + 2 * 3;
    int result2 = (1 + 2) * 3;
    


    • Name at least three element types that a class can contain. 
    • What are the differences between a method and a constructor? 
    • Does a class in a class diagram display its constructors? 
    • What does null mean? 
    • What do you use the this keyword for? 
    • When you use the == operator to compare two object references, do you actually compare the contents of the objects? Why? 
    • What is variable scope? 
    • What does “out of scope” mean? 
    • How does the garbage collector decide which objects to destroy? 
    • What is method overloading? 
    • Create a class whose fully-qualified name is com.example.Tablet to model an Android tablet. The class must have three private fields, weight (int), screenSize (float), and wifiOnly (boolean). Access to the fields must be through pairs of public get and set methods. That is getWeight/setWeight, getScreenSize/setScreenSize and getWifiOnly/setWifiOnly. The class must also have one constructor, a no-argument constructor.
    • Create a TabletTest class in the package com.example.test and instantiate the Tablet class. Print the value of the fields (by calling its get methods) right after instantiation. Then, set the field values and print them again

    Bytecodes are
          1. output from the JVM
          2. ready to be executed by a Windows sytem
          3. input to the Java compiler 
          4. input to the Java interpreter (JVM) 
    
    Which of the following is a valid statement for declaring and 
    initializing a double variable named length to a starting value of 120?
          1. Double length = 120.0; 
          2. length = 120.0; 
          3. double length = 120.0; 
    
    Which of the following can you assign to a String variable?
          1. a string literal (constant) 
          2. null 
          3. an empty string 
          4. all of the above 
    
    Relational equality operator is allowed to
          1. compare numeric variables 
          2. compare string references 
          3. both a and b 
          4. neither a nor b 
    
    What happens when you use both integer and double values in an 
    arithmetic expression?
          1. an exception occurs 
          2. all values are cast to the type of the result variable 
          3. the integer values are cast to double values 
          4. the double values are cast to integer values 
    
    What does the following statement do if userNumber has an integer 
    value of 14 and userEntry has a string value of “two”?
    
      userNumber = Integer.parseInt(userEntry);
    
          1. Stores a null value in userNumber 
          2. Converts “two” to 2 and stores it in userNumber 
          3. Throws an exception 
          4. Converts “two” to “2” and stores it in userEntry 
    
    Explicit casts must be used to perform
          1. narrowing conversions 
          2. widening conversions 
          3. none of the above 
          4. any conversion between two data types 
    
    Consider the following condition. It will be true when
    (!endProgram.equalsIgnoreCase("n"))
    
          1. the value of endProgram doesn’t equal “n” 
          2. the value of end Program equals “n” or “N” 
          3. the value of endProgram equals “n” 
          4. the value of endProgram doesn’t equal “n” or “N” 
    
    Consider the code that follows. What does it do?
    
       String value = "2";
       boolean tryAgain = true;
       while (tryAgain == true) {
    
         try {
            int num = Integer.parseInt(value);
            tryAgain = false;
         }
         System.out.println("Valid integer");
         catch(NumberFormatException nfe) {
            System.out.println("Invalid integer");
            System.out.print("Enter an integer");
         }
       }
    
          1. The code compiles but causes a runtime error. 
          2. It prints “Invalid integer” to the console. 
          3. The code doesn’t compile. 
          4. It prints “Valid integer” to the console. 
    
    If the variable named input is 755, what is the value of r 
    after these statements are executed?
     
       NumberFormat n = NumberFormat.getNumberInstance();
       n.setMinimumFractionDigits(3);
       String r = n.format(input);
          1. 755 
          2. .755 
          3. 760.000 
          4. 755.000 
    
    


    Monday, September 19, 2016

    FIFO


    Asynchronous FIFO:

    reg clk1; // write clock
    reg clk2; // read clock
    reg full_flag;
    reg empty_flag;

    // Set the Direction Signal to High when Write_address (Write_pointer ) is less than 
    // Read_address( or Read_pointer ) &&
    // i.e. (Write_pointer > Read_pointer ) then Direction = 1;


    // Reset the Direction Signal to Low when Write_address( or Write_pointer ) is greater than 
    // Read_address( or Read_pointer )
    // i.e. ( Write_pointer < Read_pointer ) then Direction = 0;


    // Case 1: ( Full Flag )
    // Assert status Full flag When Direction Signal == 1 && ( Write_pointer == Read_pointer )
    if ( Direction == 1 && ( Write_pointer == Read_pointer ) )  full_flag = 1;
    else full_flag = 0;


    // Case 2: ( Empty Flag )
    // Assert status Empty flag When Direction Signal == 0 && ( Write_pointer == Read_pointer )
    if ( Direction == 0 && ( Write_pointer == Read_pointer ) ) empty_flag = 1;
    else empty_flag = 0;


    // When Comparing Write_pointer && Read_pointer to assert Empty or Full
    // one pointer has to be synchronized to the other's clock domain
    // watch for the 2 clock delay and align with the direction to avoid 
    // overflow and underflow in FIFO

    // In general, write pointer should be delayed and behind the read pointer to
    // avoid overwriting unread data.
    // that is,  compare: if (Write_pointer == two_clk_delay_Read_pointer )

    // Use buffer management techniques if desired.


    ASIC Examples.


    • Full adder can be implemented by two half adder; a half adder can be implemented by a XOR and AND gate. XOR and AND gate can be implemented by 2:1 MUX.

      Full adder can be implemented using 8 muxes.
    • Design a combinational circuit which counts the number of 1s in a 7-bit input.
    • Design a divide by 3 counter (frequency by 3 divider). Bonus for 50% duty cycle output. (Answer)
    • How to fix setup time violation and hold time violation.
    • Complete the c function that uses recursion to determine if the string is a palindrome.
    • How to minimize the power dissipation of an ASIC chip.
    • Use full adder to detect how many logic 1's there are in a 8-bit input data.
    • Design state machine to test 10110101, how many flip-flops will be used?
    • Design a circuit that would count 1 every time when another counter counts from 0 to 255. One of the counter is working at higher frequency than the other.
    • Write Verilog for a 3 to 1 arbiter, with a priority client and 2 other clients in a round robin manner.
    • What is Moore FSM and Mealy FSM?
    • Write a Verilog to convert JK Flip-flop to D Flip-Flop.
    • What is the basic pipeline stages in computer architecture.
    • Which gate would you prefer in a design NAND or NOR and why?
    • Write Verilog code to swap data with and without a temporary register.
    • How to design clock gating for an 8-bit counter
    • What are the different ways to design clock gating in order to reduce power consumption?
    • Design a block with one data input and one clock input. The output is '1' when '0110' is detected in input and '0' otherwise.
    • Basic steps of synthesis.
    • How to decide the FIFO size when input rate is N and output rate is M.
    • What would be the behavior of a CMOS inverter if the NMOS and PMOS are interchanged.
    • Verilog code to design asynchronous FIFO.
    • FIFO synchronized and asynchronized.
    • Setup up time and hold time calculation.
    • What is the process of designing a FPGA.
    • Design a UVM driver
    • How do you combine states in a state machine? Do you save anything?
    • How to print out elements on 1/8th of the circumference of a circle?
    • How to get the second largest number in an unsorted array?
    • Basic DFT flow.
    • Cross domain clock (or clock domain crossing) design example.
    • Write verilog code of D-Latch
    • Use two 2-bit comparators to implement a 4-bit comparator and reduce the delay to one unit. Compare '0100_0000_01' and use the simplest RTL design to get the length (which is 9)

    • Write a FSM to detect the sequence 101011
    • How to design AND and OR gates with 2x1 Mux?
    • How many data bits are needed to represent A*B+C, all 8-bit unsigned.
    • What is the relationship between read and write clocks for different data widths in a FIFO?
    • Explain setup time and hold time on a registered path with clock skew.
    • Pipeline stages in MIPS.
    • What is RAW, WAW and WAR hazards and how to solve them in linear and OoO pipelines?
    • Multi Clock domain FIFO design.
    • Cache stages











    Sunday, September 18, 2016

    C Programming Examples.



    • Swap function: difference between pass by value and pass by reference.
    • Fibonacci series. Two implementation: for loop and recursive.
      • loop:
        int fibo_loop (int n) {
            int j = 1;
            int k = 1;
            int sum;
            for (int i = 2; i < n; i++) {
                sum = j + k;
                j = k;
                k = sum;
            }
            return sum;
        }
      • recursive:
        int fibo_recur (int n) {
            if (n<=2) {
                return 1;
            } else {
                return fibo_recur (n-1) + fibo_recur (n-2);
            }
        }
    • The usage of constant, constant functions
    • Detect sequence pattern in FSM
    • What is the purpose of "volatile" flag in C programming language?