Showing posts with label Java Code. Show all posts
Showing posts with label Java Code. Show all posts

Learn Java Programming the Easy Way

Java programming made easy


Like Python, Java is one of those languages refusing to die. It just keeps evolving because of it's easy and simple constructs. Even though it is simple, it is so powerful that it is the main language used on Android. Learning to code in Java will help you learn to write beautiful Android apps faster than you can imagine.

This is an introduction to Java programming to help you get started before moving onto other sources and complex constructs. Use this as a glossary to help you keep track of where you need to go.

Lessons

read more

Lesson 3: Java Assignments and Type Casting

Java programming made easy


Java makes use of the = sign to change the values associated with primitive data types. Remember that there are 8 of these primitive data types namely boolean, byte, char, short, int, float, long and double. Every time you need to make changes to a variable of primitive data type, remember to use "=" using a statement that looks like: variable = expression.

Here are a few examples
myAge = 20;
age = 21;
legalAge = age;
PI = 3.14159265359;
areaCircle = PI * radius * radius;
speed = distance/time;
The name of the variable where changes are being made is always placed on the left and the expression follows after the equal sign. An expression can consist of a mixture of arithmetic operators, other variables and constants.

There are times when you do not want to write the full assignment statement because it makes the code look weird. In situations like that, you make use of what is known as short hand assignments and this can be used on any arithmetic operator.  Here are a few short hand assignment examples.


x += 2; //same as x = x + 2
x++; // same as x = x + 1
x += y; // same as x = x + y;
rem %= 2; //same as rem = rem % 2
d /= 2; //same as d = d / 2
y *= x; //same as y = y * x
s *= (3 * x); //same as s = s * (3 * x)
f -= 100; //same as f = f -100;
b--; //same as b = b - 1;
There are times when you intentionally want to assign a value of one primitive type to a variable of a different type without generating a type mismatch error. Java will allow you to do this and it is known as type casting which is simple defined as the process of converting a value to match the data type of the variable you intend to store it in. Take a look at this type casting example.

int length = 5.45; //length cannot store double values because it is an integer data type
int length = (int)5.45; //no type mismatch error because 5.45 was converted to 5
double sum = 4; //no mismatch error because 4 is converted to 4.00
double sum = double(4); // is the same as above
The reason why its was legal to assign an integer value to a variable of double data type without casting it is because Java automatically did the casting and hence, there was no need for us to explicitly do the casting from int to double. This is known as automatic type casting and it is only done in the right direction whilst explicit type casting is done when moving from right to left. The direction is determined by the following assignment compatibility sequence.
byte —> short —> int —> long —> float —> double
Type coercion direction (—>)
 
byte <— short <— int <— long <— float <— double
Explicit type casting direction (<—)

You might be wondering why type compatibility is arranged in that way. In order to understand this, you need to take a look at the primitive data type table in the previous post and you would notice a few things right away.
  • First thing you will notice is the size of the primitive data type. The compatibility assignment sequence is arranged in ascending order with byte being the smallest with a size of 1 byte and double being the largest with a size of 8 bytes.
  • Secondly take note of the range of numbers each primitive data type can hold. A byte has a range of a 256 integers from -128 to 127. An int has a range of 4.29 billion integers ranging from -2147483648 to 2147483647. A double has the biggest range of all primitive data types.
Now that you are aware of the size and range of primitive data types, you would agree that a double is big enough to hold a float number or any number to its left in the assignment compatibility sequence. Likewise, an int is big  enough to hold a byte or short number because they are on the left of int but not big enough to store a float or double because they won't necessarily fit. 

You should however take note that you can use explicit type casting to store a double number to an int data type at the expense of losing some data such as the fraction. This means explicit type casting is done at the risk of losing data.
read more

Lesson 2: Java Variables and Naming Conventions

Java programming made easy


Unlike Python, variables in Java sometimes referred to as identifiers are declared by their type. Common types used are String and int. Also take note that Java is very case sensitive, so a variable "data", "Data" and "DATA" would be treated as separate variables. When naming your variables in Java or any other programming language, it is important that you abide to the following rules. In other words, you should adopt the PascalCase for class names and camelCase for other identifiers.
  • An identifier MUST not start with a digit and all characters must be letters, digits or underscore symbol.
  • The FIRST character should be lower case if the identifier is a variable
  • ALL characters must be upper case if the identifier is a constant variable
  • The FIRST character should be upper case if the identifier is a class name 
 These naming conventions are there to make it easy to read code and it also comes in handy when debugging. When you are reading a code written by another programmer, you should be able to spot the name of the class right away and identify any variables used at any stage of the code. The following are perfectly legal ways of naming a variable.
  • mydata
  • my_data
  • myData
  • myData1
  • thisJavaVariable
Just like any other programming language, Java too does have special words that can NEVER be used to name identifiers. These special words are referred to as keywords and reserved words. You have already seen public, class, static, void, main, String, int, print, System, print, println, etc.


