10x Blogs Directory
Showing posts with label Basics. Show all posts
Showing posts with label Basics. Show all posts

Wednesday, April 1, 2009

Polymorphism

lPolymorphism in a Java program
-
  • The ability of a reference variable to change behavior according to what object instance it is holding.
  • This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to.

There are 3 forms of Polymorphism

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
Example:

Given the parent class Person and the subclass Student of the previous examples, we add another subclass of Person which is Employee

lIn Java, we can create a reference that is of type super class to an object of its subclass. For example,
public static main( String[] args ) {
Student studentObject = new Student();
Employee employeeObject = new Employee();
Person ref = studentObject; // Person reference points              // to a Student object
   String name = ref.getName();
}
  • Now suppose we have a getName method in our super class Person, and we override this method in both Student and Employee subclass's
public class Student {
public String getName(){
System.out.println(“Student Name:” + name);
return name;
}
}
public class Employee {
public String getName(){
System.out.println(“Employee Name:” + name);
return name;
}
}

l
  • Going back to our main method, when we try to call the getName method of the reference Person ref, the getName method of the Student object will be called. 
l
  • Now, if we assign ref to an Employee object, the getName method of Employee will be called.

l
  • Another example that illustrates polymorphism is when we try to pass a reference to methods as a parameter
l
  • Suppose we have a static method printInformation that takes in a Person reference as parameter
public static printInformation( Person p ){
       // It will call getName() method of the
       // actual object instance that is passed
       p.getName();
}

  • We can actually pass a reference of type Employee and type Student to the printInformation method as long as it is a subclass of the Person class.

public static main( String[] args )
{
Student studentObject = new Student();
Employee employeeObject = new Employee();
printInformation( studentObject );
printInformation( employeeObject );
}
 

Thursday, March 12, 2009

While-loop

While loop
-is a statement or block of statements that is repeated as long as some condition is satisfied.

while loop has the form:

while( boolean_expression )
{
statement1;
statement2; . . .
}

-The statements inside the while loop are executed as long as the boolean_expression evaluates to true.

Example 1
int x = 0;
while (x<10) { System.out.println(x); x++; }

Example 2
//infinite loop
while(true)
System.out.println(“hello”);

Example 3

//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);

Monday, March 9, 2009

Switch Statements

  • switch
    -allows branching on multiple outcomes.
  • switch statement has the form:
switch( switch_expression )
{
case case_selector1: statement1;
// statement2;
//block 1 break;
case case_selector2: statement1;
// statement2;
//block 2 break;
default: statement1;
// statement2;
//block n
}
  • where,
    -switch_expression
    lis an integer or character expression
    -case_selector1, case_selector2 and so on,
    lare unique integer or character constants.
  • When a switch is encountered,
    -Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression.
    -The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure.
    -If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional.
  • NOTE:
    -Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly braces.
    -When a case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed.
    -To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.

Coding Guidelines

  • Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors.
  • An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique.

Thursday, March 5, 2009

Introduction to Arrays

  • Suppose we have here three variables of type int with different identifiers for each variable.
int number1;
int number2;
int number3;

number1 = 1;
number2 = 2;
number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose.
  • In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array.
  • An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.

Declaration ofan Array

  • To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name.
  • For example,
int []ages;
or
int ages[];


Instantiation of an Array

  • After declaring, we must create the array and specify its length with a constructor statement.
  • Definitions:
    -Instantiation
  • In Java, this means creation
    -Constructor
  • In order to instantiate an object, we need to use a constructor for this. A constructor is a method that is called to create a certain object.
  • We will cover more about instantiating objects and constructors later.
  • To instantiate (or create) an array, write the new keyword, followed by the square brackets containing the number of elements you want the array to have.
  • For example,

//declaration int ages[];

instantiate objectages = new int[100];

or, can also be written as,

//declare and instantiate object

int ages[] = new int[100];

  • You can also instantiate an array by directly initializing it with data.
  • For example,int arr[] = {1, 2, 3, 4, 5};This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5).


Accessing Array Element

  • To access an array element, or a part of the array, you use a number called an index or a subscript.
  • Index number or Subscript
    -assigned to each member of the array, to allow the program to access an individual member of the array.
    -begins with zero and progress sequentially by whole numbers to the end of the array.
    -NOTE: Elements inside your array are from 0 to (sizeOfArray-1).
  • For example, given the array we declared a while ago, we have

