Home » Java

Category Archives: Java

Java Classes

Java Classes

C++ vs. Java

Java is similar to C++ in many ways. The first is the syntax of the language. Semicolons are required to end lines just like C++. There are also many similar structures such as arrays, classes and functions (or methods as they are called in java).

There are differences however. Most noticeably, java is strictly an Object Oriented Language, meaning it is made up entirely of classes (objects). There are no exceptions to this in this language.

Another big difference between the two is that there is no pointers in java! Everything is done “behind closed doors” when dealing with addressing and arrays.

Let’s continue on and see how to define a simple program.

Classes

Since java is made up entirely of classes, all programs will be made up of classes. The overall rule is that whatever your class name is, the name MUST MATCH YOUR FILENAME. If not, when compiling it, there will be an error.

Here is the simplest program that can be made:

public class Hello{
   public static void main(String args[]){
      System.out.println("Hello!");
   }
}

Wow! Short and sweet. It will print out a “Hello” message on screen. In this program of just 3 lines, so much has happened. Let’s observe.

First, there are no include statements like C++. In java, a program can be written without anything in the head of the document.

Second, the “public class Hello” is of the following format:

keyword class name

where keyword is either public, private or protected, and name is the name of the class. The keyword public allows any java class to view the data (hence being public). There is a rule though; the class with the main method that will get the program running MUST be declared public. To declare a class private is a silly thing to do but not invalid either. Private is just the opposite of public in the sense that you cannot use it directly between classes. Variables or objects declared private can only be used within their own class.

Thirdly, the main method declaration is always of that heading. This is not something you can change in a program. The main method will take a single argument, a String array called args[] which will take, as it’s elements in the array, any command-line argument you give it. The array is of the object type String (see tutorial 3).

Finally, the System.out.println() statement will be used for output. The println() means “print line”, as this will print a string(s) and go to the next line. This is like the C++ “endl”. To be more general, any output statement is contained in the System.out set of classes. There is also a System.out.print() that will not print a new line.

Compiling programs

Now that we have our first program in java, we need to know how to compile it. The first thing is to know that java is run on a virtual machine. A virtual machine is universal to a computer and can run code for a specific task. or programming language.

Here is how to compile the java program:

javac name.java

where javac is the java compiler itself, and name is the appropriate name of the program ( here Arguments). By pressing the enter key, the program will compile and will translate into virtual machine instructions.

Once successfully compiled, run the following command in the same directory where you compiled the program.

Command-line arguments

As mentioned before, java can take command line arguments. Each of the arguments will be separated by a single space when entered on the command line. There is another rule; each argument is treated AS A STRING. Say that you need a number as an argument. Then, the number must be parsed to that type. The example below will demonstrate command line arguments.

Example 1:
Command line arguments

The purpose of this program is to demonstrate the use of command line arguments. Here, the user will enter their full name (first and last) followed by their age.

public class Arguments{
   public static void main(String args[]){

	if(args.length < 3){
		System.out.println("Too few arguments.");
		System.out.println("Enter the first name,");
		System.out.println("Then the last name,");
		System.out.println("Then the age.");
		System.exit(1);
	}

	//correct input so preform the operations:

	String name = args[0] + " " + args[1];
	int age = Integer.parseInt(args[2]);

	System.out.println("Hello " + name + ".  You are "
		+ age + " years old!");

   } //main
} //class

Again, a short program but a lot happening. Let’s look at some new things introduced here.

First, the if statement will check if the amount of arguments in the array is less than the number required. If true, then the series of instructions will be printed out, then the program will terminate. The exit statement is again contained in the System class. If the statement is false, it is implied that there are the correct number of arguments so proceed with the program.

Next, there are two variables at work here, a string variable called name and an integer variable called age. Let’s look at the name variable. Notice that it will concatenate both args[0] and args[1] in addition to a space, by the + operator. In java, the + operator functions as the String concatenator as well as the arithmetic operator.

Next, the age variable will need to be parsed to an integer type. The third argument args[2] will contain the number for the age. As mentioned earlier, the parse method of a class will convert the argument to that type. Most numeric classes have this (Double, Float, Integer etc…). Notice that the name of the class begins with an uppercase letter. Notice the same for the String class. That is a feature of java in the sense of class names. These are called wrapper classes.