A variable has to be declared before it can be used in Java. The prefix to the variable name indicate what type of data is to be stored in the variable. More than one variable of the same type can be declared in the same line. Here is an example of variable declaration.
  • String myData;
  • String varOne, varTwo, varThree;
  • int thisData = 1;
Variables can also be initialized in the same line it is declared. If it isn't initialized, it is automatically assigned a default value. Java has 8 basic data types also known as primitive data type. See the table below that shows their different properties.

Primitive Data Types
Type Value Type Memory Used Default Value Size Range
byte integer 1 byte 0 -128 to 127
short integer 2 bytes 0 -32768 to 32767
int integer 4 bytes 0 -2147483648 to
2147483647
long integer 8 bytes 0 -9223372036854775808 to
-9223372036854775807
float decimal 4 bytes 0.0 -3.40282347 × 1038 to
-1.40239846 × 10-45
double decimal 8 bytes 0.0 ±1.76769313486231570 × 10308 to
±4.94065645841246544 × 10-324
char single character
(unicode)
2 bytes \u0000 all unicode
characters
boolean true or false 1 byte false n/a

Take note that String is not a primitive data type but an object data type. Its default value is null which is the same for all object data types.
read more

The Java Series

Java programming made easy


Java is a popular programing language that can run on any computer regardless of its architecture. It first appeared in 1995 when it was developed by a group of Sun Microsystems Engineers an d it is now managed by Oracle Corporation.

Before learning to code in Java, it is advisable that you get a strong fundamental grasp of the basic programming concepts. The best way to do this is to learn one of the best and easiest programming languages you will encounter called Python. It is so easy that you can learn its syntax in 1 day and probably be very proficient by the end of the first week.

To write Java code, you are going to need preferably the latest Java Development Kit and an IDE such as jGrasp, Eclipse or NetBeans. There is another handy utility that you will need and that's called a notepad. Most programmers do not need an IDE to write and compile their code, they use notepads and run their code from the command prompt. The best free notepad you can find as of today is Notepad++ and Sublime Text . The next best Java resource you are going to keep in mind is the Java API where all pre-built in classes and methods are listed together with instructions and explanation on how to use them.

Because not everyone has access to the internet, you might want to get a Java reference book from your local bookstore or any of these books from Amazon.
  1. Introduction to Java Programming by Daniel Liang
  2. Java How to Programm by Paul Deitel 
  3. Absolute Java by Walter Savitch
If you have no interest in getting a book, the internet would also be sufficient provided you have full access. Wikipedia and Stack Exchange and other website have proven to be very useful.

That's pretty much all you need to start learning programming concepts with Java. Click and bookmark the label The Java Series to see all posts related to Java. This series of post won't cover the hardcore stuffs, just the basics to get you interested in programming with Java.
read more

We Only Desire The New Device


Came across one of those unusual article the The Onion about the undesirable device and it got me appreciating just how brilliant that article is. I found it brilliant because it was written generic in such a way that it can be applied to pretty much any device regardless of its manufacturer. One can't help but think this article was written to poke fun of iPhone enthusiasts.

There are 11 key variables you have to take note of:
1. The old device
2. The new device
3. Nationality of consumers
4. The manufacturer
5. The manufacturer spokesperson
6. The selling price
7. Consumer 1: owns old device
8. Consumer 2: just got the new device
9. Consumer 3: showing off the new device
10. The device enthusiast
11. Location from where article is posted

Now that you are aware of the key variables in the article, you can pretty much replace everything in the article with the 11 variables. You can pretty much just put all this in a programming language and insert all the variables in and whip out a number of your own customized articles.

I will name the variables like this:

  1. oldDevice
  2. newDevice
  3. nationality
  4. manufacturer
  5. spokesperson (has first and last name)
  6. sellingPrice
  7. consumerOne (has first and last name)
  8. consumerTwo (has first and last name)
  9. consumerThree (has first and last name)
  10. enthusiast (has first and last name)
  11. location

I will put the generic article with all variables inserted in and you can have fun creating your own articles.

<location>—With the holiday shopping season officially under way, millions of consumers proceeded to their nearest commercial centers this week in hopes of acquiring the latest, and therefore most desirable, personal device.

"The new <newDevice> is an improvement over the old <oldDevice>, making it more attractive for purchase by all <Nationality>," said <spokesperson>, a spokesperson for the large conglomerate that manufactures the new device. "The old <oldDevice> is no longer sufficient. Consumers should no longer have any use or longing for the old <oldDevice>."

Added <spokespersonLastName>, "The new <newDevice> will retail for $<sellingPrice>."

Able to remain operational for longer periods of time and occupy a demonstrably smaller three-dimensional space, the new <newDevice> is so advanced when compared to the old <oldDevice> that it makes the old <oldDevice> appear much older than it actually is. However, the new <newDevice> is reportedly not so radically different as to cause confusion or unwanted anxiety among those familiar with the feel of the old <oldDevice>.

"Its higher price indicates to me that it is superior, and that not everyone will be able to afford it, which only makes me want to possess it more," said <consumerOne>, owner of the old <oldDevice>, which he obtained 18 months ago when it was still the new <oldDevice>. "I feel a strong urge to purchase the new <newDevice>. Owning the new <newDevice> will please me and improve my daily life."