//assigns 10 to the first element in the array ages[0] = 10;

//prints the last element in the array System.out.print(ages[99]);

  • NOTE:
    -once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data.
    -for reference data types such as Strings, they are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly.


Coding Guidelines

  • It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration,

int []arr = new int[100]; is preferred over,

  • It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration,

int []arr = new int[100]; is preferred over,

int []arr; arr = new int[100];

int []arr; arr = new int[100];


Array Length
  • In order to get the number of elements in an array, you can use the length field of an array.
  • The length field of an array returns the size of the array. It can be used by writing,
    arrayName.length


Coding Guidelines

  • When creating for loops to process the elements of an array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays.
  • Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, final int ARRAY_SIZE = 1000; //declare a constant . . . int[] ages = new int[ARRAY_SIZE];


Multi-Dimensional Array

  • Multidimensional arrays are implemented as arrays of arrays.
  • Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name.
  • To access an element in a multidimensional array is just the same as accessing the elements in a one dimensional array.
  • For example, to access the first element in the first row of the array dogs, we write, System.out.print( dogs[0][0] );
  • This will print the String "terry" on the screen.



Command-line Arguments

l
  • A Java application can accept any number of arguments from the command-line. 
  • Command-line arguments allow the user to affect the operation of an application. 
  • The user enters command-line arguments when invoking the application and specifies them after the name of the class to run.  
  • In Java, when you invoke an application, the runtime system passes the command-line arguments to the application's main method via an array of Strings.

    public static void main( String[] args )


    Each String in the array contains one of the command-line arguments

    Example:

    1public class CommandLineSample
    2{
    3 public static void main( String[] args ){
    4
    5 for(int i=0; i
    6 System.out.println( args[i] );
    7 }
    8
    9 }
    10}  

Wednesday, February 25, 2009

Relational Operators



  • Relational operators compare two values and determines the relationship between those values.

  • The output of evaluation are the boolean values true or false.

Monday, February 23, 2009

Variables

  • A variable is an item of data used to store the state of objects.
  • A variable has a:
    -data type
  • The data type indicates the type of value that the variable can hold.
    -name
  • The variable name must follow rules for identifiers.

Declaring Variables

  • Declare a variable as follows:
    [=initial value];
  • Note: Values enclosed in <> are required values, while those values in [] are optional.

Coding Guidelines

  • It always good to initialize your variables as you declare them.
  • Use descriptive names for your variables. Like for example, if you want to have a variable that contains a grade for a student, name it as, grade and not just some random letters you choose.
  • Declare one variable per line of code. For example, the variable declarations,

double exam=0;

double quiz=10;

double grade = 0;
is preferred over the declaration,
double exam=0, quiz=10, grade=0;



Thursday, February 19, 2009

Literals

  • Literals are tokens that do not change - they are constant.
  • The different types of literals in Java are:
    -Integer Literals
    -Floating-Point Literals
    -Boolean Literals
    -Character Literals
    -String Literals

Integer Literals

  • Integer literals come in different formats:
    -decimal (base 10)‏
    -hexadecimal (base 16)‏
    -octal (base 8).
  • Special Notations in using integer literals in our programs:
    -Decimal
    No special notation
    example: 12
    -Hexadecimal
    Precede by 0x or 0X
    example: 0xC
    -Octal
    Precede by 0
    example: 014


Floating Point Literals

  • Represents decimals with fractional parts
    -Example: 3.1416
  • Can be expressed in standard or scientific notation
    -Example: 583.45 (standard), 5.8345e2 (scientific)‏


Boolean

  • Boolean literals have only two values, true or false.


Character Literals

  • Character Literals represent single Unicode characters.
  • Unicode character
    -a 16-bit character set that replaces the 8-bit ASCII character set.
    -Unicode allows the inclusion of symbols and special characters from other languages.
  • To use a character literal, enclose the character in single quote delimiter.
  • For example
    -the letter a, is represented as ‘a’.
    -special characters such as a newline character, a backslash is used followed by the character code. For example, \n’ for the newline character, ‘\r’ for the carriage return, ‘\b’ for backspace, '\t' for tab.


String Literals

  • String literals represent multiple characters and are enclosed by double quotes.
  • An example of a string literal is, “Hello World”.



