Java Classes

0

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

Abstract methods & Interfaces

0

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

0

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

0

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

0

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

0

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

0

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.

test

0
  • Language processing:
    • space for parameters and local variables is created internally using a stack.
    • compiler’s syntax check for matching braces is implemented by using stack.
    • support for recursion

Implementation

In the standard library of classes, the data type stack is an adapter class, meaning that a stack is built on top of other data structures. The underlying structure for a stack could be an array, a vector, an ArrayList, a linked list, or any other collection. Regardless of the type of the underlying data structure, a Stack must implement the same functionality. This is achieved by providing a unique interface:

public interface StackInterface<AnyType>
{
   public void push(AnyType e);

   public AnyType pop();

   public AnyType peek();

   public boolean isEmpty();
}

The following picture demonstrates the idea of implementation by composition.

 

Another implementation requirement (in addition to the above interface) is that all stack operations must run in constant time O(1). Constant time means that there is some constant k such that an operation takes k nanoseconds of computational time regardless of the stack size.

 

Array-based implementation

In an array-based implementation we maintain the following fields: an array A of a default size (≥ 1), the variable top that refers to the top element in the stack and the capacity that refers to the array size. The variable top changes from -1 to capacity - 1. We say that a stack is empty when top = -1, and the stack

NFS Server

0

Network File System (NFS)

  •  A Network File System (NFS) allows remote hosts to mount file systems over a network and interact with those file systems as though they are mounted locally. This enables system administrators to consolidate resources onto centralized servers on the network.
  • All versions of NFS can use Transmission Control Protocol (TCP) running over an IP network, with NFSv4 requiring it. NFSv2 and NFSv3 can use the User Datagram Protocol (UDP) running over an IP network to provide a stateless network connection between the client and server.
  • The NFS server sends the client a file handle after the client is authorized to access the shared volume. This file handle is an opaque object stored on the server’s side and is passed along with RPC requests from the client. The NFS server can be restarted without affecting the clients and the cookie remains intact. However, because UDP is stateless, if the server goes down unexpectedly, UDP clients continue to saturate the network with requests for the server. For this reason, TCP is the preferred protocol when connecting to an NFS server.
  • After the client is granted access by TCP wrappers, the NFS server refers to its configuration file,/etc/exports, to determine whether the client is allowed to access any of the exported file systems. Once access is granted, all file and directory operations are available to the user.

Required Services

 Red Hat Enterprise Linux uses a combination of kernel-level support and daemon processes to provide NFS file sharing. All NFS versions rely on Remote Procedure Calls (RPC) between clients and servers. RPC services under Linux are controlled by the portmap service. To share or mount NFS file systems, the following services work together, depending on which version of NFS is implemented:
  • nfs — (/sbin/service nfs start) starts the NFS server and the appropriate RPC processes to service requests for shared NFS file systems.
  • nfslock — (/sbin/service nfslock start) is a mandatory service that starts the appropriate RPC processes to allow NFS clients to lock files on the server.
  • portmap — accepts port reservations from local RPC services. These ports are then made available (or advertised) so the corresponding remote RPC services access them. portmap responds to requests for RPC services and sets up connections to the requested RPC service. This is not used with NFSv4.

The general syntax for the line in /etc/fstab is as follows:

server:/usr/local/pub /pub nfs rsize=8192,wsize=8192,timeo=14,intr

The mount point /pub must exist on the client machine before this command can be executed. After adding this line to /etc/fstab on the client system, type the command mount /pub at a shell prompt, and the mount point /pub is mounted from the server.

The /etc/fstab file is referenced by the netfs service at boot time, so lines referencing NFS shares have the same effect as manually typing the mount command during the boot process.

A sample /etc/fstab line to mount an NFS export looks like the following example:

<server>:</remote/export> </local/directory> <nfs-type> <options> 0 0

Google Interview Questions