"It's difficult to remember how I ever found enjoyment in my old <oldDevice>," <consumerOneLastName> continued. "It is no longer appealing to the eye."

In addition to aesthetic and technological enhancements, <manufacturer> claim the new <newDevice> comes equipped with a wide range of desirable features, including fewer buttons for pressing down and holding; a new wire for connecting to larger, less-portable devices; and fewer device-related errors and frustrations.

The new <newDevice> will also be available in blue.

"Not only will I be able to perform tasks faster than before, but my new <newDevice> will also inform those around me that I am a successful individual who is up on the latest trends," said <consumerTwo>, whose executive job allowed her to line up for several hours in the middle of the day in order to obtain the previously unavailable item. "Its attractiveness and considerable value are, by extension, my attractiveness and considerable value."

Consumer <consumerThree> agreed.

"I'm going to take my new <newDevice> wherever I go," said <consumerThreeLastName>, holding the expensive item directly in the eyeline of several reporters. "That way no one on the street, inside the elevator, or at my place of business will ever mistake me for the sort of individual who does not own the new <newDevice>."

Added <consumerThreeLastName>, "The new <newDevice> brings me satisfaction."

Despite the visible excitement among most consumers, some claimed to be exercising caution, choosing instead to sit back and wait for a newer version of the new <newDevice> to be released before making a purchase.

"True, it appeals to my most basic insecurities, but this new <newDevice> will ultimately be replaced by a newer device, rendering it completely undesirable and utterly repellent to my personal tastes," device-enthusiast <enthusiast> said. "Also, I should start saving my money for the next latest device, which will replace the newer new <newDevice> a couple months after that."


I will use the generic article above to talk about the new iPhone
These will be the variables:

  1. oldDevice: iPhone 6
  2. newDevice: iPhone 7
  3. nationality: American
  4. manufacturer: Apple
  5. spokesperson: Chris Gaither
  6. sellingPrice: 449
  7. consumerOne: Eric Rottenberg
  8. consumerTwo: Allison Berding
  9. consumerThree: Sean Johnson
  10. enthusiast: John Appleseed
  11. location: Cupertino

Just look at how the generic article works if variables above are substituted in.


CUPERTINO—With the holiday shopping season officially under way, millions of consumers proceeded to their nearest commercial centers this week in hopes of acquiring the latest, and therefore most desirable, personal device.

"The new iPhone 7 is an improvement over the old iPhone 6 making it more attractive for purchase by all American," said Chris Gaither, a spokesperson for the large conglomerate that manufactures the new device. "The old iPhone 6 is no longer sufficient. Consumers should no longer have any use or longing for the old iPhone 6."

Added Gaither, "The new iPhone 7 will retail for $449."

Able to remain operational for longer periods of time and occupy a demonstrably smaller three-dimensional space, the new iPhone 7 is so advanced when compared to the old iPhone 6 that it makes the old iPhone 6 appear much older than it actually is. However, the new iPhone 7 is reportedly not so radically different as to cause confusion or unwanted anxiety among those familiar with the feel of the old iPhone 6.

"Its higher price indicates to me that it is superior, and that not everyone will be able to afford it, which only makes me want to possess it more," said Eric Rottenberg, owner of the old iPhone 6, which he obtained 18 months ago when it was still the new iPhone 6. "I feel a strong urge to purchase the new iPhone 7. Owning the new iPhone 7 will please me and improve my daily life."

"It's difficult to remember how I ever found enjoyment in my old iPhone 6," Rottenberg continued. "It is no longer appealing to the eye."

In addition to aesthetic and technological enhancements, Apple claim the new iPhone 7 comes equipped with a wide range of desirable features, including fewer buttons for pressing down and holding; a new wire for connecting to larger, less-portable devices; and fewer device-related errors and frustrations.

The new iPhone 7 will also be available in blue.

"Not only will I be able to perform tasks faster than before, but my new iPhone 7 will also inform those around me that I am a successful individual who is up on the latest trends," said Allison Berding, whose executive job allowed her to line up for several hours in the middle of the day in order to obtain the previously unavailable item. "Its attractiveness and considerable value are, by extension, my attractiveness and considerable value."

Consumer Sean Johnson agreed.

"I'm going to take my new iPhone 7 wherever I go," said Johnson, holding the expensive item directly in the eyeline of several reporters. "That way no one on the street, inside the elevator, or at my place of business will ever mistake me for the sort of individual who does not own the new iPhone 7."

Added Johnson, "The new iPhone 7 brings me satisfaction."

Despite the visible excitement among most consumers, some claimed to be exercising caution, choosing instead to sit back and wait for a newer version of the new iPhone 7 to be released before making a purchase.

"True, it appeals to my most basic insecurities, but this new iPhone 7 will ultimately be replaced by a newer device, rendering it completely undesirable and utterly repellent to my personal tastes," device-enthusiast John Appleseed said. "Also, I should start saving my money for the next latest device, which will replace the newer new iPhone 7 a couple months after that."
read more