Friday, February 27, 2015

Access Modifiers


Use the code below to practice the access modifiers effects on fields and methods.  Save this code  as ClassA.

Copy HelperA code three times and rename two of the copies to HelperB and HelperC. ( don't forget to adjust the name of the constructors )
Add package package1; to all three newly created classes.

Make two more classes HelperD and HelperE by copying this code again and adding package package2; to the beginning of the classes.

That way, you will have three classes in one package and two classes in another package, so you can "play" with access to fields and methods.

Try to compile the classes and see the effects.  As you are getting error messages, just comment out the statement that causes the error message.  Make a note of the error message, comment no access, and continue until you have no more compile errors. 

As you are making modification to classes, keep track of the errors and verify this table's values with fields and methods.  You can also extend this table with other test values if needed.


public class ClassA {
   
    private int value;
    public static int static_ident;
    public static final String  CONSTANT= "STATIC CONSTANT STRING";

    public ClassA(int value ){  value=value; static_ident=2015; }  //value is a shadow, avoid it

    public int getValue(){return value;}
   
    public static int getStatValue(){return static_ident;}   //can not use this for static
   
    public static void main(String args[]) {

        ClassA me=new ClassA(20);
        String myName=new String("Richland College");
       
        System.out.println("Hello My Non-Static Value!!!"+me.getValue());
        System.out.println("Hello My Static Method!!!"+me.getStatValue());
        System.out.println("Hello Constant Field!!!"+CONSTANT);   //can not refer to it as this.CONSTANT
       
        HelperA helper=new HelperA();
       
        //System.out.println("Hello Helper Private Method!!!"+helper.getPriName());  //no access
        System.out.println("Hello Helper Public Method!!!"+helper.getPubName());
        System.out.println("Hello Helper No Method!!!"+helper.getNoName());
        System.out.println("Hello Helper Protected Method!!!"+helper.getProName());
       
        //System.out.println("Hello Helper Private Field!!!"+helper.pri_name);  //no access
        System.out.println("Hello Helper Public Field!!!"+helper.pro_name);
        System.out.println("Hello Helper No Field!!!"+helper.no_name);
        System.out.println("Hello Helper Protected Field!!!"+helper.pub_name);
    }

}

class HelperA{
    private String pri_name;
    public String pub_name;
    String no_name;
    protected String pro_name;
   
    public HelperA(){
       pri_name="pri_Anonymous";
       pro_name="pro_Anonymous";
       no_name="no_Anonymous";
       pub_name="pub_Anonymous";
    }
   
    private String getPriName(){ return pri_name; }
   
    public String getPubName(){ return pub_name; }
   
    String getNoName(){  return no_name;  }
   
    protected String getProName(){ return pro_name; }
}

Thursday, February 26, 2015

Coder Body Types

Which one are you?

Programming can be frustrating in many cases, but those starting out on learning a language should not have a reason to be frustrated if the basics are established correctly.  Creating a project should not start with opening the IDE and starting to program.  the problem should be understood and well researched before a meaningful UML, pseudo code, and/or a flowchart can be created to guide the development process.  Only after spending enough time on the design and algorithm should the coding begin.  If the correct IDE and language is selected, the coding portion should take the least amount of time.  that requires for someone to know the syntax intricacies of the language, but a good design will take much of the frustration out of coding.  The last and most important stage is the testing phase that can reveal all the semantic errors since the compiler will not be helpful in identifying those type of logical errors.  A good programmer will spend enough time on testing the code and test all the scenarios the application will face until a high level of certainty is achieved of the application reliability.  

So, as a beginning programmer, you are most likely spend way too much time on your coding and implementation because you have not spent enough time on the design of your project.  Even if you spend enough time on researching and taking courses that help you understand the math behind the problems and you can design a great algorithm, you might not see the value of through testing of the application and might introduce many logical errors into the application since implementing a design can be tricky.

This simple example could cause many hours of troubleshooting and frustration: 

float fahrenheit=82;
float celsius = ( fahrenheit -32 ) * ( 5 / 9 );

This is simple code can be fixed by ( 5 / 9.0 ) to turn an integer division into a mixed division and have a real number as a result instead of an integer that would always be zero.  This kind of mistake can be caused by a good design and bad implementation, but proper testing methodology can reveal this mistake.  Testing should be done with at least 32 and 212 for an easy to see known value result of 0 and 100.  Other values like a positive value and a negative value could also be used to test the proper sign of the results.  

So, understand the syntax of the language and the intricacies of computer operations to reduce time spend on coding and increase the time spent on design and testing to ensure the proper solution. 

                   Advanced                                     Beginner                                           Intermediate


Tuesday, February 24, 2015

Hash Calculator

Look at this code and see if you guys like to make this code into a more complex project. Always talk about a way to test if your code works properly and testing methodology before implementing your code. Testing is as important as coding.

import java.util.Scanner;
import java.security.MessageDigest;
import javax.swing.JOptionPane;
import java.io.UnsupportedEncodingException;


/**
* Application to practice creating a message digest with specifying algorithm
* @author Zoltan
* @version 1.0.0
*
*/
public class Driver {

/**
* Entry point to the application
* @param args String array that is not used in this code
*/
public static void main(String[] args) {

//variable declarations
byte[] messageBytes;
String password;
MessageDigest mDigest;
byte[] theHash;

//Let user specify the clear text password by entering a string
password = JOptionPane.showInputDialog("Please enter your password");
JOptionPane.showMessageDialog(null, "Your password was: "+password);

//Convert the entered password string to a byte array in UTF-8 encoding
//The encoding should never throw an exception in this case, but it is required for this method.
try{
      messageBytes= password.getBytes("UTF-8");
      }
catch (UnsupportedEncodingException e) {
                   throw new AssertionError("UTF-8 is unknown");
      }

//Generate the message digest for the clear text of byte array
try{
      //Lookup the available algorithms and adjust the code to be dynamic of fix
      // http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest
       mDigest = MessageDigest.getInstance("MD5");
       theHash = mDigest.digest(messageBytes);

       //Convert the byte array to Hex values for display 
       StringBuffer sBuffer = new StringBuffer();
      
       for (int i = 0; i < theHash.length; i++) {
             sBuffer.append(Integer.toString((theHash[i] & 0xff) + 0x100, 16).substring(1));
            }

       // Verify the results on-line with a simple string
       // like "password" http://www.miraclesalad.com/webtools/md5.php

       JOptionPane.showMessageDialog(null, "Your password hash is: "+sBuffer);
}
catch (java.security.NoSuchAlgorithmException e) { }

     }// end of main method
}//end of Driver class

Sunday, February 22, 2015

Greenfoot game and Javadoc

This is the code for the game created for the class learning about the value of documentation.
Watch the video to understand and appreciate the learning process of this code.
https://www.youtube.com/watch?v=kOnvLnmbeno


public class myWorld extends World
{
public myWorld(){
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1,false);
getBackground().drawRect(300, 200, 100, 100);
getBackground().setColor(java.awt.Color.CYAN);
getBackground().fillRect(Greenfoot.getRandomNumber(550),Greenfoot.getRandomNumber(150),50,50);

prepare();
}

private void prepare(){
myDot mydot = new myDot();
addObject(mydot, 109, 96);
}
}

