Monday, March 25, 2013

Java;Notes - 7.) Java Operators

In Java you get the usual math operations of:

  • Addition(+)
  • Subtraction(-)
  • Multiplication(*)
  • Division(/)
I am sure by now we know what these do... Other than mess with our brains once we get into Algebra!
"I got it! We will add numbers to English!! It will be marvelous!" - The Devil
Back on topic:

Java and the Modulus:
In java the / operator denotes integer division and so will only divide whole numbers. This is where we get a special division tool called the "Modulus" which looks like: %
If it sounds like something out of Harry Potter your right! This one allows us to magically find remainders of division For example:

  • 15  /  2  = 7
  • 15 % 2 = 1   <---LOOK AT IT GO!
  • 15.0 / 2 = 7.5 
NOTE: If your going to make a calculator to handle Floating Point Numbers its best to do with double instead of int (Which is what I did with my previously posted Calculator Program) 

Java Binary Arithmetic Operators shortcut:
Java also has a nifty built in shortcut for Binary Arithmetic Operators in assignments like so:

x += 4; 
is the same as:
x = x + 4 

In general: Place the operator to the left of what ever sign your going to use!

Increment and Deincrement: 

To get a number / variable to increase or decrease its value by one you simply do this:
  • number++   <--- Adds 1 from variable number
  • number--    <--- Subtracts 1 from variable number

Relational and Boolean operators: 

 Boolean operators will help determine if something is true or false. Think of this as the interesting class in math about "Greater than Less than or Equal to" Since that is what Boolean focuses on. So lets jump into it!
The basic operators are as follows:

  • == (When something is for sure equal to something else)
    • IE: x == 3 (Variable "x" is equal to 3)
  • !=  (Tests inequality)
    • IE: 3 != 7 (3 is not equal to 7)
  • <  (Tests to see if one thing is less than something else)
    • IE: 3 < 7 (is 3 is less than 7)
  • >  (Tests to see if something is greater than something else)
    • IE: 7 > 3 (is 7 greater than 3)
  • <= (Tests to see if something is less than or Equal to something else)
    • 3 <= 7 (Is 3 Less than or Equal to 7)
  • >= (Tests so see if something is Greater than or Equal to something else)
    • 7 >= 3 (Is 7 Greater than or Equal to 3)
  • && (Is the logical "and" operator)
    • The second argument is not evaluated if the first argument determines the value when you combine two expressions with the && operator like so: num1 && num2 
    • If the truth of the first value is determined to be false it is impossible for the result to be true and so num2 is left alone and not evaluated. The following exploit can be used to avoid errors
    • x != 0 && 1 / x > x + y  (Can not / 0) 
  • || (Is the logical "or" operator)
  • ? (Ternary operator: Evaluates Expression1 if the condition is true to the second expression otherwise) 
    • condition ? expression1 : expression2
    • for example: x < y ? x : y
Bitwise Operators:
In java if you want to work with single bits of a string you can do so with Bitwise operators. The typical operators in mention consist of the following:
  • & ("and")
  • |   ("or") 
  • ^  ("xor")
  • ~  ("not")
All of these operators work on bit patterns. Say you have a variable int of "n" then:
int fourthBitFromRight = (n & 0b1000) / 0b1000;
This would return a "1" since the 4th bit from the letter "n" is a 1 and 0 otherwise. Using "&" with the appropriate power of 2 lets you mask out all but a single digit.

There are also the following Operators:
  • >> (Shift Right)
  • << (Shift left)
Which are useful when you need to build up bit patterns to do bit masking. Like so:
int fourthBitFromRight = (n & ( 1 << 3 )) >> 3;

Finally the ">>>" operator fills the top bits with 0. Unlike ">>" which just extends the sign bit into the top bits. 

Note: there is no "<<<" operator.  







Java;Notes - 6.) Variables in Java


In Java when you declare a variable you must also declare its type. Here are a few examples:
  • double salary;
  • int vacationDays;
  • long earthPopulation;
  • boolean done;
NOTE: The use of a semicolon when you see on it means it is the official end of that line of code. Meaning a single line can be any number of lines of the page.

