Friday, June 3, 2011

JAVA Programming Fundamentals I

JAVA Programming Fundamentals I
Topics:
  • What is Java Technology?
  • Features of Java Technology
  • Phases of a Java Program.
  • Identifying the basic parts of a Java program. Java literals, primitive data types, variables, identifiers and operators.
What is Java Technology?
  • A programming language
  • A development environment
  • An application and deployment environment
1. A Programming Language
  • As a programming language, Java can be used to create all kinds of applications that you could create using any conventional programming language.
  • Its primary goal is to enable developers to write applications that could run to any platform. (Write once, run anywhere.)
2. A Development Environment
  • As a development environment, Java provides the developers with a large suite of tools: (comes with the Java 2 SDK)
              - A compiler (javac)
              - An interpreter (java)
              - A documentation generator (javadoc)
              - A packaging tool (jar) and many more...
3. An Application and Deployment Environment
  •  In order for Java Applications to run on any target machine, Java Runtime Environment (JRE) should be installed.
  •  The two main deployment environments are:
      - the JRE supplied by the Java 2 Software Development Kit.
      - your web browser which usually comes with a Java Interpreter and runtime environment.
Features of Java Technology
1. Java Virtual Machine (JVM)
  • An imaginary machine that runs on top of the underlying operating system responsible in running Java applications.
  • It interprets the Java program for the native operating system.
  • It is provided by the Java Runtime Environment suited for a particular platform.
2. Java Bytecode (.class)
  • A special machine language that can be understood and execute by the JVM.
  • It is platform independent, allowing any machine to execute a Java program regardless where it was compiled.    
3. Garbage Collector
  • It is a special thread that comes with the JVM responsible for freeing-up memory allocations. 
  • Garbage collection automatically happens during the lifetime of a Java program and in a scheduled and strategic manner.
  • The developers are now freed from the tedious tasks of manual memory deallocations.

JVM, Bytcode and Garbage Colletor

Phases of a Java Program
   1. define the problem
   2. design a solution (classes, methods)
   3. Implement design
   4. Test (go back to step2 if tests fail)







My first Java Program:
    public class myFirstJavaClass {
       public static void main(String[] args) {
            System.out.println("Hello World!");      
       }
  }
Inspecting my first Java Program:
Java Class 










Class Declaration
  • A class should:
  • have a fully-qualified class name.
  • be declared with a class keyword.
  • be declared with an Access Modifier, possible values are public, abstract and final.
  • have an open and close curly braces {} to indicate its code block.

Method Declaration
A method should:

  • have a fully-qualified method name.
  • be declared with an Access Modifier, possible values are public, private, protected, static, abstract, synchronized and final.
  • have a return type: any primitive type or object type.
  • have an open and close parenthesis () after its name.
  • have an open and close curly braces {} to indicate its code block.
Package Declaration
  • A package is a set of Java classes.
  • Use package keyword in package declaration.

Import Declaration
  •  It is used to refer other Java classes defined in a different package by using the import keyword and qualifying their names with the package name and a period.
Java Comments:
  • These are notes written to a code for documentation purposes.
  • These are not actually part of the program and do not affect the program flow.
  • Types are C++-style or single line, C-style or block and Javadoc comments.
           // This is an example of C++-style or single line comment
           /**
             * This is an example of C-style or block comment.
             */
           /**
             * This is an example of special Javadoc comments
             * and it uses tags like:
             * @author Froilan C. Benito
             * @since January 1, 2007
             * @version 1.0.0.0
             */
Java Statements:
  • One or more lines of code terminated by a semicolon;
      System.out.println("Hello World!");
Java Blocks:
  • One or more statements bounded by an open and close curly braces {} that groups them as one unit.
        public static void main(String[] args) {
               System.out.println("Hello World!");
               System.out.println("Hello World Again!");
               System.out.println("Hello World Again and Again!");
          }
Best practices in writing Java programs:
  • Java source files should always end with “.java” extension.
  • Filename should match the name of your class within your class declaration.
  • Take advantage the use of comments. Comments should be descriptive enough to explain what a specific code does.
  • Use indentations in writing Java statements. It enhances code readability
Java Identifiers:
  • These are user-defined tokens that represent names of packages, classes, interfaces, methods, variables and enums. Examples are HelloWorld, main, System and println.
  • Identifiers are case-sensitive.
  • Identifiers should begin with either an alphabet ”a-z, A-Z”, an underscore “_” or a dollar sign “$”. Subsequent characters may be numbers (0-9).
  • Avoid usage of Java Keywords in naming Identifiers. Examples of Java Keywords are public, class, interface, for, else, etc.