Finally, the program will output a simple message to the screen displaying the full name and age of the user.

You can run the above program with the following command line:

java Arguments John Doe 22

The output from that action will be: Hello John Doe. You are 22 years old!

Example 2:
Command line arguments II

The purpose of this program is to demonstrate the use of command line arguments. Here, the user will enter their full name (first and last) followed by their age.

public class Arguments2{
   public static void main(String args[]){

	if(args.length < 3){
		System.out.println("Too few arguments.");
		System.out.println("Enter 3 numbers to see,");
		System.out.println("Their average.");
		System.exit(1);
	}

	//correct input so preform the operations:
        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
	int n3 = Integer.parseInt(args[2]);

        double avg = ((double) (n1+n2+n3))/3.0;
	System.out.println("The average is: " + avg);

   }
}

You can run the above program with the following command line:

java Arguments 21 22 23

The output from that action will be: The average is: 22

Advertisements

Abstract methods & Interfaces

Abstract methods & Interfaces

Interfaces

When dealing with an abstract class, we sometimes see what’s called an interface. An interface is a definition of all abstract methods however, unlike abstract methods within an abstract class, these methods defined in the interface can be used in any other class, regardless of being abstract or not.

Here is how to define an interface:

interface Name {
       //methods here
}

The methods that are defined in the interface DO NOT need the abstract keyword with them.

In order for a class to use an interface, it must use the keyword implements in it’s class header. Here is the definition:

public class Name implements interfaceName {
	//code here
}

where Name is the name of the class and interfaceName is the name of the interface you will be implementing.

By default, all methods in an interface contain the keywords abstract public before each definition so these are not needed. You also cannot make the methods private or protected as this is not allowed in Java interfaces.

Let’s look back at the previous chapter’s example of the Food stores. Here is the full example using an interface:

Example 1:
Simple Interface example

public interface Slogan {
	String slogan();
}

public abstract class FoodStore implements Slogan{
	private String name;
	private int opened;

	public FoodStore(String n, int o){
		if(n == null)
	 throw new IllegalArgumentException("No name given!");
		else if(o < 0 || o > 2010)
	 throw new IllegalArgumentException("Bad opening!");
		else{
		   name = n;
		   opened = o;
		}
	} //constructor

	public String toString(){
	  return("Name: " + name + "nOpened: " + opened);
	}
} //class

public class BestFoods extends FoodStore {
	private String slogan = "The best food anywhere!";

	public BestFoods(String n, int o){
		super(n,o);
	}

  //implements the slogan() method from the interface:
	public String slogan(){
		return slogan;
	}
} //class

public class OldFoods extends FoodStore{
   private String slogan = "The oldest food store around!";

    public OldFoods(String n, int o){
		super(n,o);
	}

        //implements the slogan() method:
	public String slogan(){
		return slogan;
	}
}

public class WholesomeFoods extends FoodStore {
	private String slogan = "Mmmmmm, delicious!";

	public WholesomeFoods(String n, int o){
		super(n,o);
	}

        //implements the slogan() method:
	public String slogan(){
		return slogan;
	}
}

public class Stores{
	public static void main(String args[]){
		FoodStore fs[] = new FoodStore[3];

	fs[0] = new BestFoods("Best", 1956);
	fs[1] = new OldFoods("Old", 1944);
	fs[2] = new WholesomeFoods("Whole", 1987);

	for(int i = 0; i < 3; i++)
        System.out.println(fs[i] + "nSlogan: "
         + fs[i].slogan() + "n");

	} //main
} //class

Since each subclass is inheriting all methods from the super class FoodStore, it is not necessary to place the implements Slogan in each subclass. If you did that, you would get an error citing that the method from the interface is undefined and the super class must implement the interface.

The output is also the same as the last chapter. All we did was change the abstract method in the class to an interface.

Interface constants

Constants can be placed in an interface. This is perfectly legal in Java.

Here is an interface example that uses a constant:

public interface Calendar {
	int MONTHS = 12;
	int DAYS = 365;
}

public class Year implements Calendar{
	public static void main(String args[]){
		int m = 12;
		int d = 366;
	if(d == DAYS)
            System.out.println("Equal days!");
	if(m == MONTHS)
            System.out.println("Equal months!");

        } //main
} //class

The output would simply be “Equal months!”

Java Random numbers

Java Random numbers

In Java, as well as any other programming language, you can generate a random number or sequence of random numbers. Here, it involves the use of one library of Java; the util library.

You need to import the library in order to use the random number feature:

import java.util.Random;

Random Methods

Here is how to create a new Random object in Java:

Random name = new Random();

Where name is an appropriate name for the Random object. Once declared, you can begin to generate a random number by making use of an appropriate method. Here is a short list that you will make the most use of when dealing with random numbers:

int nextInt()

This method will return a pseudorandom integer. This will cover all 232 possibilities of integers (both positive and negative).

int nextInt(int range)

This method will return a pseudorandom integer in the range: 0 <= x < range. Notice that the range is not included and 0 is. So say that you wanted to go from 1 to 10. You need to avoid 0 in that mix and you need to include the topmost value range. This is a good way of doing that:

int num = r.nextInt(10) + 1;

So even if 9 is generated, it will add 1 and make it 10 and similarly with 0, it will make it 1.

double nextDouble()
float nextFloat()

This will generate numbers in the range 0.0 to 1.0 inclusive.

long nextLong()

This will generate random numbers in the range 2^64 based on the long type.

boolean nextBoolean()

This will generate either true or false respectively.

Here is an example program that will fill an array with random numbers:

Example 1:
Random Arrays

import java.util.Random;
public class ArrayRandom{
	public static void main(String args[]){
		Random r = new Random();
		int arr[] = new int[20];

		for(int i = 0; i < 20; i++){
		   //random numbers from 1 to 10:
		   arr[i] = r.nextInt(10) + 1;
		}

		for(int i = 0; i < 20; i++){
		   System.out.print(arr[i] + " ");
		}
	} //main
} //class

The program simply places random numbers from 1 to 10 inside the array called arr. It will output the values in the array in the second program. This is a simple program to see how random numbers work. Run the program multiple times to see the different numbers appear.

Example 2:
Random Array’s 2

import java.util.Random;
public class ArrayRandom2{
	public static void main(String args[]){
		Random r = new Random();
		int arr[] = new int[25];

		for(int i = 0; i < 1000; i++){
		   //random numbers from 1 to 10:
		   arr[r.nextInt(25)] ++;
		}

		for(int i = 0; i < 25; i++){
		   System.out.println(i + " was generated " +
		 		  arr[i] + " times.");
		}
	} //main
} //class

This program will keep track of how many times a random number was drawn. This will increment the appropriate place in the array. The generated number itself will be the index of the array. One possible output can be:

0 was generated: 33 times.
1 was generated: 33 times.
2 was generated: 43 times.
3 was generated: 44 times.
4 was generated: 45 times.
5 was generated: 39 times.
6 was generated: 44 times.
7 was generated: 40 times.
8 was generated: 41 times.
9 was generated: 43 times.
10 was generated: 37 times.
11 was generated: 38 times.
12 was generated: 42 times.
13 was generated: 37 times.
14 was generated: 38 times.
15 was generated: 42 times.
16 was generated: 30 times.
17 was generated: 37 times.
18 was generated: 42 times.
19 was generated: 38 times.
20 was generated: 33 times.
21 was generated: 52 times.
22 was generated: 45 times.
23 was generated: 51 times.
24 was generated: 33 times.

The output will be different each time the program is run.

Example 3:
Random Stars

import java.util.Random;
public class RandomStars{
	public static void main(String args[]){
		Random r = new Random();
		int num = 0;

	      for(int i = 0; i < 25; i++){
	         //random numbers from 0 to 15:
	         num = r.nextInt(16);
	         for(int j = 0; j < num; j++)
	    	      System.out.print("*");
	         System.out.println();
	      }
	} //main
} //class