Variable Rules:
When dealing with variables in Java keep the following things in mind:
  1. Variables must begin with a letter
  2. Variables must be a sequence of letters and digits (yes you can use single letter sequences such as "int x = 2.34;" and it will work)
  3. Variables can not contain spaces or symbols such as: @#$% and so on.
  4. In proper naming convention if you have a variable that explains something and uses a mix of names such as a variable for positive and negative numbers its a good idea when naming them to make the first letter of the variable lowercase and them capitalize the first letter of each part after that Like so:
    1. Incorrect but will still work: int posnum; 
    2. Correct: int posNum;
    3. Correct more than one part: int numberOfCakesInShop; (I think you get the picture now)
  5. If you are going to be using more than one of the same data types add them all to the same line. Say for instance again you have a positive number and a negative number. Instead of listing each number type on its own line. Use comma's to put them all on the same line like so:
    1. int posNum, negNum, answer; //Doing it like this will save you space on your code. instead of one line for each just do it like this!
  6. There are occasions where you will have a variable and a type that can only be described one way simply say for instance you have Type: Box and variable: box you can go "Box box;" and call it a day but that might get messy after a while. Instead add a number (To the back) or a letter to the front of the variable like so: "Box aBox;" or even "Box box1;" and these will suit and give a good idea if you have more than one of what ever variable you are using.
Initializing a Variable:
In java you can not just make a variable and start printing it like so:
  1. int vacationDays;
  2. System.out.println(vacationDays);  <--- This will lead to an error telling you to initialize it. 
Initializing Variables is actually rather simple as all you are doing is giving it a meaning just do the following:
  1. int vacationDays;
  2. vacationDays = 12;
Now the variable vacationDays has a meaning and thus something to print out. 
What if I told you there was a better more simple way to do that? Well there is... you can do it all on one line like so:
  1. int vacationDays = 12;
Using the last two methods you will now be able to use the previous print statement to make the screen print out "12" both ways work the same.
Note: you can put variable declarations anywhere in your code. Usually it is wise to keep them near the top so you have an easy reference place.

Constant Variables:
This is not as complex as it sounds it simply means your telling your program of a variable that (For this program) will never change. To do this we make use of the final declaration. Say for instance we are making a program to measure the circumference of a circle. What is one common factor in this calculation.... You guessed it... Pi (Funny... a Pie can also be a circle!) so say we want to make pi a constant... you simply do the following:
  1. final float pi = 3.14159;
and now pi will not change... less you edit that code line for a different number. 


Java;Notes - 5.) Comments and Data Types