Java Identifiers Naming Conventions:
  • For classes with a single-word names, capitalize the first letter of the class name. For example, 
        public class Inventions {
          }
  • For classes with a multi-word names, capitalize the first letter of every word. For example,
        public class myFirstJavaClass {
          }
  • For variables and methods with a single-word names, the first letter should begin with a small letter. For example, 
        String name;
          public void invention() {
          }

  • For variables and methods with a multi-word names, use capital letters to indicate the start of the word except the first word. For example,
        String thisIsMyName;
          public void thisIsMyInvention() {
          }

  • Avoid using underscores “_” and dollar signs “$” at the start of an identifier.

        String _ThisIsMyName;
          public void _avoidThis() {
          }
          String $ThisIsMyName;
          public void $avoidThis() {
          }
Java Keywords:

  • These are special identifiers reserved by Java for specific purpose.
  • You cannot use keywords in naming your packages, classes, interfaces, methods, variables and enums.

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

  • These are tokens that do not change, they are constant. Usually they are values of variables.

Types of Literals


  • Integer Literals, examples are 0, 1, 2… 9
  • Floating Point Literals, examples are 3.1416, 1.453, 5.6743e2
  • Boolean Literals, could be true or false
  • Character Literals, examples are ‘a’, ‘b’, ‘c’, ‘\n’, ‘\r’, ‘\b’
  • String Literals, examples are “Hello World!”, “I am Froi”, “Java Rocks!”
Java Primitive Types:
Defines the set of values that expression can produce or a variable can contain. Also defines what operations can be performed on an expression or a variable.
Java defines eight primitive types:
  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
  • long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead ofdouble) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of'\uffff' (or 65,535 inclusive).

Type Casting:
refers to changing an entity of one datatype into another. This is important for the type conversion in developing any application. If you will store a int value into a byte variable directly, this will be illegal operation. For storing your calculated int value in a byte variable you will have to change the type of resultant data which has to be stored. This type of operation has illustrated below :
In this example we will see that how to convert the data type by using type casting. In the given line of the code c = (char)(t?1:0); illustrates that if t which is boolean type variable is true then value of c which is the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into character according to the Unicode value. But in this line c = (char)(t?'1':'0'); 1 is already given as a character which will be stored as it is in the char type variable c.
Code sample
//X is a supper class of Y and Z which are sibblings.
public class RunTimeCastDemo {
public static void main(String args[]) {
                 X x = new X();
                 Y y = new Y();
                 Z z = new Z();
                 X xy = new Y(); // compiles ok (up the hierarchy)
                 X xz = new Z(); // compiles ok (up the hierarchy)
                 //  Y yz = new Z();   incompatible type (siblings)
                 //  Y y1 = new X();   X is not a Y
                 //  Z z1 = new X();   X is not a Z
                 X x1 = y; // compiles ok (y is subclass of X)
                 X x2 = z; // compiles ok (z is subclass of X)
                 Y y1 = (Y) x; // compiles ok but produces runtime error
                 Z z1 = (Z) x; // compiles ok but produces runtime error
                 Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
                 Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
                 //  Y y3 = (Y) z;     inconvertible types (siblings)
                 //  Z z3 = (Z) y;     inconvertible types (siblings)
                 Object o = z;
                 Object o1 = (Y) o; // compiles ok but produces runtime error
            }
       }

Variables:
  • These are user-defined items that can hold data constantly or dynamically.
  • Variables should be declared the following way
               type identifier [ = value][, identifier [= value] ...] ;
  • Variables should have a primitive type or object reference type.
Examples are:
         String name = "Froilan";
      public int age = 21;
      final boolean isHandsome = true;
Best Practices in Variable declarations
  • Declaring your variables with initial values is a good idea.
  • Always use descriptive names for your variables.
  • Declare one variable per line of code.
Scope of a Variable
You can declare variables in several different places:
  • In a class body as class fields. Variables declared here are referred to as class-level variables.
  • As parameters of a method or constructor.
  • In a method's body or a constructor's body.
  • Within a statement block, such as inside a while or for block.
Variable scope refers to the accessibility of a variable.
The rule 1 is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined. For example, consider the following for statement.
         public class MainClass {
              public static void main(String[] args) {
                   for (int x = 0; x < 5; x++) {
                        System.out.println(x);
                   }
              }
         }
Rule number 2 is a nested block can access variables declared in the outer block. Consider this code.

         public class MainClass {
              public static void main(String[] args) {
                   for (int x = 0; x < 5; x++) {
                        for (int y = 0; y < 3; y++) {
                             System.out.println(x);
                             System.out.println(y);
                        }
                   }
              }
         }
Variables declared as method parameters can be accessed from within the method body. Class-level variables are accessible from anywhere in the class.
If a method declares a local variable that has the same name as a class-level variable, the former will 'shadow' the latter. To access the class-level variable from inside the method body, use the this keyword.

Variable scope in a block
         public class MainClass {
              public static void main(String[] args) {
                   int outer = 1;
                   {
                        int inner = 2;
                        System.out.println("inner = " + inner);
                        System.out.println("outer = " + outer);
                   }
                   int inner = 3;
                   System.out.println("inner = " + inner);
                   System.out.println("outer = " + outer);
              }
         }