The program will simply output rows of stars to the screen 25 times. However, you may not see 25 rows since the inner loop will strictly be less than the generated number. If the random number is 0, the loop will not run and leave a blank row.

One possible output is this:

****
**

*
********
****
**
************
*******

***

*******
****

*********
*****
*****
***

********
*******
****
**

Another possible output is this:

*********
****
******
**
******
***
*********
********
********
****
***
************
**
*******
********
***
*************
*****
*********
***
******
**********
********
******
**

Abstract classes & methods

Abstract classes & methods

When dealing with inheritance, we have seen the relationship between super classes and subclasses. However, this was all done on a public level.

An abstract, by its textbook definition, is a rough sketch of something. By it’s application in Java, an abstract class is a class that is a sketch of something to come. It is a class that cannot be directly constructed. This is a common error among Java programmers.

Abstract classes

In order for a class to be declared abstract, you must use the abstract keyword:

public abstract class Name {
	//code
}

As an example, let’s say that you are thinking of running an electronic store. We know that there can be CD’s, DVD’s, VHS tapes or even, for those oldies, Records. All of these are of a “super” type called Media. So for Java, the Media class can be declared abstract while the other classes can be subclasses of Media. Here is a diagram to show this:

    Media
/    |
CD   DVD   VHS

where Media would be abstract (in addition to the super class) and the other classes would extend Media.

Now let’s see that sketch above implemented in some code. Try to follow the program and compute the output before looking:

Example 1:
Abstract classes example

public abstract class MediaItem{

private String title;  //global title variable
private int year;  //global year variable
private int quantity;  //global quantity variable

public MediaItem(String t, int yr, int q){

   if(t == null)
   throw new IllegalArgumentException("No title given");
      else if(yr < 0 || yr > 2010)
    throw new IllegalArgumentException("Bad year");
    else if(q < 0)
       throw new IllegalArgumentException("Bad quantity");
           else{
                title = t;
		year = yr;
		quantity = q;
           }
        } //constructor

    public String toString(){
       return("Title: " + title
         + "nYear: " + year
	 + "nQuantity: " + quantity);
        } //toString()
} //class

public class CD extends Media{
	public CD(String t, int yr, int q){
		super(t, yr, q);
        } //constructor
} //class

public class DVD extends Media{
	public DVD(String t, int yr, int q){
		super(t, yr, q);
        } //constructor
} //class

public class VHS extends Media{
	public VHS(String t, int yr, int q){
		super(t, yr, q);
        } //constructor
} //class

public class Store{
	public static void main(String args[]){

        Media items[] = new Media[5];

	for(int i = 0; i < 5; i++){
	   try{
	      if(i % 3 == 0)
	  items[i] = new CD("Im a CD", 1993, i*3);
	      else if(i % 3 == 1)
	  items[i] = new DVD("Im a DVD", 1999, i*2);
	      else
        items[i] = new VHS("Im old!", 1987, i*4);
	   }catch(IllegalArgumentException iae){}
	}

	System.out.println("Inventory:n");

	for(int i = 0; i < 5; i++)
            System.out.println("Item: " + items[i] + "n");

        } //main
} //class

The above is an example to show how a class can be declared abstract. Each of the CD, DVD, and VHS classes are subclasses of Media.

In the main method of the class Store, we can declare an array of Media objects. Here we declare it to be of size 5. This is certainly allowed so long as we don’t say:

items[i] = new Media( ... );

By the rules of abstract classes, this is not allowed. The abstract class Media cannot be constructed directly.

Also in the main method of class Store, we include a try/catch block since in the Media constructor, we are throwing an exception if a certain condition is met. This try/catch block is there just for good practice since none of the items in this example are throwing an exception.

The output from the above example is:

Inventory:

Item: Title: Im a CD
Year: 1993
Quantity: 0

Item: Title: Im a DVD
Year: 1999
Quantity: 2

Item: Title: Im old!
Year: 1987
Quantity: 8

Item: Title: Im a CD
Year: 1993
Quantity: 9

Item: Title: Im a DVD
Year: 1999
Quantity: 8

Abstract methods

