Skip to main content

Java for Beginners

What is Object in Java?
Objects, in the real world, describe things that have both a state and behaviour. For example, your phone's state can be: turned on or turned off while its behaviour can be: displaying a game or playing music.

Objects, in programming, are similar. They too have a state and behaviour, storing state in fields, also called variables, and behaving via use of methods. 

What is Class in Java?
A class, is the "blueprint from which individual objects are created" -- a template. Classes are used to create objects, and classes also define these objects' states and behaviours.

The class we have created together, HelloWorld, is not the best example for what a class is, so here's another example class that better illustrates one: 
Let's dissect this class. Pay careful attention to the braces, which have been color coded to demonstrate where each brace's counterpart is. (Notice how the indents give us a sense of hierarchy. The red braces comprise the largest section of the class, the brown braces comprise the second largest section, which in turn comprises two identically sized yellow and green sections).

The red braces contain the class called Phone. In other words, it contains the blueprint that you use to create Phone objects. This class contains one method called togglePower, which as we have mentioned before is used to express or change the behavior of an object - it is a way of doing something.

The yellow braces denote the beginning and end of the method called togglePower. This method checks the value of the boolean variable "turnedOn" and acts accordingly.

The green braces denote the beginning and end of one conditional if statement, and the blue braces do the same for another conditional if statement.




public static void main(String[] args) {
   // Method body
}

public - visible to other classes. Java programs usually incorporate multiple class files, so if you want to refer to code in the class from other classes, you make it public. (The opposite is private).

static - means that this method belongs to the Class, not an instance of the class. Recall that classes are blueprints for creating objects. The main method is the first piece of code that runs. Since we have no way of creating theHelloWorld object to call its main method, it has to be static. If that doesn't make sense, don't worry too much about it. We will discuss it in detail later.

void - whenever we call a method (call means to ask for it to run), we can ask to receive a value back. Void means that no value will be returned. For example, if we have a method that adds two values together, then we would not write void, but int, so that the method can return an int value representing the sum.



Methods, in Java, are indicated like below:

I. methodOne() 

This above method is called "methodOne" and requires no arguments, or parameters, for the method to work.

II. methodTwo(type argumentName)

This above method is called "methodTwo" and requires an argument of the declared type (which can be int, boolean, etc). 

When dealing with a method that requires an argument, at the moment it is invoked (or called by using a statement), it will ask for an input. It will take this input and use it in the method. I will show you how this works in the following examples.


Applying #2 to the main method:

main(String[] args)

We know that the main method requires an argument of type String called args. The [] indicates that this is an array, which you can think of as a table of corresponding x and y values. For now, just know that this is what goes in as the argument of the main method every time. You do not need to understand why or what it means just yet. Trust me.


Here is the main method with its braces: 
  1. public class HelloWorld {
  2.  
  3.    public static void main(String[] args) {
  4.       // Method Body
  5.    }
  6.  
  7. }
If you were to copy this code into eclipse and pressed Run, it would compile successfully and run.

The problem is... the main method is empty. It won't do anything yet.

So let's write our first statement (or command): 
  1. System.out.println("Hello Kilobolt!");
Pretty basic right? No? Let's dissect it.

1. System refers to a class in the library that I've mentioned before (from which you can import code), also known as the API (Application Programming Interface).

2. The periods between "System" and "out" & "out" and "println" represent hierarchy. This is called the dot operator. When we use a "." on an object, we are able to refer to one of its variables or methods.

For example:

HelloWorld.main(args);

would invoke the main method in the class HelloWorld (not that you would ever do that since main methods are called automatically).

3. println requires an argument. Inside it, you can type both literals (meaning things that represent themselves) and variables (things that contain values).

You indicate literals with quotes: " " and variable names can just be written.
I will show you an example on this.

(Note: If you want to know more about the System.out.println and how it works at the lowest level, you can refer to this site: http://luckytoilet.wordpress.com/201...-really-works/
But I recommend not doing so until you have a better understanding of Java).

I know it's frustrating for some of you to be writing code that you don't yet fully understand, but just bear with me for a while. Everything will become clear.

