Author Topic: My Java Studies Topic.  (Read 5465 times)

0 Members and 1 Guest are viewing this topic.

SoShySkye

  • Tier 1
  • *
  • Posts: 2
My Java Studies Topic.
« on: December 06, 2012, 09:35:49 PM »
Be the best programmer around, but I just took my java 2 exam and I've always found that the best way to study is to help others with the very things you're trying to learn. So here it goes, I'll try and keep it as relevant as I can to the average person learning a new language.

If you already know a bit about programming you can probably skip this part. This first section is an introduction to setup and basic concepts.

|||||||
Intro
|||||||

Okay, how can we begin? Well, lets start with setup for now. At the end of the day, the code you input is just a series of printable character to be interpreted (and compiled) by your environment. This just means that after you have your code together, compiling makes a translated version of your code in a language the computer can actually understand.

Before we can compile or run our code, we need to download the tools to do so.

Simply google java jdk and download the Java Development Kit and Java Runtime Environment right from sun.com. Although the Java Development Kit contains the files from the Java Runtime Environment, my browser is restricted to the 32 bit version, so I downloaded both that and the 64 bit Java Development Kit to get started.

Now that we have the tools to write and run code, lets talk about structure. The important part of this is  that your compiler knows the structure of java so it can translate these to machine code for your computer to understand. Much like any other language, the correctness of HOW you say something in a programming language has nothing to do with the truth value of what it is you're TRYING to say. The important part is ensuring that your code follows the structure of the language so there is no question for the computer as to what you're telling it to tell a machine do. This is what makes programming function; proper code translates your ideas into well defined structures without any ambiguity.

To simplify the whole process, I'd recommend downloading an Integrated Development Environment, or IDE. I used one called Jgrasp, but most people like to work in Visual Studio and similar environment. Find one  and create a java file in it. I won't cover the steps to this because they're relatively well defined and easily supplied by the content providers, so once you get your IDE set up, we're ready to get to the language!

Create a text file inside your IDE (If you use one :P).

While you may hold representations of your code in plain-text files, the development kit stores this code in Class files. Class files are where most of our coding will take place, so lets try and make one!


|||||||||||||||
End of Intro
|||||||||||||||

First, tunes:
Harry Enfield: loadsamoney


Loud, obnoxious things help me focus, but thats just me.

Java is an Object Oriented programming language, and in general we need an object to work with. We'll start by making a box to play around with the structure of our language. The great part is that Java never asks you too many questions, it only wants to know as much as it needs to know to do what you want. So lets start by looking at what java asks of you to create a class file. Here is an example:

public class Santa{

}

Thats all!

In order to  create a simple class in java, all you need to tell it is;

1. Who can access this?*
2. What type of object is this ?
3. What name will we use to talk about it?
4. Curly Braces!
* = Not really, see 1. below.

Lets look at those for a second.

/////////////////////

1. Access control.

Access control restricts the ability of your files to read the each-other. This is helpful for two main reasons, security and structure. In this case, we have used the public identifier, but lets look at all possible settings:

Public: All classes can access this code.

Protected: Only this class, the package its contained in, and subclasses can access this code.

* = "none": By default, only this class and the package can access this code.

Private: Only this class can access this code.

These rules prevent code from getting into places it shouldn't, or accessing information you don't want it to. For now, we'll just use public.

2. Type.

Really, we only need to worry about a class right now but there is a type called an interface. Think of an interface as a checklist, it provides a way for you to make sure that the file has all the things on that list before the file that uses the interface could be right. If you and a friend were making a game with two basic character types, but the two of you wanted to design how the levels might react to the characters first, you could write an interface to agree on what your files need to have in order to work properly with the level. More on this in a bit.

3. Name.

Anything you make in java needs to have a distinct name to prevent confusion, so your files should be given an appropriate name so they can interact properly. General practice dictates that the name be capitalized. More on this later.

4. Braces

In java, one of the primary means of separating code is  the use of curly braces: "{" and "}". More often than not, they just function as convenient containers to make distinctions about the behavior of our code.  Again, more in a second.

//////////////

Okay, so we have Santa, now what. Well, when we made Santa, we only told java those attributes. These attributes aren't one for one particular Santa, either. Technically, a user would make as many Santas as they want, but we'll hold off on that for a second.

 What else would we need to do something useful? Utility demands that we either store data, or behavior (probably both). So lets do both! Before we can even do that, though, we need to know how to interact and store information in Java.

There is a basic data type in java called a primitive, and it denotes common object that java can interact with with  well defined attributes. The primitive types are as follows:
 
byte, short, int, long, float, double boolean, char.

Lets go into a bit on each.

byte: Uses an 8 bit binary number to represent a signed integer between -128 and 127 inclusively. Has its uses.

short: Essentially, the same as a byte, but with 16 bits. This extends its range to -32768 to 32767

int: The default choice for an integer. Just like the last two, but 32 bits, extending its range... a lot, don't worry about hitting that limit for now :P

long:  Same as an int, but 64 bit.

float: 32 bit floating point number. Really ugly, we'll get to him later Append an f, for now, to a decimal number to denote it as a float.