Variable Types
There are three kinds of variables in Java:
  • Local variables
  • Instance variables
  • Class/static variables
Local Variables
  • are declared in methods, constructors, or blocks.
  • are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.
  • Access modifiers cannot be used for local variables.
  • are visible only within the declared method, constructor or block.
  • are implemented at stack level internally.
  • There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Example:

Here age is a local variable. This is defined inside pupAge() method and its scope is limited to this method only.

       public class Test{ 
             public void pupAge(){
                  int age = 0;
                  age = age + 7;
                  System.out.println("Puppy age is : " + age)
             }   
             public static void main(String args[]){
                  Test test = new Test();
                  Test.pupAge();
             }
        }
Output: Puppy age is: 7

Instance variables
  • are declared in a class, but outside a method, constructor or any block.
  • When a space is allocated for an object in the heap a slot for each instance variable value is created.
  • are created when an object is created with the use of the key word 'new' and destroyed when the object is destroyed.
  • hold values that must be referenced by more than one method, constructor or block, or essential parts of an object.s state that must be present through out the class.
  • can be declared in class level before or after use.
  • Access modifiers can be given for instance variables.
  • are visible for all methods, constructors and block in the class. Normally it is recommended to make these variables private (access level).However visibility for subclasses can be given for these variables with the use of access modifiers.
  • have default values. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor.
  • can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) the should be called using the fully qualified name . ObjectReference.VariableName.
Example:
   import java.io.*
   class Employee { 
        // this instance variable is visible for any child class. 
        public String name
        // salary  variable is visible in Employee class only. 
        private double salary;
        // The name variable is assigned in the constructor. 
        public Employee (String empName) { 
             name = empName; 
        } 
        // The salary variable is assigned a value. 
        public void setSalary(double empSal) { 
             salary = empSal; 
        } 
        // This method prints the employee details. 
        public void printEmp() { 
             System.out.println("name  : " + name ); 
             System.out.println("salary :" + salary ); 
        } 
        public static void main(String args[]) { 
             Employee empOne = new Employee("Froilan"); 
             empOne.setSalary(1000);
                empOne.printEmp(); 
        } 
  }
Output:
Name: Froilan
Salary: 1000.0
Classic/Static Variables
  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • There would only be one copy of each class variable per class, regardless of how many objects are created from it.
  • Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.
  • Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.
  • Static variables are created when the program starts and destroyed when the program stops.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Default values are same as instance variables. For numbers the default value is 0, for Booleans it is false and for object references it is null. Values can be assigned during the declaration or within the constructor. Additionally values can be assigned in special static initializer blocks.
  • Static variables can be accessed by calling with the class name . ClassName.VariableName.
  • When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final the naming syntax is the same as instance and local variables.
Example:
       import java.io.*; 
class Employee{ 
    // salary  variable is a private static variable 
    private static double salary
    // DEPARTMENT is a constant 
    public static final String DEPARTMENT = "Development"
    public static void main(String args[]){ 
         salary = 1000; 
         System.out.println(DEPARTMENT "average salary:" salary);                       
    } 
}
Output: Development average salary:1000

Primitive Variables vs. Reference Variables

Primitive Variables:
  • These are variables with primitive data types such as int or long.
  • Store the data in the actual memory location where the variable is located
Reference Variables:
  • These are variables that store the memory address that points to another memory address where the actual data is located.
  • Declaring a variable for a certain class is actually declaring a reference variable to the actual object of that class.
Example:

      int salary  = 100; // A primitive variable
       String name = "Froilan"; // A reference variable

Operators
  • Simple Assignment Operator
= Simple assignment operator
  • Arithmetic Operators
+ Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator / Division operator % Remainder operator
  • Unary Operators
U+ Unary plus operator; indicates positive value (numbers are positive without this, however) - Unary minus operator; negates an expression ++ Increment operator; increments a value by 1 -- Decrement operator; decrements a value by 1 ! Logical compliment operator; inverts the value of a boolean
  • Equality and Relational Operators
== Equal to != Not equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to
  • Conditional Operators
&& Conditional-AND || Conditional-OR ?: Ternary (shorthand for if-then-else statement)

NOTE: These operators follow certain kind of precedence so the compiler will know which operator to evaluate first in case of multiple operators are used in a single statement.
Summary:
  • Java Technology: A programming language, a development environment, and an application and deployment environment.
  • Java Virtual Machine and Garbage Collector are the primary features of Java Technology.
  • Write, compile and run are the phases of a Java program.
  • Basic parts of a Java program are package, import, class and method declarations.
  • Primitive Types: byte, short, int, char, long, float and double.
  • Variables and Scope
  • Operators: Arithmetic, Relational, Logical and Conditional.
Next: Java Programming Fundamentals II

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Blog List