In Java, a method can be declared abstract. This means that it will not have an implementation. It also means that it MUST appear inside an abstract class.

The method will use the same abstract keyword in it’s title:

abstract identifier type Name();

where identifier can be public, private or protected; type is the return type of the method and Name is the name of the useful name of the method. Notice that there is a semicolon appearing at the end of the method declaration. This is how to denote an abstract method since there is no implementation after it.

Let’s say that you were writing a Java program to keep track of different Food stores in your area. Each food store may have a different slogan. So in many ways, the FoodStore class can be abstract and inside that class, the method called slogan() can be abstract. The method will be implemented in each of the subclasses.

Inheritance

Inheritance

Topics:    What is an array?

Super keyword

This keyword

getName() & getClass()

What is inheritance?

In Java, a class can inherit all methods, instance variables etc… from another by extending it. Java allows the keyword extends when dealing with inheritance. Here is how to extend a class from another:

public class Wheels extends Car{
	//code here
}

where the class Wheels will now be the subclass and the class Car will be the super class. In “human terms” this is true since a wheel is part of a larger being called the car.

super keyword

The keyword super will be used when referring to the super class of an object. This will reference the constructor when used like this for an example:

super( argument(s) )

or if accessing another method:

super.methodName( argument(s) )

What is NOT inherited from the super class is the constructors, since they are strictly used by that class.

this keyword

The keyword this will reference the current class the word appears in. It will allow you to use the classes methods if used like this:

this.methodName();

Let’s see a simple example of some inheritance for an Animal class.

Example 1:
Simple array example

public class Dog extends Animal{
	public Dog(String n, int a){
		super(n,a);
	}
}

public class Cat extends Animal{
	public Cat(String n, int a){
		super(n,a);
	}
	public String toString(){
		return "I am a " + getClass().getName();
	}
}

public class Animal{
  static Animal animals[] = new Animal[5];
  String name = "";
  int age = 0;
  static int ct = 0;

  public Animal(String n, int a){
  name = n;
  age = a;
	}

  public String toString(){
   return "I am a " + getClass().getName() +
        ".  My name is " + name + ".  I am "
            + age + " years old!";
	}

  public static void main(String args[]){

    for(int i = 0; i < 5; i++){
         if(i % 2 == 0){
	    animals[i] = new Cat("Fluffy", i+5);
	      }else{
		   animals[i] = new Dog("Jake", i+3);
		   }
		}
    for(int i = 0; i < 5; i++){
	System.out.println(animals[i]);
		}
	}
} //class

Again, a lot has happened here in just a short program. Lets break it down bit by bit.

First, the main Animal class. What will happen here is an array of Animal objects called animals[] will hold information for 5 Animals that will be created in the main method. Each of those animals are either a Dog or Cat object.

Second, both the Dog and Cat class are the subclass of Animal. The constructor of the Dog class will call the Animal constructor and create each Object. The Cat constructor will do the same. However, in the Cat class, there is a toString method that will OVERRIDE the ANIMAL toString method. This is important for later use.

Finally, the Animal class will create the objects of either Dog or Cat based on an if statement in the first for loop. When the last for loop occurs, the output will be:

I am a Cat
I am a Dog.  My name is Jake.  I am 4 years old!
I am a Cat
I am a Dog.  My name is Jake.  I am 6 years old!
I am a Cat

 

getClass() & getName() method

When referring to classes, there is a method called getClass() that will return the current class it is called in. So in the above example, the keyword this is used to refer directly to the Animal or Cat class but that can be left out.

Inside the getClass() method is another method called getName(). This will return a String representing the name of that class. The previous example shows this in both the Animal and Cat classes in the second example.

When dealing with inheritance, do not be frightened. The first thing to note is what class will be the super class. Then, look for methods that are overridden from the super class. Finally, observe the super class and the main method to trace the output. Inheritance takes practice so please be patient.

Methods & parameters

Methods & parameters

Topics : MethodsIdentifiers

Types of methods

Parameters (arguments)

Overloading methods

Methods

In Java, a method is a block of code that performs a certain task. This is *almost* the same as a C++ function. There are some small differences.