Comments:
In Java there are two ways to do comments
  1. The Double Slash: (IE: //Zomg Dat code!) -- Double Slash's are good for taking notes in your code. Or "Commenting out (Explained later)" single lines of code. This in practicality would look more like:
    1. System.out.println("Say something!"); //This is a simple call for a system output on the screen
  2. The Multi-line Comment: (IE: /*This is a comment!*/) Anything between those two slash's will be marked as a comment. This allows for the use of more than one line of comments So it would look more like the following few lines for a proper example:
    1. /*This is a simple comment line
    2. *This is an extension of the same comment line above
    3. *This is the final line in our comment!*/
  3. Documentation Comments: These work in the same way as a multi-line but are used for something specific, generating program documentation All we do is add another asterisk to first line of the comment. Here is an example of how this would work:
    1. /**  <--- See that?
    2. * Program Name: progName.java
    3. * Code maintainer: Your Name (yourname@emailprovider.com)
    4. * Program functions: List, some, stuff
    5. * I am sure you get the point <-- Note if you put this in your program and release it it will show up in the docs. */
Commenting Out: Commenting out is reffered to as using Double Slash comments to "Strike out" code to do tests on how the program will work with out the need to kill the whole line. So for instance you have a program that has two print statements and you want to take one out with out totally killing it you would simply do the following:
  1. //System.out.println("Hello World!");
  2. System.out.println("We will not be saying 'Hello world!' Instead lets say "Salution Mundo!");


Data Types:
In Java every variable must have a declared type (You cant just type "out x = 3;" instead it must be "int x = 3;")
The 8 primitive types Breakdown:
  • Four of them are integers (Whole Numbers... yup... back to math!)
  • Two of them are Floating Point numbers (Numbers with decimal points)
  • One is the Character type (Used with Unicode)
  • Lastly we have Boolean (True and False)
Java Integers:
An integer in Java is any number positive or negative in which is whole and not a fraction or decimal. Java has the following four kinds of integers:
  1. int: with a storage requirement of 4 bytes and a maximum positive / negative value in the 2,000,000,000 range 
  2. short: with a storage requirement of 2 bytes and a Maximum positive / negative value in the 32,000 range
  3. long: with a storage requirement of 8 bytes and is considered anything over positive / negative 2,147,483,648
  4. byte: with a storage requirement of 1 byte and a maximum positive / negative range of: -128 and 127
Note: You will most likely be using the int type in most cases as the rest are really for specialized programs.
Java Floating Point Numbers:
An FPN is any number that has fractional parts or decimal points. Java Has two kinds of FPN:
  1. Float: Any number with up to 7 significant decimal digits (IE: 1.2345678 is a float)
  2. Double: Any number with up to 15 Significant decimal digits ( IE: 3.141592653589793 is a double.... this one is also pi or at least the first 15 digits)
Note: A "Significant Decimal Digit" is defined as how many decimal places will show before the numbers get abbreviated like when you see something like: "E+38F" at the end of a decimal number. All the numbers after the decimal and before the "E" are considered significant.
The Java "Char" type:
Put simply the char date type allows for the use of an old system called "Unicode" which was a number variant of regular keyboard buttons. Unicode was also used to be able to include different letters for different languages. to use Unicode in code you simply use the "Escape Sequence" of \u and whatever  unicode value you want to put in there. an example would be:
Normally you start the "Main" part of a java program by calling it out like so: public static void main(String[] args)
Now lets replace the square brackets ([]'s) with their Unicode values to get the same results: public static void main(String\u005B\005D args) 

Java Escape Sequences:
You can think of java's escape sequences as way of formatting the text in your program. Here are the basic need to know ES's and what they mean:
  • \b = backspace
  • \t = tab
  • \n= linefeed (everything after this shows up on the next line)
  • \r = carriage return
  • \" = double quote
  • \' = single quote
  • \\ = backslash
Java Boolean Values:
Put simply there are two and they are what they state:
  1. True
  2. False

Java;Notes - 4.) Java Command Line Basics: Moving in the mess!


Understanding the use of the command line utilities for Java is a needed skill at this point in the game since you might not have a GUI all the time.

So in order to compile and run Java files you simply do the following:
  1. Open the Windows Start Menu
  2. Go to the search bar and type "cmd" into it.
  3. Click the program that comes up. You will get greeted with a Classic Command Line Interface or "CLI"
  4. Now to navigate the file system you simply use the "cd" command which means "Change Directory"
  5. So to get to your Java files you simply use: cd c:\\path\to\java_files (cd C:\Program Files\Java\jdk1.7.0_17 - to get the JDK folder)
  6. To compile a program navigate to where you keep your java programs (cd C:\Users\Zilvarael\Desktop\Android Dev Tools\eclipse\CoffeeShop -- for me)
  7. then you simply use the: javac programName.java (Ex: javac hello.java) javac = Java compiler.
  8. To run the program you simply do the following: java hello to launch any java class file!
To launch a java applet:
  1. Use java compiler on what the applet file: javac applet.java
  2. Launch the applet by using: appletviewer applet.html -- This is after an applet is made in my case I learned from the books example applet (Which can be found in the CoreJava Source we downloaded before.

Java;Notes - 3.) Installing Library Source and Documentation: Making a house a Home


There are a few more things we need to do in order to get started with Java. We have our house bought for and we are all moved in the house is livable and so on now its time to add those touches that make our house a home! Note all of the following can be done through the GUI so this is the GUI version of the instructions which are simple to work with:

  1. Download the following Files:
    1. http://www.oracle.com/technetwork/java/javase/documentation/java-se-7-doc-download-435117.html   <---Java Documents
    2. http://horstmann.com/corejava/corejava9.zip <-- CoreJava7 Book Code Examples.
    3. The third ZIP is Located in the JDK folder mentioned before (Located here: C:\Program Files\Java\jdk1.7.0_17\) as "src.zip"
  2. Unzip all three files to the desktop and copy paste the files to the C:\Program Files\Java\jdk1.7.0_17\ directory 

Doing this will enable you to keep all the Java docs and example code in one place! :D

Side Notes:
  • You will by the time you get this far on this page have a local copy of the documents for Java 7 you can find them here: file:///C:/Program%20Files/Java/jdk1.7.0_17/docs/docs/index.html Just open this in your web browser. It is suggested you book mark this and keep it handy as it will be useful! This is a local file so you dont need to use the web to access it! :D

Java;Notes - 2.) Getting setup with Java: Moving in


Getting setup with Java on windows 7 is rather strait forward on windows however there are a few steps I will cover in here for the "Just in Case"

Downloading JDK7:
  1. Go to the following page to download the latest JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Download by clicking on the box that says: Java Platform (JDK) 7uXX (In the case of writing: 7u17) this will cause the EXE file to download
 Downloading Eclipse(Our Dev Enviroment):
  1. Go to: http://www.eclipse.org/downloads/packages/eclipse-classic-422/junosr2 Download the version that corresponds to your OS
  2. Navigate to your downloads folder and Unzip the Zip to the desktop.
Setting up the Environment:
  1. Navigate to your computer's download folder (c://users/your-username/downloads *unless you specified it elsewhere in your web browsers settings)
  2. Double click the:  jdk-7u17-windows-x64.exe to install
  3. After you installed the JDK7 you should then be able to use eclipse to write programs. With little to no issues when you start eclipse up as it automatically registers the JDK location on the file system.
To be convenient you can simply copy eclipse from the folder you unzipped it to and paste a shortcut to the desktop allowing you to run it from there. To paste the shortcut you go into the eclipse folder copy the EXE / Application file and right click and empty spot on the desktop click "Paste Shortcut" button and you will now be able to use eclipse from the desktop.

====JUST IN CASE!!====

How to manually set the Path to the Java JDK7 Folder(Setting up Command Line Usage):
  1. Click on the start menu
  2. Move your mouse to the "computer" button right click on it
  3. Click "Properties" from the menu that shows up this should bring you to the "System" Screen where it tells you all the info for your computer.
  4. To the top right of the screen there is a menu click the "Advance System Settings" option. This will bring up a window called "System Properties"
  5. In the system properties window go to the advanced tab if you are not there already
  6. Click the Environment Variables Button (Its the last option on the window before the standard windows UI kicks in) It will bring up the coresponding screen.
  7. On the bottom part of the window there is a list called "System Variables" Scroll till you find "Path" Click it once to highlight
  8. Press the edit button right under the list subwindow. This will bring up another screen. Go to the back of the list
  9. Add a semicolon to the back of the list and add the following path to the list: C:\Program Files\Java\jdk1.7.0_17\bin
  10. Click "OK" and then you can exit those windows. -- You should now be setup to run JDK commands from the windows command line!

Java;Notes - 1.) Basics of Java: Getting to know our new friend

