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?