0
Google Interview Questions: Software Engineer
  1. Why are manhole covers round?
  2. What is the difference between a mutex and a semaphore? Which one would you use to protect access to an increment operation?
  3. A man pushed his car to a hotel and lost his fortune. What happened?
  4. Explain the significance of “dead beef”.
  5. Write a C program which measures the the speed of a context switch on a UNIX/Linux system.
  6. Given a function which produces a random integer in the range 1 to 5, write a function which produces a random integer in the range 1 to 7.
  7. Describe the algorithm for a depth-first graph traversal.
  8. Design a class library for writing card games.
  9. You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
  10. How are cookies passed in the HTTP protocol?
  11. Design the SQL database tables for a car rental database.
  12. Write a regular expression which matches a email address.
  13. Write a function f(a, b) which takes two character string arguments and returns a string containing only the characters found in both strings in the order of a. Write a version which is order N-squared and one which is order N.
  14. You are given a the source to a application which is crashing when run. After running it 10 times in a debugger, you find it never crashes in the same place. The application is single threaded, and uses only the C standard library. What programming errors could be causing this crash? How would you test each one?
  15. Explain how congestion control works in the TCP protocol.
  16. In Java, what is the difference between final, finally, and finalize?
  17. What is multithreaded programming? What is a deadlock?
  18. Write a function (with helper functions if needed) called to Excel that takes an excel column value (A,B,C,D…AA,AB,AC,… AAA..) and returns a corresponding integer value (A=1,B=2,… AA=26..).
  19. You have a stream of infinite queries (ie: real time Google search queries that people are entering). Describe how you would go about finding a good estimate of 1000 samples from this never ending set of data and then write code for it.
  20. Tree search algorithms. Write BFS and DFS code, explain run time and space requirements. Modify the code to handle trees with weighted edges and loops with BFS and DFS, make the code print out path to goal state.
  21. You are given a list of numbers. When you reach the end of the list you will come back to the beginning of the list (a circular list). Write the most efficient algorithm to find the minimum # in this list. Find any given # in the list. The numbers in the list are always increasing but you don’t know where the circular list begins, ie: 38, 40, 55, 89, 6, 13, 20, 23, 36.
  22. Describe the data structure that is used to manage memory. (stack)
  23. What’s the difference between local and global variables?
  24. If you have 1 million integers, how would you sort them efficiently? (modify a specific sorting algorithm to solve this)
  25. In Java, what is the difference between static, final, and const. (if you don’t know Java they will ask something similar for C or C++).
  26. Talk about your class projects or work projects (pick something easy)… then describe how you could make them more efficient (in terms of algorithms).
  27. Suppose you have an NxN matrix of positive and negative integers. Write some code that finds the sub-matrix with the maximum sum of its elements.
  28. Write some code to reverse a string.
  29. Implement division (without using the divide operator, obviously).
  30. Write some code to find all permutations of the letters in a particular string.
  31. What method would you use to look up a word in a dictionary?
  32. Imagine you have a closet full of shirts. It’s very hard to find a shirt. So what can you do to organize your shirts for easy retrieval?
  33. You have eight balls all of the same size. 7 of them weigh the same, and one of them weighs slightly more. How can you fine the ball that is heavier by using a balance and only two weighings?
  34. What is the C-language command for opening a connection with a foreign host over the internet?
  35. Design and describe a system/application that will most efficiently produce a report of the top 1 million Google search requests. These are the particulars: 1) You are given 12 servers to work with. They are all dual-processor machines with 4Gb of RAM, 4x400GB hard drives and networked together.(Basically, nothing more than high-end PC’s) 2) The log data has already been cleaned for you. It consists of 100 Billion log lines, broken down into 12 320 GB files of 40-byte search terms per line. 3) You can use only custom written applications or available free open-source software.
  36. There is an array A[N] of N numbers. You have to compose an array Output[N] such that Output[i] will be equal to multiplication of all the elements of A[N] except A[i]. For example Output[0] will be multiplication of A[1] to A[N-1] and Output[1] will be multiplication of A[0] and from A[2] to A[N-1]. Solve it without division operator and in O(n).
  37. There is a linked list of numbers of length N. N is very large and you don’t know N. You have to write a function that will return k random numbers from the list. Numbers should be completely random. Hint: 1. Use random function rand() (returns a number between 0 and 1) and irand() (return either 0 or 1) 2. It should be done in O(n).
  38. Find or determine non existence of a number in a sorted list of N numbers where the numbers range over M, M>> N and N large enough to span multiple disks. Algorithm to beat O(log n) bonus points for constant time algorithm.
  39. You are given a game of Tic Tac Toe. You have to write a function in which you pass the whole game and name of a player. The function will return whether the player has won the game or not. First you to decide which data structure you will use for the game. You need to tell the algorithm first and then need to write the code. Note: Some position may be blank in the game। So your data structure should consider this condition also.
  40. You are given an array [a1 To an] and we have to construct another array [b1 To bn] where bi = a1*a2*…*an/ai. you are allowed to use only constant space and the time complexity is O(n). No divisions are allowed.
  41. How do you put a Binary Search Tree in an array in a efficient manner. Hint :: If the node is stored at the ith position and its children are at 2i and 2i+1(I mean level order wise)Its not the most efficient way.
  42. How do you find out the fifth maximum element in an Binary Search Tree in efficient manner. Note: You should not use use any extra space. i.e sorting Binary Search Tree and storing the results in an array and listing out the fifth element.
  43. Given a Data Structure having first n integers and next n chars. A = i1 i2 i3 … iN c1 c2 c3 … cN.Write an in-place algorithm to rearrange the elements of the array ass A = i1 c1 i2 c2 … in cn
  44. Given two sequences of items, find the items whose absolute number increases or decreases the most when comparing one sequence with the other by reading the sequence only once.
  45. Given That One of the strings is very very long , and the other one could be of various sizes. Windowing will result in O(N+M) solution but could it be better? May be NlogM or even better?
  46. How many lines can be drawn in a 2D plane such that they are equidistant from 3 non-collinear points?
  47. Let’s say you have to construct Google maps from scratch and guide a person standing on Gateway of India (Mumbai) to India Gate(Delhi). How do you do the same?
  48. Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
  49. Given a binary tree, programmatically you need to prove it is a binary search tree.
  50. You are given a small sorted list of numbers, and a very very long sorted list of numbers – so long that it had to be put on a disk in different blocks. How would you find those short list numbers in the bigger one?
  51. Suppose you have given N companies, and we want to eventually merge them into one big company. How many ways are theres to merge?
  52. Given a file of 4 billion 32-bit integers, how to find one that appears at least twice?
  53. Write a program for displaying the ten most frequent words in a file such that your program should be efficient in all complexity measures.
  54. Design a stack. We want to push, pop, and also, retrieve the minimum element in constant time.
  55. Given a set of coin denominators, find the minimum number of coins to give a certain amount of change.
  56. Given an array, i) find the longest continuous increasing subsequence. ii) find the longest increasing subsequence.
  57. Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  58. Write a function to find the middle node of a single link list.
  59. Given two binary trees, write a compare function to check if they are equal or not. Being equal means that they have the same value and same structure.
  60. Implement put/get methods of a fixed size cache with LRU replacement algorithm.
  61. You are given with three sorted arrays ( in ascending order), you are required to find a triplet ( one element from each array) such that distance is minimum.
  62. Distance is defined like this : If a[i], b[j] and c[k] are three elements then distance=max(abs(a[i]-b[j]),abs(a[i]-c[k]),abs(b[j]-c[k]))” Please give a solution in O(n) time complexity
  63. How does C++ deal with constructors and deconstructors of a class and its child class?
  64. Write a function that flips the bits inside a byte (either in C++ or Java). Write an algorithm that take a list of n words, and an integer m, and retrieves the mth most frequent word in that list.
  65. What’s 2 to the power of 64?
  66. Given that you have one string of length N and M small strings of length L. How do you efficiently find the occurrence of each small string in the larger one?
  67. How do you find out the fifth maximum element in an Binary Search Tree in efficient manner.
  68. Suppose we have N companies, and we want to eventually merge them into one big company. How many ways are there to merge?
  69. There is linked list of millions of node and you do not know the length of it. Write a function which will return a random number from the list.
  70. You need to check that your friend, Bob, has your correct phone number, but you cannot ask him directly. You must write a the question on a card which and give it to Eve who will take the card to Bob and return the answer to you. What must you write on the card, besides the question, to ensure Bob can encode the message so that Eve cannot read your phone number?
  71. How long it would take to sort 1 trillion numbers? Come up with a good estimate.
  72. Order the functions in order of their asymptotic performance: 1) 2^n 2) n^100 3) n! 4) n^n
  73. There are some data represented by(x,y,z). Now we want to find the Kth least data. We say (x1, y1, z1) > (x2, y2, z2) when value(x1, y1, z1) > value(x2, y2, z2) where value(x,y,z) = (2^x)*(3^y)*(5^z). Now we can not get it by calculating value(x,y,z) or through other indirect calculations as lg(value(x,y,z)). How to solve it?
  74. How many degrees are there in the angle between the hour and minute hands of a clock when the time is a quarter past three?
  75. Given an array whose elements are sorted, return the index of a the first occurrence of a specific integer. Do this in sub-linear time. I.e. do not just go through each element searching for that element.
  76. Given two linked lists, return the intersection of the two lists: i.e. return a list containing only the elements that occur in both of the input lists.
  77. What’s the difference between a hashtable and a hashmap?
  78. If a person dials a sequence of numbers on the telephone, what possible words/strings can be formed from the letters associated with those numbers?
  79. How would you reverse the image on an n by n matrix where each pixel is represented by a bit?
  80. Create a fast cached storage mechanism that, given a limitation on the amount of cache memory, will ensure that only the least recently used items are discarded when the cache memory is reached when inserting a new item. It supports 2 functions: String get(T t) and void put(String k, T t).
  81. Create a cost model that allows Google to make purchasing decisions on to compare the cost of purchasing more RAM memory for their servers vs. buying more disk space.
  82. Design an algorithm to play a game of Frogger and then code the solution. The object of the game is to direct a frog to avoid cars while crossing a busy road. You may represent a road lane via an array. Generalize the solution for an N-lane road.
  83. What sort would you use if you had a large data set on disk and a small amount of ram to work with?
  84. What sort would you use if you required tight max time bounds and wanted highly regular performance.
  85. How would you store 1 million phone numbers?
  86. Design a 2D dungeon crawling game. It must allow for various items in the maze – walls, objects, and computer-controlled characters. (The focus was on the class structures, and how to optimize the experience for the user as s/he travels through the dungeon.)
  87. What is the size of the C structure below on a 32-bit system? On a 64-bit?