Now we insert the statement into the Main Method to get the full working code: 
  1. public class HelloWorld {
  2.    
  3.     public static void main(String[] args) {
  4.         System.out.println("Hello Kilobolt!");
  5.     }
  6.  
  7. }
Copy and paste this into eclipse and press Run!
You should see: 
 Hello Kilobolt! 
What's going on here? When you press Run, the main method is called. The main method has one statement (System.out...)
which displays "Hello Kilobolt!"

Press Ctrl + Shift + F. This auto-formats your code! In Eclipse

More on Variables:
We will be talking about variables in this lesson.
Refer to the phone pseudo-class that I created as an example:
The three fields (also called variables) that I've created are: an integer variable called weight, a boolean variable called turnedOn, and a String object called color.
There are four kinds of variables (also called fields. Remember! Variables = Fields!)

First, recall that Classes are blueprints for creating objects. Every time you create an object with this class, you are instantiating (creating an instance, or copy, of) this class. In other words, if you were to use the Phone class to create Phone objects, every time you created a new Phone object, you would have a new instance of the Phone class.

With each of these instances, variables that are defined in the class are also created. So each of these Phone instances will now have the weight, turnedOn, and String fields. When you make adjustments to a specific phone by, for example, adding 1 to weight, IT WILL ONLY AFFECT THAT PHONE. The other phone's weights are not affected. This means that each of these Phone objects have their own sets of fields (variables) that are independent from each other.

This is because the variables (fields) are...

1. Instance variables. When a variable is declared without the keyword "static" (i.e. "int weight = 0" rather than "static int weight = 0"), you are creating instance variables, which have unique values for each instance of the Object that they belong to.

What if you wanted to be able to change the values of these variables (again, fields) and affect every single Phone object that you created?

Then you create what we call...

2. Class variables. Any time that you declare a variable with the keyword "static" ("static int weight = 0"), you are basically saying that there will only be a single copy of this variable even if there are multiple Phone objects.


Have a look at the following example. (No need to write it yourself).
It will (hopefully) clear some things up. 
Pretend that we live in a world where you can make real life changes happen with Java.

Let's say Samsung has created 10 Android Phones using the AndroidPhone class above.
The next day, 10 users purchase these phones. We will label them phoneOne, phoneTwo, phoneThree, and so on.