double: 64 bit, the more likable of the decimals. 

boolean: A true or false value.

char: A single character, with a wide range of values, but we'll just leave it to alphanumerical for now. To refer to a character, put single quotes around it, as so: 'o'

lets look at the syntax of how to talk about this data by making one of each in our Santa class;

public class Santa{
private static int fingers = 10;
private static byte toes = 10;
private static short eyes = 2;
private static long hairs = 2000000;
private static double height = 5.6;
private static float weight = 257.843f;
private static char middleInitial = 'c';
}

Note that all of these values have private and static before them, this means that every Santa we make shares all of these, and that only Objects of type Santa can access them. This is good practice, because it stops users from looking at or changing things we don't want them to. We also gave each of them a variable name, to refer to later. Typically, these are lowercase with uppercase letters to denote the start of another word. 

How do we get at these values if we want them to be private? Simple, we provide "getter methods" to allow other classes to ask this one for information. Methods are what programs "do", and will be your primary focus most of the time. Lets do one example by allowing the user to ask for santa's middle initial.  The syntax for that would be similar to that of a variable:

public static char getMiddle(){
return middleInitial;
}

Note that before the inclusion of the parentheses, this line looked very similar to the others. This is by no accident; the output of this method is intended to be a character, so we explicitly refer to that when creating the method. Because of this typing, and the fact that the method is private, another class could call this method to get at these variables by calling the corresponding method. The parentheses always accompanies a method because they define the structure required to call that method, in a defined order. In this case, we access no variables, so we need no input. A user calling the method might do so as follows;

char santaChar = Santa.getMiddle();

This is actually a special case, because the middle initial and method are both static. Because of this, we're able to ask for the middle initial without explicitly asking one particular Santa object.  More often than not, though, an object must first be created to call a method. To accomplish this, we need to make a constructor method within Santa to allow for this. The constructor is a special method that shares the name of the class. It is often also a setter method for the variables in one particular object, so we can define the creation of a unique Santa, with all of his attributes, like so.

public class Santa{
private int fingers;
private byte toes ;
private short eyes;
private long hairs;
private double height;
private float weight;
private char middleInitial;
public Santa(int fin, byte toe, short eye, long hair, double heigh, float weigh, char middle)
{
fingers = fin;
toes = toe;
eyes = eye;
hairs = hair;
height = heigh;
weight = weigh;
middleInitial = middle;
}
}

Note that the method pulls these values into variables outside the method. This is important because anything defined inside the method disappears upon it's completion. Also note that a variable can be referenced without actually setting it. This means the the compiler automatically sets it to either null or a reasonable value, like zero. This is important because null values throw errors, if we try to treat the like a valid entry before setting them. So we have to make sure a value is set before we try to do anything to it.

So far, we've stored data, written a method and written a class. The code can be run  as is, just not without using another class or interacting with java and observing the environment. Instead, lets now create a method that will let us run our program.  A main method looks as follows

public static void main(String[] args){
String message = "ho ho ho!";
System.out.println(message)
}

A few things;
An array, like int[] or String[] or char[], denotes a collection of objects liked together. We'll talk about those later.
A String is a special data type represented by a char array in java. They're used quite often to store plain-text.
System is another special case in java. The Java runtime environment is allowed to ask the machine it runs on certain information to help it run. In this case, java sends the string "ho ho ho!" to the standard output and prints it. Now we have all the elements needed to make it function properly. So lets load it into the compiler and see what happens!

public class Santa{
private int fingers;
private byte toes ;
private short eyes;
private long hairs;
private double height;
private float weight;
private char middleInitial;
public Santa(int fin, byte toe, short eye, long hair, double heigh, float weigh, char middle)
{
fingers = fin;
toes = toe;
eyes = eye;
hairs = hair;
height = heigh;
weight = weigh;
middleInitial = middle;
public static void main(String[] args){
String message = "ho ho ho!";
System.out.println(message)
}
}

Hohoho! Merry Christmas.

Zeriab

  • Tier 2
  • *
  • Posts: 44
  • Current Mood: happy happy
Re: My Java Studies Topic.
« Reply #1 on: December 30, 2012, 03:03:38 PM »
Hi SoShySkye,

Trying to explain how stuff works can be a great way to learn how it works.
Good job in creating this introduction.

I highly suggest wrapping your code in [code] tags. It makes the code more clear and preserves the indention.
The few issues with your last code is for example more noticeable:

Code: [Select]
public class Santa{
    private int fingers;
    private byte toes ;
    private short eyes;
    private long hairs;
    private double height;
    private float weight;
    private char middleInitial;
    public Santa(int fin, byte toe, short eye, long hair, double heigh, float weigh, char middle)
    {
        fingers = fin;
        toes = toe;
        eyes = eye;
        hairs = hair;
        height = heigh;
        weight = weigh;
        middleInitial = middle;
        public static void main(String[] args){ // What is this doing here?
        String message = "ho ho ho!";
        System.out.println(message) // Missing semicolon
    }
}

In java it is not best practice to shorten the input variables in the constructor to make them unique from the instance variables.
Instead name them the same if that makes the most sense, then you can use something like this.fingers = fingers; for the assignments. I.e. the code could look like this:
Code: [Select]
public class Santa
{
    private int fingers;
    private byte toes ;
    private short eyes;
    private long hairs;
    private double height;
    private float weight;
    private char middleInitial;