import greenfoot.*;

public class myDot extends Actor{
public void act() {
setLocation(getX()+5,getY()+5);
if(isAtEdge()){
gameOver lost=new gameOver();
getWorld().addObject(lost,getWorld().getWidth()/2,getWorld().getHeight()/2);
Greenfoot.stop();
}
if(Greenfoot.isKeyDown("up")){
setLocation(getX(),getY()-Greenfoot.getRandomNumber(25));
}
java.awt.Color isOnTop = getWorld().getBackground().getColorAt(getX(),getY());

if(isOnTop.equals(java.awt.Color.CYAN)){
//System.out.println("I'm over it!!!");
UgotIt won=new UgotIt();
getWorld().addObject(won,getWorld().getWidth()/2,getWorld().getHeight()/2);
Greenfoot.stop();
}
}
}

public class gameOver extends Actor{
public void act() {
// Add your action code here.
}
}

public class UgotIt extends Actor{
public void act() {
// Add your action code here.
}
}

Saturday, January 24, 2015

Documentation and Comments

Many people starting out in programming thinks that documentation and commenting is a waste of time and it does make them better programmers.  It might be that documentation does not make a better program, but the quality of code can also be measured by its comments.  Just like science is not a science without documented measurements, code is not part of computer science if it is not documented.  