Keywords

  • Keywords are predefined identifiers reserved by Java for a specific purpose.
  • You cannot use keywords as names for your variables, classes, methods ... etc.
  • Below is the list of the Java Keywords.

  • abstract
  • boolean
  • break
  • byte
  • bytevalue
  • case
  • catch
  • char
  • class
  • const
  • continue
  • default
  • do
  • double
  • else
  • extends
  • false
  • final
  • finally
  • for
  • goto
  • if
  • implements
  • import
  • instanceof
  • int
  • interface
  • long
  • native
  • null
  • package
  • private
  • protected
  • public
  • return
  • short
  • static
  • super
  • switch
  • synchronized
  • this
  • threadsafe
  • throw
  • transient
  • true
  • try
  • void
  • while

Identifiers

  • Identifiers
    -are tokens that represent names of variables, methods, classes, etc.
    -Examples of identifiers are: Hello, main, System, out.
  • Java identifiers are case-sensitive.
    -This means that the identifier Hello is not the same as hello.
  • Identifiers must begin with either a letter, an underscore “_”, or a dollar sign “$”. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9.
  • Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more about Java keywords later.


Coding Guidelines:

  • For names of classes, capitalize the first letter of the class name. For example,
    ThisIsAnExampleOfClassName
  • For names of methods and variables, the first letter of the word should start with a small letter. For example,
    thisIsAnExampleOfMethodName
  • In case of multi-word identifiers, use capital letters to indicate the start of the word except the first word. For example,
    charArray, fileNumber, ClassName.
  • Avoid using underscores at the start of the identifier such as _read or _write.

Statements & Blocks

  • Statement
    -one or more lines of code terminated by a semicolon.
    -Example:System.out.println(“Hello world”);
  • Block
    -is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit.
    -Block statements can be nested indefinitely.
    -Any amount of white space is allowed.
    -Example:

-public static void main( String[] args )

{

System.out.println("Hello");

System.out.println("world”);

}


Coding Guidelines:

  • In creating blocks, you can place the opening curly brace in line with the statement. For example:
    public static void main( String[] args ){
    or you can place the curly brace on the next line, like,
    public static void main( String[] args )‏
    {
  • You should indent the next statements after the start of a block. For example:
    public static void main( String[] args ){
    System.out.println("Hello");
    System.out.println("world");
    }


Coding Guidelines

  • The Java programs should always end with the .java extension.
  • Filenames should match the name of your public class. So for example, if the name of your public class is Hello, you should save it in a file called Hello.java.
  • You should write comments in your code explaining what a certain class does, or what a certain method do.

Analyzing the Basic Program

1 public class Hello
2 {
3 /**
4 * My first Java program
5 */

  • Indicates the name of the class which is Hello
  • In Java, all code should be placed inside a class declaration
  • The class uses an access specifier public, which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). We will be covering packages and access specifiers later.

______________________________________________________________________


1 public class Hello
2 {
3 /**
4 * My first Java program
5 */

  • The next line which contains a curly brace { indicates the start of a block.
  • In this code, we placed the curly brace at the next line after the class declaration, however, we can also place this next to the first line of our code. So, we could actually write our code as:
    public class Hello{

______________________________________________________________________


1 public class Hello
2 {
3 /**
4 * My first Java program
5 */

  • The next three lines indicates a Java comment.
  • A comment
    -something used to document a part of a code.
    -It is not part of the program itself, but used for documentation purposes.
    -It is good programming practice to add comments to your code.

______________________________________________________________________


1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){

  • Indicates the name of one method in Hello which is the main method.
  • The main method is the starting point of a Java program.
  • All programs except Applets written in Java start with the main method.
  • Make sure to follow the exact signature.

______________________________________________________________________


1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){
7
//prints the string “Hello world” on screen

The 7th line is also a Java comment

______________________________________________________________________


1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){
7 //prints the string “Hello world” on screen
8
System.out.println(“Hello world”);

The command System.out.println(), prints the text enclosed by quotation on the screen.
______________________________________________________________________

1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){
7 //prints the string “Hello world” on screen
8 System.out.println(“Hello world”);

9 }
10 }

The last two lines which contains the two curly braces is used to close the main method and class respectively.





Basic Elements For Programing

Sample Java Program:

1 public class Hello
2 {
3 /**
4 * My first Java program
5 */
6 public static void main( String[] args ){
7 //prints the string Hello world on screen
8 System.out.println(“Hello world”);
9 }
10 }