    public Santa(int fingers, byte toes, short eyes, long hairs, double height, float weight, char middleInitial)
    {
        this.fingers = fingers;
        this.toes = toes;
        this.eyes = eyes;
        this.hairs = hairs;
        this.height = height;
        this.weight = weight;
        this.middleInitial = middleInitial;
    }

    public static void main(String[] args)
    {
        Santa santa = new Santa(10, 10, 2, 2000000, 5.6, 257.843f, 'n');
        String message = "ho ho ho!";
        System.out.println(message);
    }
}

Note that I also streamlined your {braces}.
There are typically two conventions for how to align them
Code: [Select]
public KlassSameLine {
    // ...
}

public KlassNewLine
{
    // ...
}
Whichever you choose I suggest you stay consistent in your use.
Do note using one style for classes and another for methods can be perfectly fine, but changing styles for the various methods in a class just needlessly increases the complexity of the code. (I.e. makes it more confusing)

I suggest you also include a little something about the typical structure of a java class.
I.e. including something about the starting package definition and imports.
Not including it can easily burn beginners with the compiler giving weird errors.
Feel free to look at the structure of a class I wrote like half a year ago: http://pastebin.com/P7s7PTR5


Good job again, I wish you good wind in becoming a great programmer :D
*hugs*
 - Zeriab

Gogobrasil8

  • Tier 3
  • *
  • Posts: 87
  • Gender: Male
  • Current Mood: cheerful cheerful
Re: My Java Studies Topic.
« Reply #2 on: January 22, 2013, 07:11:38 PM »
Oh! Good! I was looking after To learn This. Thanks! :gothat!:
Lunair >> all

To the Moon - Finished
Do you remember my lullaby? - Finished
The Mirror Lied - Finished
Quintessence - Finished (Sorta, of course.)
A Bird`s Story - Finished

:plat:<- I love This Smiley

Twitter: @gogobrasil8_br

Dreadsteed

  • *
  • Tier 3
  • **
  • Posts: 92
  • Current Mood: happy happy
Re: My Java Studies Topic.
« Reply #3 on: January 28, 2013, 09:33:52 PM »
This seems like a cool project, in the future add some stuff like Inheritance, Interfaces, inner classes, generics as you learn it. It would be a good learning experience and a good thing for others to learn from. Heck I can probably look through and see how well I understand some of these concepts.

What book are you using for your java class?

sectionfull

  • Tier 1
  • *
  • Posts: 1
Re: My Java Studies Topic.
« Reply #4 on: December 06, 2013, 06:09:57 AM »
The experience gained from this site useful and it is very valuable. It allows me to bring these experiences to use in everyday life

Kyo

  • no title at all
  • *
  • Tier 7
  • **
  • Posts: 1264
  • Gender: Male
  • Current Mood: evil evil
Re: My Java Studies Topic.
« Reply #5 on: December 06, 2013, 06:35:54 AM »
>Java
>use in everyday life

U wot, m8?

Spoiler: show
Replicant alert. Man the bannons!
« Last Edit: December 06, 2013, 06:38:18 AM by Kyo »

Question Mark

  • 疑問符の人
  • Mod-Suspect
  • Tier 7
  • *
  • Posts: 1492
  • Gender: Male
Re: My Java Studies Topic.
« Reply #6 on: December 06, 2013, 07:01:39 AM »
>Java
>use in everyday life

U wot, m8?
Java rice is delicious, y'know?

Guttend

  • Tier 2
  • *
  • Posts: 12
  • Current Mood: happy happy
Re: My Java Studies Topic.
« Reply #7 on: January 21, 2014, 08:03:47 AM »
I am thinking about digging in programming myself but my friends keep demotivating me saying its not easy being a programmer, its rocket science and stuff.

Question Mark

  • 疑問符の人
  • Mod-Suspect
  • Tier 7
  • *
  • Posts: 1492
  • Gender: Male
Re: My Java Studies Topic.
« Reply #8 on: January 21, 2014, 08:46:00 AM »
I am thinking about digging in programming myself but my friends keep demotivating me saying its not easy being a programmer, its rocket science and stuff.
To be fair, all learning endeavors have their own share of reliance on innate knowledge. Obviously, if you ask a 1337 programmer that, he'd tell you the opposite of what your friends said. For you to find out whether you would really enjoy, appreciate, and survive something, you'd have to get in there yourself.

Case in point: I thought level design was -cuss- ing impossible since I have to work with four views at once (3D, top, front, side) but finding a tutorial on the 'net that suited me helped me get in there. Before level design, I tried programming. And eh, I found out myself that I won't get anywhere with it(Pointers pointed that out to me) so I just stuck to scripting using Python and Squirrel. I'm referring to the languages, not animals.