When (if ever) Samsung releases an update, they would want all 10 of these devices to get the update together (I know this isn't a very realistic scenario, just pretend)!

So they would use Eclipse to say: 
(Note: If you take the equal sign too mathematically, it will confuse you. So, whenever you give a value to a variable, try and interpret it like this:
"versionNumber is TAKES THE VALUE OF 2.3." It will make it easier to conceptualize).

Recall that we created a static double (decimal variables) called versionNumber. This means that when you change the value of versionNumber once, it will affect every instance of the AndroidPhone class, meaning that all 10 AndroidPhones will receive the update immediately!

It makes sense to create a static variable for the versionNumber, but it does not make sense to create a static variable for the power! You don't want the user to be able to turn off other people's phones - you want each phone to have its own "turnedOn" boolean (True/False variables).

How, then, do you select which phone will turn on or off?
It's rather simple!

Remember that we labeled each of these phones (phoneOne, phoneTwo, etc). 
Now the final variable, "final String color = "blue";
String means text, and we are creating a color variable with the value of "blue" (quotes indicate literals. no quotes would give color the value of a variable called blue).

The color of these 10 AndroidPhones will never change (ignore spraypaint and cases). So, we just indicate that they are "final."

In case you forgot (or skipped) how we got into the discussion of static, non-static, and final variables, we were talking about the four types of variables in Java.

Moving on to the third type of variable!
We've been creating variables that belonged to the class as a whole. Now we will talk about...

3. Local Variables. If you create a variable within a method, it will only belong to that method (and go away when that method is finished). If you try to invoke that variable by name in other methods, Eclipse will happily and correctly inform you that the variable doesn't exist!

Example: 
There are three variables (NOT TWO) in this class.
1. The class variable called pi.
2. The local variable called hello in the main method.
3. The local variable called hello in the secondaryMethod.

REMEMBER:
When you declare and initialize a variable in a method, that variable will only belong to that method!

Let us finish with the discussion of the final type of variable:

4. Parameters. It is possible to use a local variable in multiple methods. This is how: 
Whenever you invoke a method, you use the "methodName();" statement.
If this method requires a parameter, the code will not successfully run (it will give you errors for that method).

The secondaryMethod requires a "double (decimal number)" to proceed. So you must pass in a double when you invoke the method... 
What this does (when you invoke secondaryMethod from the main method):

It takes the hello double from the main method and "sends it over" to the secondaryMethod, which labels it as a LOCAL VARIABLE called hello. So there are TWO hello variables involved, just like before. NOT ONE.

What does this mean?
Main method's hello will have a value of 5.14.
Secondary method's hello will have a value of 10.14.
Confused? Read the last few paragraphs a few more times, and then comment below.
__________________

Just to clear things up regarding methods and invocation.

In Java, the code will typically be read from top to bottom.
As the programmer, you are basically doing one of two things:

1. Setting up things to be invoked.
2. Invoking (calling) things.

When you create a new method, let's say it's named methodName, it will be ignored until you explicitly call it into action by writing:
methodName();

You can see an example of this if you compare the examples for Local Variables and Parameters. In the Local Variables example, I setup the secondaryMethod() but I never call it to happen. So nothing inside it actually gets
reached when you press Play. However in the Parameters example, I state: secondaryMethod(hello);. This calls the secondaryMethod that I have setup, so everything inside will be reached and ran.

The only exception is the main method, because it is IMPLICITLY called when you press Play in Eclipse.

You can create as many methods as you want. They are there for your benefit: to group and organize your statements, and to make these statements easily accessible without re-writing each line of code. 

Comments

Popular posts from this blog

Login and Registration Example in JSP with Session

Those who want to start with jsp and MySQL, this is an excellent example for themselves. Here you can learn how to insert data to MySQL using JSP. Also you can learn about session handling in jsp. 1 2 3 4 5 6 7 8 9 10 CREATE TABLE `members` (    `id` int (10) unsigned NOT NULL auto_increment,    `first_name` varchar (45) NOT NULL ,    `last_name` varchar (45) NOT NULL ,    `email` varchar (45) NOT NULL ,    `uname` varchar (45) NOT NULL ,    `pass` varchar (45) NOT NULL ,    `regdate` date NOT NULL ,    PRIMARY KEY   (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; index.jsp 1 2 3 4 5 6 ...

Timer funcitons in JavaScript: Reminder Script

Timers are used in web pages and we will discuss how to setup one and how to use one with an example. The function setTimeout() in function is used and here is its general syntax. mytime = setTimeout(expression, msec); mytime  is the identifier used to identify the current timeout function.  expression  is the statement that is to be executed after the specified time has ticked off.  msec  is the duration of time in milliseconds after which the expression will be executed.  You can see by using setTimeout function we can execute any function or object after a set of time. For example if msec is set 5000 then the expression will be executed after 5 seconds or 5000 milliseconds.  We will try one example where we will have four period buttons and each button will set a different time for another function to execute and display a alert button. We will call it as a reminder script and we will get one alert box based on the period button we click...

Binary Addition

/* File Name : BinAdd.java */    import java.util.*; public class BinAdd    {  public static String addBit(String a, String b, String c)  { String r=""; if(a.equals("1") && b.equals("0") || a.equals("0") && b.equals("1")) { if( c.equals("0")) r="1"; else { r="0"; c="1"; } } else if( a.equals("0") && b.equals("0") ) { if(c.equals("0")) r="0"; else r="1"; } else if( a.equals("1") && b.equals("1") ) { if(c.equals("0")){ r="0"; c="1"; } else { r="1"; c="1"; } } return c+r; }   public static String add(String a, String b)   { String r=""; int len=a.length(); String carry="0"; for(int i=len-1;i...

Real time changing Clock showing date and time

We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.  We have seen in our  date object example how to display current date and time   where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using  setTimeout function . This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.  Here is the demo of this script and code is given below that.  Sat Apr 23 2016 08:27:22 GMT+0530 (IST)   Here is the code <html> <head> <title>(Type a title for your page here)</title> <script type="text/javascript...