A method can be private, protected, or public and static or non static. The return types can be anything primitive (int, float etc…) or user defined.

Here is how to define a Java method:

identifier type Name( argument(s) ){
    //code here
}

where identifier is either public, private or protected; type is the return type of the function; Name is a useful name of the method and arguments is the parameters to pass to the function ( if any).

Identifiers

As stated, a method can be public, private or protected.

A public method can be seen by any class, anywhere. There are no restrictions regarding public.

A private method can be seen only within the class itself. It cannot be accessed elsewhere.

A protected method is not commonly used but it means that it can be accessed within the class or any of its subclasses.

Types of methods

A method that uses instance variables of that class is called an instance method. This is the default for a method.

A method that uses NO instances variables can be declared static. It must NOT use any of them otherwise there will be a compiler warning. The static methods tend to compute something from arguments of that method instead of using the variables.

Here is a valid static method:

public static double mean(int n1, int n2, int n3){
       int sum = 0;
       double ans = 0.0;

       sum += n1 + n2 + n3;

       ans = sum / 3.0;

       return ans;
}

The above will compute the average of the three integer parameters (see below for description of parameters). Notice that it only uses local variables to the method and only the parameters. If it tried to use any instance variables there will be a warning.

Method parameters (arguments)

A parameter (or argument as we know already), is a variable given to a method. A parameter to a method is also called a formal parameter.

PLEASE NOTE: all parameters that are not of object types are PASSED BY VALUE! All others are PASSED BY REFERENCE (including arrays). This is a common mistake made by Java newcomers.

Let’s see a simple class and a simple instance method:

Example 1:
Simple method

public class SimpleStatic{
	private static int s=3, t=7;

	public static void main(String args[]){
               System.out.println("sum: " + sum(s,t));
	}

	private static int sum(int a, int b){
		return a+b;
	}
}

The above program will be compute the sum of the 2 instance variables. The reason the method is static is because the instance variables are static as well as the method is being called from the static main() method.

Since we know that object types are passed by reference, let’s use an array as an example.

Example 2:
Simple array method

public class SimpleArrayMethod{
	public static void main(String args[]){
		int s[] = new int[5];

		for(int i = 0; i < 5; i++)
			s[i] = i*3;

		int sum = sumArray(s);

                System.out.println("sumArray: " + sum);
	}

	private static int sumArray(int arr[]){
		int sum = 0;

		for(int i = 0; i < arr.length; i++)
			sum += arr[i];

		return sum;
	}
}

Here, we declare an array of size 5 and with the use of a for loop, we assign values to each cell. Then we call the static method sumArray() and pass the entire array to the method. What is returned is the sum of the values in the array.

Now let’s see an example with a String to see, if we change something in the method, if it will also change in the main() or wherever we called it from.

Example 3:
Simple String method

public class SimpleStringMethod{
	static String word1 = "Cats";
	static String word2 = "Dogs";

	public static void main(String args[]){

		System.out.println("Before call:nword1: " +
				word1 + "nword2: " + word2);

		switches(word1,word2);

		System.out.println("nAfter call:nword1: " +
				word1 + "nword2: " + word2);
	}

	private static void switches(String w1, String w2){
		w1 = w2;
		w2 = "Changed!";
	}
}

Here, we wrote a method called switches that takes two String arguments. It is seen that we are changing the values of the words in the method. The words in the main method DO NOT change. Once we attempt to change a variable in a method, we lose the reference to it from the place we called it. Therefore, although it is passed by reference, we do not change the values of the variables.

Here is the output of the following program:

Before call:
word1: Cats
word2: Dogs

After call:
word1: Cats
word2: Dogs

Overloading methods

In Java, many methods are already written for you, such as the equals() method in the String class as an example. If you wish to create your own version of a method that may take different data types as parameters, you can by what’s called overloading.

Say we have a short program as follows:

public class OverloadExample{
	public static void main(String args[]){
	 talk("Hey there!");
	 talk("Hey there my name is John", "John");
	} //main

	public static void talk(String t){
		System.out.println(t);
	}

	public static void talk(String t, String name){
	  System.out.println(name + " said this: " + t);
	}
} //class