Right so starting today I am going to be working on putting some Java related notes on this page just to keep things fresh. As some of you might or might not know I am working on re-learning Java but I am starting with the latest Java (J7) instead of Java 6. I will be taking these notes off of the book: Core Java (Version 9) So here is my statement of credit to the authors. So with this being said... Lets get to work!


What is Java:
Java is an object oriented programming language that was originally created in 1992 as an improvement to C++
Since 1992 Java has gone through 7 versions and is currently at "Java 7" and only really picked up speed in 1996
after the creation of the worlds first web browser built in Java called the "Hot Java" browser and it featured the capability
to run java applets over the world wide web. Since then Java has been in boom. However not with out its own share of issues.

Java and the White Paper Buzzwords:
Java when it was conceived had aimed to be quite a few things in its time such as the following list:

Simple:
Java had aimed to be the next evolution of C++ having stripped out most of the unused, and grief ridden features, as well as
cleaning up the syntax. Over all if you know C++ you will have little problem with Java as the two are related. Some of the syntax
Stayed the same such as the switch statement which we will go over later.
Object-Oriented:
Java wanted to be revolutionary in its thinking so it took on the task of making an object oriented approach to code. OOP as it is 
referred to is the act of transferring data from one class to another. Whole Programs can be referred to as an object with a simple
import function you can use all of the classes and calls from one program to another.
Network-Savvy:
Java was meant to be distributed over a network and even has the ability to remotely use objects from other programs even if they are
across the world.
Robust:
Java itself is more than a simple programming language, its a full platform. This does not mean that you can just code your own OS with it
and start using that on your supercomputer it does however mean that it provides lots of standard features. Such as:
  • Live Bug Tracking (Errors show up before you run the program)
  • No need to keep track of memory
  • and many other features that make Java a good language.
NOTE: However Java is not for the feint of heart. Due to its complex nature and its hundreds of thousands of library's Java is not suggested for the novice programmer. 
Secure: 
Java by default creates its own little island on your computer to work out of. This is often called the "JVM" or Java Virtual Machine. The JVM by default isolates the System from Java and allows the code to run in sort of a safe sandbox.
Architecture-Neutral:
What makes Java cross platform for is that any machine with the Java Runtime Environment (Another Term fro the JVM Also known as the JRE) will be able to run the programs made. Hence the motto: "Write once run anywhere"
Interpreted
Java's Interpreter basically allows you to run your code anywhere you have the "JDK"(Java Development Kit) installed. With out the need for special software.
High-Performance:
Java makes use of what is called "Just in time compilers  to make code run faster than it ever did in the yesteryears of Java's life. For a long time Java was considered "Adequate"  to get the job done.
MultiThreaded:
Due to being able to do more than one thing at a given time Java is able to make the most use of its threads to created live Interactive responsiveness and  real-time behavior. Meaning Speedy object goes in speedy object flies out.
Dynamic:
Java has a habit of evolving with its environment. The more complex things get in the environment the more you should be able to do.