As more programming languages support docstrings, that feature of the language actually makes better programmers right from the start.  Java is one of those languages that is easy to learn, but its ability to support docstrings is not focused on in the early stage of learning.  

Java is also a great language to help those new to programming learn documentation of existing libraries of classes.  The main difference between a novice and an expert is that an expert know how to get help when needed in a fast and efficient way.  Thus, education could focus on not just the syntax, but focusing on how to find answers when questions arise.  That would help novice graduates overcome confusions faster and focus on real problem solving issues instead.  

Computer Science is also evolved to many languages and can not rely on a single language that is considered the latest "fad".  It is the combination of languages in order to solve problems by picking the right "tool".

Thus, you need to learn about many languages and collect your notes in a way that you can use regardless of the language you will use, but helps you with the required syntax.

This flowchart can be one of the ways you can map simple concepts and document each language.


  

Eclipse Shortcuts

Eclipse IDE is an amazing environment to help you learn many languages in one simple to install and use environment.  You can use it to learn Java, C++, and Python without learning IDE for each of those languages.  That way, you can focus on the actual language instead of wasting time learning another IDE.

Eclipse has man shortcuts that can help you make your programming experience much more fun by providing shortcuts for repeated tasks.

Auto-generate constructor
Auto generate setters and getters
Project->Generate javadoc
sysout + Ctrl + Space


Ctrl + i - indent selection
Ctrl+Shift+o - import required libraries
Ctrl+D - delete line
Alt+Shift+R - rename all occurrence of an identifier
Ctrl+F11 - run the code


Others

Alt+up or down  - Move a line of code up or down
main + Ctrl + Space  - Create main method signature
Ctrl+D  - Show hierarchy of a class
Ctrl+/ - comment the source code line
Ctrl+L - jump to line number
Ctrl+q  - last edit location
Ctrl+ o - outline of class

Short video summarizing most of the features mentioned in this post.
https://www.youtube.com/watch?v=7ESqUgkzke4

Wednesday, January 14, 2015

ReadyNAS 104 and iSCSI

There are many talks about cloud storage and storing files remotely as a way to protect data from loss.  While it is a great way to use free services for this purpose, you might also need to think about learning about this technology as a learning environment.  It does not matter if you are an information technology, information assurance, digital forensics, cybersecurity, or computer science student, you will need an infrastructure where you can experiment and learn on your own.  Hardware prices and open source operating systems make the setup of this environment easy and cheap.

If you are in computer science and try to learn about programming, you might find it easier to learn about network based programming by setting up a web server and experimenting with HTML and JavaScript as a start.

It seems like every application that is written these days are based on web services or use web services as its interface.  Thus, it is in your interest to learn about network based programs and program execution.  You will also need to think about safeguarding the code you write and ensuring its availability as you are progressing with your studies. So, you might need to learn about server management and file sharing.

One of the lesser known file sharing technologies is iSCSI ( Internet Small Computer System Interface, an Internet Protocol (IP)-based storage networking standard ).  It typically use TCP ports 860 and 3260 and provides authentication for secure sessions.  It is based on the Target ( server ) and the iSCSI Initiator ( client ) model that is built into Microsoft Windows 7 and above or can be freely installed on XP machines for iSCSI support.

There is not much "talk" about this technology, so I wanted to bring this technology to light for those of you interested setting up a home based network environment.

Watch video on how to setup and use a ReadyNAS based system.
http://youtu.be/Ag3tfc2VSUA