Here, we see that there are two methods called talk, both of which return void and are named the same. The only difference is the arguments of these methods. This is allowed in Java. We have now overloaded the talk() method.

BE CAREFUL: It is NOT okay to have two methods with the same name and DIFFERENT return types. This will produce an error in Java. Specifically, it will say “Duplicate method [name(type)] in [class name]”.

Objects

Objects in Java

Topics

Creating Objects

Constructors

Instance variables

Static variables

Creating Objects

In java, an object is a block of memory that will hold code and preform a specific task(s). This is the foundation of a class that was discussed previous.

An object can be initialized (or as it’s said instantiated) with the keyword new. In order for an object to be used, it must be created first.

Here is a general way to define an object:

Method 1:

type name;
This way will declare, but not instantiate the object of
a specific type.  At some point in the program, the name
object would have to be instantiated.

Method 2:

type name = new type();
This is a good way to declare AND instantiate an object.
It still uses the assignment operator ( = ).  This will
then allow the object to be used as it is now active.

Let’s observe method 2 a bit more as this is most common. Similar to a regular variable, this will initialize the object called name by invoking whats called a constructor for that class. A constructor can be thought of as a construction worker for a specific building. Without them, the building cannot be built. The same applies to a class; without a constructor, there is no class that can be used as an object.

Constructors

A constructor must be part of a class if you are going to use it as a type. It can also be thought of as a method that will preform specific actions.

There are rules about constructors. First, the constructor MUST BE PUBLIC. Second, it MUST MATCH THE CLASS NAME EXACTLY. Thirdly, it contains no other keywords such as void, int, boolean etc.

Here is a class that contains a constructor:

public class Example1{

   public Example1(){
      System.out.println("Welcome!");
   }
   public static void main(String args[]){
      Example1 ex1 = new Example1();
   }
}

A small example at that. What this will do is create a new instance of the object Example1. Contained in the constructor is a simple welcome message that will print out “Welcome!” when instantiated.

Instance variables

A class or object can have it’s own variables. In Java, these are called instance variables. By its definition, an instance variable is unique to each instance of the class; so in general, each time a class is “instantiated” with the new operator, there is another variable associated with it.

These variables are declared outside any methods you may have. These variables are declared either public, private or protected. They are global to the class or object they appear in. Let’s see a small example.

Example 1:
Instance variables

public class Variables{

   private int x = 0;

   public Variables(){
      x++;
      System.out.println("Welcome! " + x);
   }
   public static void main(String args[]){
      Variables var1 = new Variables();
   }
}

In this example, the instance variable x is declared private. In addition, it is global to the Variables object.

The program simply prints out “Welcome! 1” when the program starts.

Static variables

Static variables are quite a bit harder to understand. Do not be confused with a static variable from C++. They are very different.

In java, a static variable (also called a class variable), is a variable that is given a fixed block of memory. The static keyword tells the compiler that there is exactly one copy of this variable in existence, no matter how many times the class has been instantiated.

Let’s just think of a real world example. Say you own a car. The car will always have four wheels in the US. So if you made a class in java called Car, a variable called numWheels can be made static since it will be the same for every car.

Let’s see an example of a static variable.

Example 2:
Static variables

public class SVariables{

   private static int x = 0;
   private int y = 3;

   public SVariables(){
      x++;
      y += 5;
      System.out.println(y + " -- Welcome -- " + x);
   }
   public static void main(String args[]){
      SVariables s1 = new SVariables();
      SVariables s1a = new SVariables();
      SVariables s1b = new SVariables();
   }
}

When you run the above program, this is the output:

8 -- Welcome -- 1
8 -- Welcome -- 2
8 -- Welcome -- 3

Here is why the output is this way. With the s1 instance of the object, the value of x is 1 and the value of y is 8, as per the arithmetic operations in the constructor.

The next instance of the object SVariables is s1a. Here, the value of x is 2 BECAUSE OF THE STATIC while the value of y is again 8, BECAUSE OF THE NON-STATIC.

In the final instance of the object SVariables, the x is 2 while the y is 8.