You are on page 1of 124

Unit 4 - Java basics & usage of Classes,

Objects &
Inheritance
By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Contents
• 4.1.1 Explain eight simple types of data. • 4.1.8 Create classes and objects.
• 4.1.2 Explain Java literals. • 4.1.9 Illustrate the use of new operator
• 4.1.3 Declare and initialize variables. and methods, constructors, method
• 4.1.4 Illustrate type conversion and overloading, ‘this’ pointer
casting features. • 4.1.10 Explain the working of static and
• 4.1.5 Illustrate use of one-dimensional final.
and two–dimensional array. • 4.1.11 Explain string classes and
• 4.1.6 Explain various types of operators. methods.
• 4.1.7 Write the syntax of selection • 4.1.12 Illustrate the use of command-
statements, iteration statements, jump, line arguments.
break, and continue statements • 4.1.13 Illustrate the Implementation of
inheritance
• 4.1.14 Illustrate the implementation of
multi level hierarchy
• 4.1.15 Illustrate the use of ‘final’ to
avoid overriding.
Hello World!

// HelloWorld.java: Hello World program


import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Hello World! Java vs C Lang...

// HelloWorld.java: Hello World program /* helloworld.c: Hello World program */


import java.lang.*;
#define <stdio.h>
class HelloWorld
{
public static void main(String args[]) void main(int argc, char *argv[])
{ {
System.out.println(“Hello World”); printf(“Hello World\n”);
} }
}
Closer Look at - Hello World
• The class has one method – main()

public static void main(String args[])


{
System.out.println(“Hello World”);
}
• Command line input arguments are passed in the String array
args[]

e.g java HelloWorld John Jane

args[0] – John args[1] – Jane


Default package - java.lang.*
• import java.lang.*;
▫ Java allows grouping of related classes into a package.
▫ It allows different companies to develop different packages, may even have same class
and method names, but they differ by package name:
ibm.mathlib.*
microsoft.mathlib.*
Helps in managing name clash problems.
▫ Think of this package as library.
▫ “import” statement somewhat serves similar purpose as C’s #include
▫ If you don’t add import statement, then you need utilise fully qualified name.
ibm.mathlib.sin()
If you do “import ibm.*” then you can use mathlib.sin() instead.
• You don't need to import java.lang.*
• That means, you can invoke services of java’s “lang” package classes/entities, you don’t
need to use fully qualified names.
▫ We used System.out.println() instead of
java.lang. System.out.println()
public static void main(String args[])
• public:
▫ The keyword “public” is an access specifier that declares the
main method as unprotected.
• static:
▫ It says this method belongs to the entire class and NOT a part
of any objects of class.
▫ The main must always be declared static since the interpreter
uses this before any objects are created.
• void:
▫ The type modifier that states that main does not return any value.
System.out.println(“Hello World”);
• java.lang.*
▫ Import All classes/items in “lang” package of java
package.
• System is really the java.lang.System class.
▫ This class has a public static field called out which is an instance
of the java.io.PrintStream class.
• So when we write System.out.println(), we are really
invoking the println() method of the “out” field of the
java.lang.System class.
Java Program Structure
Documentation Section

Package Statement

Import Statements

Interface Statements

Class Declarations

Main Method Class


{
}
More Java Classes and static methods

// SquareRoot.java: compute square root of number

import java.lang.Math;

class SquareRoot
{
public static void main(String args [])
{
double x = 4;
double y;
y = Math.sqrt(x);
System.out.println("y= "+y);
}
}
Java Literals
• A literal is the source code representation of a fixed value.
• Literals in Java are a sequence of characters (digits, letters, and
other characters) that represent constant values to be stored in
variables.
• Java language specifies five major types of literals.
▫ Integer literals
int decimal = 100;
int octal = 0144;
int hexa =  0x64;
▫ Floating literals
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32)  Double-precision floating-point literal
7D  Double-precision floating-point literal
.01f  Floating-point literal
▫ Character literals
▫ String literals
▫ Boolean literals
Numeric Literals
▫ Integer literals
int decimal = 100;
int octal = 0144;
int hexa =  0x64;
▫ Floating literals
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32)  Double-precision floating-point literal
7D  Double-precision floating-point literal
.01f  Floating-point literal
Character and String Literals
▫ Character Literals
The ASCII character set includes 128 characters including letters, numerals,
 punctuation etc.
Below table shows a set of these special characters.
▫ String Literals
The set of characters in represented as String literals in Java.
Always use "double quotes" for String literals.
 Escape  Meaning  'u0041'  Capital letter A
 \n  New line  '\u0030'  Digit 0
 \t  Tab  '\u0022'  Double quote "
 \b  Backspace  '\u003b'  Punctuation ;
 \r  Carriage return  '\u0020'  Space
 \f  Formfeed  '\u0009'  Horizontal Tab 
 \\  Backslash
 \'  Single quotation mark  ""  The empty string
 \"  Double quotation mark  "\""  A string containing
 \d  Octal  "This is a string"  A string containing 16 characters
 \xd  Hexadecimal  "This is a " + "two-  actually a string-valued constant expression,
 \ud  Unicode character line string" formed from two string literals
Boolean and null Literals
▫ Boolean Literals:
The values true and false are treated as literals in Java programming.
When we assign a value to a boolean variable, we can only use these
two values.
Example: boolean chosen = true;

▫ Null Literals
The final literal that we can use in Java programming is a Null literal.
We specify the Null literal in the source code as 'null'.
To reduce the number of references to an object, use null literal.
The type of the null literal is always null.
We typically assign null literals to object reference variables.
Example: s = null;
Java Data types and References
Primitive Data Types
• There are totally eight primitive data types in Java. They can be
categorized as given below:
• Integer types (Does not allow decimal places)
▫ byte
▫ short
▫ int
▫ long
• Rational Numbers(Numbers with decimal places)
▫ float
▫ double
• characters
▫ char
• conditional
▫ boolean
Data Types with Characteristics
Data Type Memory Size Default value Declaration
byte 8 bits 0 byte a=9;
short 16 bits 0 short b=89;

int 32 bits 0 int c=8789;

long 64 bits 0 long=9878688;

float 32 bits 0.0f float b=89.8f;

double 64 bits 0.0 double c =87.098

char 16 bits '\u0000' char a ='e';

boolean JVM Dependent false boolean a =true;


Java Variables
• Variable is a name of memory location.
data type variable [ = value][, variable [= value] ...] ;
• There are three types of variables:
▫ Local variables
A variable that is declared inside the method is called local variable.
▫ Instance variables
A variable that is declared inside the class but outside the method is
called instance variable .
It is not declared as static.
▫ Static variables
A variable that is declared as static is called static variable.
It cannot be local.
Local Variables public class LocalVariable
{
• Local variables are declared in methods, public void pupAge()
constructors, or blocks. {
• Life: Local variables are created when the int age = 0;
method, constructor or block is entered age = age + 7;
and the variable will be destroyed once it System.out.println("Puppy age is : " + age);
exits the method, constructor or block. }
• Access modifiers cannot be used for local public static void main (String args[])
variables. {
• Span: Local variables are visible only
within the declared method, constructor or LocalVariable obj = new LocalVariable ();
block. obj.pupAge();
• Local variables are implemented at stack }
level internally. }//end of class
• Default Value: There is no default value
for local variables so local variables should
be declared and an initial value should be Output:
assigned before the first use. Puppy age is: 7
Instance Variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Life: Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
• Instance variables 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
throughout the class.
• Access modifiers can be given for instance variables.
• Span: The instance variables are visible for all methods, constructors and block in the
class.
• Default Values: Instance variables have default values.
▫ For numbers the default value is 0,
▫ for Booleans it is false and
▫ for object references it is null.
• Instance variables can be accessed directly by calling the variable name inside the class.
import java.io.*;
public class Employee
{
public String name; // this instance variable is visible for any child class.
private double salary; // salary variable is visible in Employee class only.

// 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; }
public void printEmp() // This method prints the employee details.
{
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[])
{
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
Class/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.
• Life: Static variables are created when the program starts and destroyed when
the program stops.
• Span: 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: They 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;
Constants
• Constants are similar to //Declaring Constants Example
variables except that they
hold a fixed value. class CircleArea
• They are also called {
“READ” only variables. public static void main(String args[])
{
• Constants are declared with
final double PI = 3.1428;
the reserved double radius = 5.5; // in cms
word “final”. double area;
final int MAX_LENGTH
= 420; area = PI * radius * radius;
final double PI =
3.1428; System.out.println("Circle Radius = "
• By convention upper case +radius+”Area="+area);
letters are used for defining }
constants. }
import java.io.*;
public 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
Java - Modifier Types
• Access Control Modifiers:
▫ Java provides a number of access modifiers to set access levels for classes,
variables, methods and constructors.
▫ The four access levels are:
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
• Non Access Modifiers:
▫ Java provides a number of non-access modifiers to achieve many other
functionality.
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes, methods, and
variables.
The abstract modifier for creating abstract classes and methods.
The synchronized and volatile modifiers, which are used for threads.
Type Conversion and Casting
• Changing a value from one data type to another type is known as data
type conversion.
• Data type conversions are either widening or narrowing, it depends on
the data capacities of the data types involved.
• There are different ways of, implicitly or explicitly - changing an entity
of one data type into another data type.
• An important consideration with a type conversion is whether the result
of the conversion is within the range of the destination data type.
• If the two types are compatible, then Java will perform the conversion
automatically.
▫ For example, assign an int value to a long variable.
• For incompatible types we must use a cast.
• Casting is an explicit conversion between incompatible types.
Conversion - Widening and Narrowing
• Widening conversion is allowed in the following cases:
byte can be converted to short, int, long, float, or double
Short can be converted toint, long, float, or double
char can be converted toint, long, float, or double
intcan be converted to long, float, or double
long can be converted to float or double
float can be converted to double
• Narrowing conversion is allowed in these cases:
short can be converted to byte or char
char can be converted to byte or short
int can be converted to byte, short, or char
long can be converted to byte, short, or char
float can be converted to byte, short, char, int, or long
double can be converted to byte, short, char, int, long, or float
• Narrowing conversion should follow the following thumb rule
The narrowing conversion must be explicit.
The target type need to be specified in parentheses.
public class Main /* Representing widening conversions, integer and floating-point */
{
public static void main(String[] argv)
{
int i = 1234;
float f = i;
System.out.println("i is " + i);
System.out.println("f is " + f);
}
}
public class Main /* Representing the use of intValue() function to fetch the integer value from a string*/
{
public static void main(String[] argv)
{
String strValue = "5";
try
{
int iValue = new Integer(strValue).intValue();
}
catch (NumberFormatException ex)
{
ex.printStackTrace();
}
}
}
public class MainClass /* Representing the automatic Type Promotion in Expressions*/
{
public static void main(String args[])
{
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

double result = (f * b) + (i / c) - (d * s);


System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
What’s output of the following code?
public class Main
{ public class Main
public static void main(String[] argv) {
{ public static void main(String[] argv)
char ch = 'a'; {
int num = 99; byte b = 11111;
ch = num; }
} }
}
public class MainClass /* Type Casting - Representing the narrowing conversion */
{
public static void main(String[] args)
{
long a = 12345678965;
int b = (int) a; // narrowing conversion
System.out.println(a); System.out.println(b);
}
}

public class MainClass /*Type Casting - Representing the casting of incompatible types */
{
public static void main(String args[])
{
byte b;
int i = 399; double d = 424.142;
System.out.println("\nConversion of int to byte.");

b = (byte) i;
System.out.println("i and b " + i + " " + b+ "\nConversion of double to int.");

i = (int) d;
System.out.println("d and i " + d + " " + i+ "\nConversion of double to byte.");

b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Java Arrays
• Java provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
• Declaring Array Variables:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
• Creating Arrays:
▫ You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
• The above statement does two things:
▫ It creates an array using new dataType[arraySize];
▫ It assigns the reference of the newly created array to the variable arrayRefVar.
• Declaring an array variable, creating an array, and assigning the reference of the array
to the variable can be combined in one statement:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Java Arrays
• Array is a data structure capable to hold data of similar data types.
• Following are the properties of arrays as accepted by the Java compiler.
▫ Arrays stores similar data types.
That is, array can hold data of same data type values.
This is one of the limitations of arrays compared to other data structures.
▫ Each value stored, in an array, is known as an element and all elements are indexed.
The first element added, by default, gets 0 index.
That is, the 5th element added gets an index number of 4.
▫ Elements can be retrieved by their index number.
▫ Array elements are stored in contiguous (continuous) memory locations.
▫ Once array is created, its size is fixed.
That is, at runtime if required, more elements cannot be added.
This is another limitation of arrays compared to other data structures.
▫ One array name can represent multiple values.
Array is the easiest way to store a large quantity of data of same data types.
▫ Arrays can be multidimensional.
▫ At the time of creation itself, array size should be declared (array initialization does not require
size).
▫ In Java, arrays are predefined objects.
With methods, the array elements can be manipulated.
▫ As Java does not support garbage values, unassigned elements are given default values; the
same values given to unassigned instance variables.
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++)
{ System.out.println(myList[i] + " "); }

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++)
{ total += myList[i]; }
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0]; Output:
for (int i = 1; i < myList.length; i++) 1.9
2.9
{ if (myList[i] > max) max = myList[i]; }
3.4
System.out.println("Max is " + max);
3.5
} Total is 11.7
} Max is 3.5
public class ArrayTest1
{
public static void main(String args[])
{
int marks[] = new int[5];

System.out.println("Elements are " + marks.length);


System.out.println("Default value: " + marks[0]);
// Now assign values
marks[0] = 50; marks[1] = 60; marks[2] = 70; marks[3] = 80; marks[4] =
90;

System.out.println("Value of 1st element: " + marks[0]);

System.out.println("\nPrint the values in a single row");


for(int i = 0; i < marks.length; i++)
{
System.out.print(marks[i] + "\t"); // to print in a single line, ln is removed
}

System.out.println("\n\nOther way of printing supported from JDK 1.5");


for(int k : marks)
{
System.out.print(k + "\t");
}
}
import java.util.Scanner;  
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];  
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];  

System.out.println("Enter " + n + " integers");  


for (c = 0; c < n; c++)
array[c] = in.nextInt();  
System.out.println("Enter value to find");
search = in.nextInt();  
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
public class MyBinarySearch
{
    public int binarySearch(int[] inputArr, int key)
{
        int start = 0;
        int end = inputArr.length - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            if (key == inputArr[mid]) {     return mid;        }
            if (key < inputArr[mid]) {     end = mid - 1;    } 
else {     start = mid + 1; }
      }
        return -1;
  }
  
  public static void main(String[] args)
{
        MyBinarySearch mbs = new MyBinarySearch();
        int[] arr = {2, 4, 6, 8, 10, 12, 14, 16};
        System.out.println("Key 14's position: "+mbs.binarySearch(arr, 14));
        int[] arr1 = {6,34,78,123,432,900};
        System.out.println("Key 432's position: "+mbs.binarySearch(arr1, 432));
    }
}
public class MyRecursiveBinarySearch
{
    public static int recursiveBinarySearch(int[] sortedArray, int start, int end, int key)
{        
        if (start < end)
{
            int mid = start + (end - start) / 2; 
            if (key < sortedArray[mid]) {
                return recursiveBinarySearch(sortedArray, start, mid, key);
            } 
else if (key > sortedArray[mid]) {
                return recursiveBinarySearch(sortedArray, mid+1, end , key);
            } 
else {    return mid;   }
        }
        return -(start + 1); 
    }
    public static void main(String[] args)
{
        int[] arr1 = {2,45,234,567,876,900,976,999};
        int index = recursiveBinarySearch(arr1,0,arr1.length,45);
        System.out.println("Found 45 at "+index+" index");
        index = recursiveBinarySearch(arr1,0,arr1.length,999);
        System.out.println("Found 999 at "+index+" index");
        index = recursiveBinarySearch(arr1,0,arr1.length,876);
        System.out.println("Found 876 at "+index+" index");
    }
}
More Array Example Codes
Java 2D Arrays
• In Java, multidimensional arrays are actually arrays of arrays. For example, the following
declares a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
public class Main
{
public static void main(String args[])
{
int twoD[][] = new int[4][5];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{ twoD[i][j] = i*j; }
}
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{ System.out.print(twoD[i][j] + " "); }
System.out.println();
}
}
}
import java.applet.*;
import java.awt.*;
public class Applet3 extends Applet
{
      int table[][];
      public void init()
      {
            table = new int[6][8];
            for (int x=0; x<6; ++x)
            for (int y=0; y<8; ++y)
            table[x][y] = x+y*6;
      }
      public void paint(Graphics g)
      {
            for (int x=0; x<6; ++x)
            for (int y=0; y<8; ++y)
            {
                  String s = String.valueOf(table[x][y]);
                  g.drawString(s, 50+x*25, 50+y*15);
            }
      }
}
Types of operators
• Java operators can be grouped into the following four groups:
▫ Arithmetic
Arithmetic operators are used in mathematical expressions in the same
way that they are used in algebra.
▫ Bitwise
Java bitwise operators can be applied to the integer types: long, int,
short, char, byte.
Bitwise Operators act upon the individual bits of their operands.
▫ Relational
The relational operators determine the relationship between two operands.
▫ Logical
The Boolean logical operators operate only on boolean operands.
Java Arithmetic Operators
Operato public class ArithmeticTest
Result
r {
+ Addition public static void main(String args[])
- Subtraction (unary minus) {
System.out.println("Integer Arithmetic");
* Multiplication
int a = 1 + 1;
/ Division int b = a * 3;
% Modulus int c = b / 4;
++ Increment int d = c - a;
int e = -d;
+= Addition assignment
System.out.println("a = " + a);
-= Subtraction assignment System.out.println("b = " + b);
*= Multiplication assignment System.out.println("c = " + c);
/= Division assignment System.out.println("d = " + d);
System.out.println("e = " + e);
%= Modulus assignment
}
-- Decrement }
Home Work: Calculate Area of a Circle!
//the modulus operator to calculate the prime numbers
public class Main
{
public static void main(String[] args)
{
int limit = 100;
System.out.println("Prime numbers between 1 and " + limit);
for (int i = 1; i < 100; i++)
{
boolean isPrime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
isPrime = false; break;
}
}
if (isPrime) System.out.print(i + " ");
}
} Prime numbers between 1 and 100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83
} 89 97
Bitwise Operators public class BitwiseTest
Operator Result {
public static void main(String args[])
~ Bitwise unary NOT
{
& Bitwise AND int a = 1;
| Bitwise OR int b = 2;
^ Bitwise exclusive OR int c = a | b;
int d = a & b;
>> Shift right
int e = a ^ b;
>>> Shift right zero fill int f = (~a & b) | (a & ~b);
<< Shift left int g = ~a & 0x0f;
&= Bitwise AND assignment System.out.println(" a = " + a);
|= Bitwise OR assignment
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
^= Bitwise exclusive OR System.out.println(" a&b = " + d);
assignment
System.out.println(" a^b = " + e);
>>= Shift right assignment System.out.println("~a&b|a&~b = " + f)
>>>= Shift right zero fill assignment ;
System.out.println(" ~a = " + g);
<<= Shift left assignment }
}
Relational Operators

public class Main


Operator Result {
== Equal to public static void main(String[] argv)
!= Not equal to {
> Greater than int a = 4;
int b = 1;
< Less than
boolean c = a < b;
>= Greater than or equal to System.out.println("c is " + c);
<= Less than or equal to }
}
Boolean Logical Operators
public class BooleanLogicalTest
{
Operato public static void main(String args[])
Result
r {
& Logical AND boolean a = true;
| Logical OR boolean b = false;
boolean c = a | b;
^ Logical XOR (exclusive OR)
boolean d = a & b;
|| Short-circuit OR boolean e = a ^ b;
&& Short-circuit AND boolean f = (!a & b) | (a & !b);
! Logical unary NOT boolean g = !a;
System.out.println(" a = " + a);
&= AND assignment
System.out.println(" b = " + b);
|= OR assignment System.out.println(" a|b = " + c);
^= XOR assignment System.out.println(" a&b = " + d);
== Equal to System.out.println(" a^b = " + e);
!= Not equal to System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
?: Ternary if-then-else
}
}
Descending Order of Precedence

Category Operators
Unary ++ -- + - ! ~ (type)
Arithmetic */%+-
Shift <<>>>>>
Comparison <<= >>= instanceof == !=
Bitwise &^|
Short-circuit && ||
Conditional ?:
Assignment = op=
The statements inside your source files are generally executed from top to bottom, in the order that they appear. 

Control flow statements, however, break up the flow of execution by employing decision making, looping, and
branching, enabling your program to conditionally execute particular blocks of code.

This section describes the decision-making statements (if-then, if-then-else, switch), the looping statements (for,
 while, do-while), and the branching statements (break, continue, return) supported by the Java programming
language.
Java Control statements
• Java Control statements control the order of execution in a
java program, based on data values and conditional logic.
• There are three main categories of control flow statements;
▫ Selection statements: 
if, if-else and switch.
▫ Loop statements: 
while, do-while and for.
▫ Transfer statements: 
break, continue, return, try-catch-finally and assert.
• We use control statements when we want to change the
default sequential order of execution
Selection: if statement
• The if statement executes a block of code
only if the specified expression is true.
• If the value is false, then the if block is
skipped and execution continues with the
rest of the program.
• You can either have a single statement or
a block of code within an if statement.
• Note that the conditional expression must
be a Boolean expression.
• The simple if statement has the following
syntax:
 if (<conditional expression>) 
       <statement action>
Selection: extended if statement
The if-else statements The Nested if-else statements
It is basically extension of if statement.  The Nested if-else statements are used where we want to make
series of decision making. Thus one if-else is nested within
if(boolean-expression)
{ another if-else. Therefore nested if-else give us to make a
  if-code; decision within a decision already taken.
}
else
{ if(boolean-expression 1)
  else-code; {
}   if(boolean-expression 2)
  {
Else-if Ladder Statements     statement 1;
Else-if ladder is generally used when we want to take multiple   }
decision. These multiple decision are in chains of if followed by   else
  {
else-if statements till n number.      statement 2;
if(boolean-expression 1)   }
{ }
  statement-1; else
} {
else if(boolean-expression 2)   statement 3;
     { }
       statement-2;
     }
     else if(boolean-expression n)
       {
         statement-n;
       }      
          else
          {
          default-statement;   
          }
public class IfStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;

if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b < a");
}
}
public class IfElseStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;

if (a > b)
{
System.out.println("a > b");
}
else
{
System.out.println("b < a");
}
}
}
Selection: switch statement
• if-else is limited to use in complex scenarios.
• This switch statement evaluates an expression and based on the result of expression
chooses a path that matches one of the list values.
• The list values are called as Cases.
• The expression value is matched against this cases, and which ever case match the
control moves to that switch.
switch(expression)
{
  case value-1:
              block-1
              break;
  case value-2:
              block-2
              break;
 
  default:
             default-block
             break;
}
public class SwitchCaseStatementDemo
{
public static void main(String[] args)
{
int a = 10, b = 20, c = 30;
int status = -1;

if (a > b && a > c)


{ status = 1; }
else if (b > c) { status = 2; }
else { status = 3; }

switch (status)
{
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Iteration: while statement
• The while statement is a looping construct control statement
that executes a block of code while a condition is true.
• You can either have a single statement or a block of code
within the while loop.
• The loop will never be executed if the testing expression
evaluates to false.
• The loop condition must be a boolean expression.
• The syntax of the while loop is
while (<loop condition>)
<statements>
Iteration: Java do-while Loop
• The Java do-while loop is used to
iterate a part of the program several
times.
• If the number of iteration is not fixed
and you must have to execute the loop
at least once, it is recommended to
use while loop.
• It is executed at least once because
condition is checked after loop body.
do
{  
//code to be executed  
}while(condition); 
Iteration: for statement
• The Java for loop is used to iterate a part of the program
several times.
• If the number of iteration is fixed, it is recommended to use
for loop.
• There are three types of for loop in java.
▫ Simple For Loop for(initialization;condition;incr/decr){  
//code to be executed  
}  
▫ For-each or Enhanced For Loop for(Type var:array){  
//code to be executed  
▫ Labeled For Loop }  
labelname:  
for(initialization;condition;incr/decr){  
//code to be executed  

Iteration: Java Simple for Loop
• The simple for loop is
same as C/C++.
• We can initialize variable,
check condition and
increment/decrement
value.
public class ForExample 
{  
public static void main(String[] args) 
{  
     for(int i=1;i<=10;i++)
{
        System.out.println(i);  
}
}

Iteration: Java For-each Loop
• The for-each loop is used
to traverse array or
collection in java.
• We don't need to
increment value and use
subscript notation.
• It works on elements
basis not index.
• It returns element one by
one in the defined
variable.
Iteration: Java Labeled For Loop
• We can have name of each
for loop.
• To do so, we use label
before the for loop.
• It is useful if we have
nested for loop so that we
can break/continue specific
for loop.
• Normally, break and
continue keywords breaks/
continues the inner most for
loop only.
Write a Java program to print same character on each line and having character printed in Square shape form.
Write a Java program to print different character on each line and having character increment with each line.
 Write a Java program to print same character on each line and having character increment with each line.
Write a Java program to print same character on each line and having character printed in diagonal form.
Write a Java program to print same character on each line and having character printed in Inverted V Shape form
 Write a Java program to print same character on each line and having character printed in V Shape form.
Classes, fields, methods, constructors, and objects are the building blocks of
object-based Java applications.
An object-based Java application is a Java application whose design is based on
declaring classes, creating objects from them, and designing interactions between
those objects.
Java OOPs Concepts
• Object Oriented Programming is a paradigm that provides
many concepts such as inheritance, data binding,
polymorphism etc.
• Simula is considered as the first object-oriented programming
language.
• The programming paradigm where everything is represented as
an object, is known as truly object-oriented programming
language.
• Smalltalk is considered as the first truly object-oriented
programming language.
Traditional Procedural-Oriented languages
• Traditional procedural-oriented programming languages
(such as C, Fortran, Cobol and Pascal) suffer some
notable drawbacks in creating reusable software
components:
▫ The procedural-oriented programs are made up of functions.
Functions are less reusable.
It is very difficult to copy a function from one program and
reuse in another program because the function is likely to
reference the global variables and other functions.
In other words, functions are not well-encapsulated as a
self-contained reusable unit.
▫ The procedural languages are not suitable of high-level
abstraction for solving real life problems.
For example, C programs uses constructs such as if-else,
for-loop, array, method, pointer, which are low-level and
hard to abstract real problems such as a Customer
Relationship Management (CRM) system or a computer
soccer game.
• The traditional procedural-languages separate the data
structures (variables) and algorithms (functions).
Object-Oriented Programming Languages
• Object-oriented programming (OOP) languages are designed to
overcome these problems.
▫ The basic unit of OOP is a class, which encapsulates both the static
properties and dynamic operations within a "box", and specifies the public
interface for using these boxes.
▫ Since classes are well-encapsulated, it is easier to reuse these classes.
In other words, OOP combines the data structures and algorithms of a software
entity inside the same box.
OOP languages permit higher level of abstraction for solving real-life problems.
▫ The traditional procedural language (such as C and Pascal) forces you to
think in terms of the structure of the computer (e.g. memory bits and
bytes, array, decision, loop) rather than thinking in terms of the problem
you are trying to solve.
▫ The OOP languages (such as Java, C++ and C#) let you think in the
problem space, and use software objects to represent and abstract entities
of the problem space to solve the problem.
Benefits of OOP
• The object-oriented languages focus on components that the user
perceives, with objects as the basic unit.
▫ You figure out all the objects by putting all the data and
operations that describe the user's interaction with the data.
• Object-Oriented technology has many benefits:
▫ Ease in software design 
as you could think in the problem space rather than the machine's bits
and bytes.
You are dealing with high-level concepts and abstractions.
Ease in design leads to more productive software development.
▫ Ease in software maintenance:
object-oriented software are easier to understand, therefore easier to
test, debug, and maintain.
▫ Reusable software:
you don't need to keep re-inventing the wheels and re-write the same
functions for different situations.
The fastest and safest way of developing a new application is to reuse
existing codes - fully tested and proven codes.
Class & Instances
• In Java, a class is a definition of objects of the same kind.
▫ In other words, a class is a blueprint, template, or prototype that defines
and describes the static attributes and dynamic behaviors common to all
objects of the same kind.
• An instance is a realization of a particular item of a class.
▫ In other words, an instance is an instantiation of a class.
▫ All the instances of a class have similar properties, as described in the
class definition.
For example, you can define a class called "Student" and create three instances
of the class "Student" for "Peter", "Paul" and "Pauline".
• The term "object" usually refers to instance.
▫ But it is often used loosely, and may refer to a class or an instance.
A Class is a 3-Compartment Box Encapsulating Data and
Operations
• A class can be visualized as a three-
compartment box, as illustrated:
▫ Name (or identity): identifies the class.
▫ Variables (or attribute, state, field): contains
the static attributes of the class.
▫ Methods (or behaviors, function, operation):
contains the dynamic behaviors of the class.
• In other words, a class encapsulates the static
attributes (data) and dynamic behaviors
(operations that operate on the data) in a
box.
CLASS - Brief Summary
• A class is a programmer-defined, abstract, self-contained,
reusable software entity that mimics a real-world thing.
• A class is a 3-compartment box containing the name,
variables and the methods.
• A class encapsulates the data structures (in variables) and
algorithms (in methods).
• The values of the variables constitute its state. The methods
constitute its behaviors.
• An instance is an instantiation (or realization) of a
particular item of a class.
Class Definition in Java
In Java, we use the keyword class to define a class.
For examples:
Class Naming Convention: 
public class Circle { // class name
1. A class name shall be a noun or a noun phrase made up of
double radius; // variables
several words.
String color;
2. All the words shall be initial-capitalized
double getRadius() { ...... } // methods
(camel-case).
double getArea() { ...... }
}
3. Use a singular noun for class name.
public class SoccerPlayer { // class name
4. Choose a meaningful and self-descriptive classname.
int number; // variables
String name;
int x, y;
For examples, 
void run() { ...... } // methods
SoccerPlayer,
void kickBall() { ...... }
HttpProxyServer, FileInputStream, PrintStream And SocketFactory.
}

The syntax for class definition in Java is:

[ AccessControlModifier] class ClassName {


// Class body contains members (variables and methods)
......
}
Creating Instances of a Class
• To create an instance of a class, you have to:
▫ Declare an instance identifier (instance name) of a particular class.
▫ Construct the instance (i.e., allocate storage for the instance and initialize the
instance) using the "new" operator.
• For examples, suppose that we have a class called Circle, we can create
instances of Circle as follows:
// Declare 3 instances of the class Circle, c1, c2, and c3
Circle c1, c2, c3; // They hold a special value called null

// Construct the instances via new operator


c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");

// You can Declare and Construct in the same statement


Circle c4 = new Circle();

When an instance is declared but not constructed, it holds a special value called null.
Dot (.) Operator
• The variables and methods belonging to a class are formally called member
variables and member methods.
• To reference a member variable or method, you must:
▫ First identify the instance you are interested in, and then,
▫ Use the dot operator (.) to reference the desired member variable or method.
// Suppose that the class Circle has variables radius and color,
// and methods getArea() and getRadius().

// Declare and construct instances c1 and c2 of the class Circle


Circle c1 = new Circle ();
Circle c2 = new Circle ();

// Invoke member methods for the instance c1 via dot operator


System.out.println(c1.getArea());
System.out.println(c1.getRadius());

// Reference member variables for instance c2 via dot operator


c2.radius = 5.0;
c2.color = "blue";
Member Variables
• A member variable has a name (or identifier) and a type; and holds a value of that particular
type (as descried in the earlier chapter).
• Variable Naming Convention: 
▫ A variable name shall be a noun or a noun phrase made up of several words.
▫ The first word is in lowercase and the rest of the words are initial-capitalized (camel-case),
▫ e.g., fontSize, roomNumber, xMax, yMin and xTopLeft.
• The formal syntax for variable definition in Java is:

[ AccessControlModifier] type variableName [= initialValue];

[ AccessControlModifier] type variableName-1 [= initialValue-1] [, type variableName-2 [= initialValue-2]] ... ;

private double radius;

public int length = 1, width = 1;


Member Methods
• A method:
▫ receives arguments from the caller,
▫ performs the operations defined in the method body, and
▫ returns a piece of result (or void) to the caller.
• The syntax for method declaration in Java is as follows:
[ AccessControlModifier] returnType methodName ([ parameterList])
{
// method body or implementation
......
}
// Return the area of this Circle instance
public double getArea()
{
return radius * radius * Math.PI;
}
Method Naming Convention: 
A method name shall be a verb, or a verb phrase made up of several words.
The first word is in lowercase and the rest of the words are initial-capitalized (camel-case).
For example, getArea(), setRadius(), getParameterValues(), hasNext().
Variable name vs. Method name vs. Class name:
A variable name is a noun, denoting an attribute; while a method name is a verb, denoting an action.
They have the same naming convention (the first word in lowercase and the rest are initial-capitalized).
Nevertheless, you can easily distinguish them from the context. Methods take arguments in parentheses (possibly zero arguments
with empty parentheses), but variables do not.
In this writing, methods are denoted with a pair of parentheses, e.g., println(), getArea() for clarity.
On the other hand, class name is a noun beginning with uppercase.
 Constructors
• A constructor is a special method that has the same method name as the class
name.
• A constructor is used to construct and initialize all the member variables.
• To construct a new instance of a class, you need to use a special "new"
operator followed by a call to one of the constructors.
•  Constructor is different from an ordinary method in the following aspects:
▫ The name of the constructor method is the same as the class name.
By classname's convention, it begins with an uppercase (instead of lowercase for ordinary
methods).
▫ Constructor has no return type.
It implicitly returns void. Circle c1 = new Circle();
No return statement is allowed inside the constructor's body. Circle c2 = new Circle(2.0);
▫ Constructor can only be invoked via the "new" operator. Circle c3 = new Circle(3.0, "red");
It can only be used once to initialize the instance constructed.
Once an instance is constructed, you cannot call the constructor anymore.
▫ Constructors are not inherited.
• Default Constructor: A constructor with no parameter is called the default
constructor. It initializes the member variables to their default value. 
Method Overloading 
• Method overloading means that the same method name can have different implementations.
• However, the different implementations must be distinguishable by their parameter list (either the number of
parameters, or the type of parameters, or their order).
public vs. private - Access Control Modifiers
• An access control modifier can be used to control the visibility of a class, or a member variable or
a member method within a class.
• We begin with the following two access control modifiers:
▫ public:
The class/variable/method is accessible and available to all the other objects in the system.
▫ private:
The class/variable/method is accessible and available within this class only.
• For example, in the previous program for Circle definition, the member variable radius is
declared private.
• As the result, radius is accessible inside the Circle class, but NOT in the TestCircle class.
• In other words, you cannot use "c1.radius" to refer to c1's radius in TestCircle.
• Try inserting the statement "System.out.println(c1.radius)" in TestCircle and observe the
error message.
• Try changing radius to public in the Circle class, and re-run the above statement.
• On the other hand, the method getRadius() is declared public in the Circle class. Hence, it can
be invoked in the TestCircle class.
Keyword "this"
• You can use keyword "this" to refer to this instance inside a class definition.
• In the below codes, there are two identifiers called radius -
▫ a member variable of the class and
▫ the method's argument.
• This causes naming conflict.
• To avoid the naming conflict, you could name the method's argument r instead of radius.
• However, radius is more approximate and meaningful in this context.
• Java provides a keyword called this to resolve this naming conflict.
▫ "this.radius" refers to the member variable;
▫ while "radius" resolves to the method's argument.

public class Circle


{
double radius; // Member variable called "radius"

public Circle(double radius)


{
// Method's argument also called "radius"
this.radius = radius; // "radius = radius" does not make sense!
// "this.radius" refers to this instance's member variable //
"radius" resolved to the method's argument.
}
...
}
/* * The Account class models a bank account with a balance. */
public class Account { // The private instance variables
private int accountNumber; private double balance;
// The constructors (overloaded)
public Account(int accountNumber, double balance) {
this.accountNumber = accountNumber; this.balance = balance;
}
public Account(int accountNumber) { // with default balance
this.accountNumber = accountNumber;
this.balance = 0.0; // "this." optional
}
// The public getters/setters for the private instance variables.
// No setter for accountNumber because it is not designed to be changed.
public int getAccountNumber() { return this.accountNumber; // "this." optional }

public double getBalance() { return this.balance; // "this." optional }

public void setBalance(double balance) { this.balance = balance; }


// Add the given amount to the balance.
public void credit(double amount) { balance += amount; }
// Subtract the given amount from balance, if applicable.
public void debit(double amount) {
if (balance < amount) {
System.out.println("amount withdrawn exceeds the current balance!"); }
else { balance -= amount; }
}
// The toString() returns a string description of this instance.
public String toString() {
// Use built-in function System.format() to form a formatted String
return String.format("A/C no:%d, Balance=%.2f", accountNumber, balance);
}
}
/* * The Point class models a 2D point at (x, y). */
public class Point { // The private instance variables
private int x, y;
// The constructors (overloaded)
// The default constructor
public Point() { this.x = 0; this.y = 0; }
public Point(int x, int y) { this.x = x; this.y = y; }
// The public getters and setters
public int getX() { return this.x; }
public void setX(int x) { this.x = x; }
public int getY() { return this.y; }
public void setY(int y) { this.y = y; }
// Return "(x,y)"
public String toString() { return "(" + this.x + "," + this.y + ")"; }
// Return a 2-element int array containing x and y.
public int[] getXY() {
int[] results = new int[2];
results[0] = this.x; results[1] = this.y;
return results; }
// Set both x and y.
public void setXY(int x, int y) { this.x = x; this.y = y; }
// Return the distance from this instance to the given point at (x,y).
public double distance(int x, int y) {
int xDiff = this.x - x; int yDiff = this.y - y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff); }
// Return the distance from this instance to the given Point instance (called another). public double distance(Point another) {
int xDiff = this.x - another.x; int yDiff = this.y - another.y;
return Math.sqrt(xDiff*xDiff + yDiff*yDiff); }
// Return the distance from this instance to (0,0).
public double distance() { return Math.sqrt(this.x*this.x + this.y*this.y); }
}
/* * A Test Driver for the Point class. */
public class TestPoint {
public static void main(String[] args)
{
// Test constructors and toString()
Point p1 = new Point(1, 2);
System.out.println(p1);
// toString()
Point p2 = new Point();
// default constructor
System.out.println(p2);
// Test Setters and Getters
p1.setX(3);
p1.setY(4);
System.out.println(p1);
// run toString() to inspect the modified instance
System.out.println("X is: " + p1.getX());
System.out.println("Y is: " + p1.getY());
// Test setXY() and getXY()
p1.setXY(5, 6);
System.out.println(p1);
// toString()
System.out.println("X is: " + p1.getXY()[0]);
System.out.println("Y is: " + p1.getXY()[1]);
// Test the 3 overloaded versions of distance()
p2.setXY(10, 11);
System.out.printf("Distance is: %.2f%n", p1.distance(10, 11));
System.out.printf("Distance is: %.2f%n", p1.distance(p2));
System.out.printf("Distance is: %.2f%n", p2.distance(p1));
System.out.printf("Distance is: %.2f%n", p1.distance());
}
/* * The student class models a student having courses and grades. */
public class Student { // The private instance variables
private String name; private String address;
// The courses taken and grades for the courses are kept in 2 parallel arrays
private String[] courses; private int[] grades; // [0, 100]
private int numCourses; // Number of courses taken so far
private static final int MAX_COURSES = 30; // Maximum number of courses taken by student
// Constructor
public Student(String name, String address) {
this.name = name; this.address = address;
courses = new String[MAX_COURSES];
grades = new int[MAX_COURSES]; // allocate arrays
numCourses = 0; // no courses so far
}
// The public getters and setters. No setter for name as it is not designed to be changed.
public String getName() { return this.name; }
public String getAddress() { return this.address; }
public void setAddress(String address) { this.address = address; }
// Describe this instance
public String toString() { return name + "(" + address + ")"; }
// Add a course and grade
public void addCourseGrade(String course, int grade) {
courses[numCourses] = course; grades[numCourses] = grade;
++numCourses; }
// Print all courses taken and their grades
public void printGrades() {
System.out.print(name);
for (int i = 0; i < numCourses; ++i) {
System.out.print(" " + courses[i] + ":" + grades[i]); }
System.out.println(); }
// Compute the average grade
public double getAverageGrade() {
int sum = 0;
for (int i = 0; i < numCourses; ++i) { sum += grades[i]; }
return (double)sum/numCourses; }
}
/* * A test driver program for the Student class. */
public class TestStudent {
public static void main(String[] args)
{
// Test constructor and toString()
Student ahTeck = new Student("Tan Ah Teck", "1 Happy Ave");
System.out.println(ahTeck);
// toString()
// Test Setters and Getters
ahTeck.setAddress("8 Kg Java");
System.out.println(ahTeck);
// run toString() to inspect the modified instance
System.out.println(ahTeck.getName());
System.out.println(ahTeck.getAddress());
// Test addCourseGrade(), printGrades() and getAverageGrade()
ahTeck.addCourseGrade("IM101", 89);
ahTeck.addCourseGrade("IM102", 57);
ahTeck.addCourseGrade("IM103", 96);
ahTeck.printGrades();
System.out.printf("The average grade is %.2f%n", ahTeck.getAverageGrade());
}
}
Inheritance
• In OOP, we often organize classes in hierarchy to avoid duplication and reduce
redundancy.
• The classes in the lower hierarchy inherit all the variables (static attributes) and
methods (dynamic behaviors) from the higher hierarchies.
• A class in the lower hierarchy is called a subclass 
(or derived, child, extended class).
• A class in the upper hierarchy is called a superclass 
(or base, parent class).
• By pulling out all the common variables and methods into the superclasses, and leave
the specialized variables and methods in the subclasses, redundancy can be greatly
reduced or eliminated as these common variables and methods do not need to be
repeated in all the subclasses. 

class Goalkeeper extends SoccerPlayer


{......}

class MyApplet extends java.applet.Applet {.....}

class Cylinder extends Circle


{......}
Types of inheritance in java
class A
{  
void msg()
{System.out.println("Hello");}  
}  
class B
{  
void msg()
{System.out.println("Welcome");}  
}  
class C extends A,B //suppose if it were  
{
Public Static void main(String args[])
{  
    C obj=new C();  
obj.msg();
//Now which msg() method would be invoked?  }  
}  
public class Circle
{

// private instance variables


private double radius; private String color;
// Constructors
public Circle()
{ this.radius = 1.0; this.color = "red"; }
public Circle(double radius)
{ this.radius = radius; this.color = "red"; }
public Circle(double radius, String color)
{ this.radius = radius; this.color = color; }
// Getters and Setters
public double getRadius()
{ return this.radius; }
public String getColor()
{ return this.color; }
public void setRadius(double radius)
{ this.radius = radius; }
public void setColor(String color)
{ this.color = color; }
// Describle itself
public String toString()
{
return "Circle[radius=" + radius + ",color=" + color + "]";
}
// Return the area of this Circle
public double getArea()
{
return radius * radius * Math.PI;
}
}
/* * A Cylinder is a Circle plus a height. */
public class Cylinder extends Circle {
// private instance variable
private double height;
// Constructors
public Cylinder() {
super(); // invoke superclass' constructor Circle()
this.height = 1.0;
}
public Cylinder(double height) {
super(); // invoke superclass' constructor Circle()
this.height = height;
}
public Cylinder(double height, double radius) {
super(radius); // invoke superclass' constructor Circle(radius)
this.height = height;
}
public Cylinder(double height, double radius, String color)
{
super(radius, color); // invoke superclass' constructor Circle(radius, color)
this.height = height;
}
// Getter and Setter
public double getHeight()
{ return this.height; }
public void setHeight(double height)
{ this.height = height; }
// Return the volume of this Cylinder
public double getVolume() { return getArea()*height; // Use Circle's getArea() }
// Describle itself
public String toString() { return "This is a Cylinder"; // to be refined later }
}
/* * A test driver for the Cylinder class. */
public class TestCylinder
{
public static void main(String[] args)
{
Cylinder cy1 = new Cylinder();

System.out.println("Radius is " + cy1.getRadius() +


" Height is " + cy1.getHeight() +
" Color is " + cy1.getColor() +
" Base area is " + cy1.getArea() +
" Volume is " + cy1.getVolume());

Cylinder cy2 = new Cylinder(5.0, 2.0);

System.out.println("Radius is " + cy2.getRadius() +


" Height is " + cy2.getHeight() +
" Color is " + cy2.getColor() +
" Base area is " + cy2.getArea() +
" Volume is " + cy2.getVolume());
}
}
 Method Overriding & Variable Hiding
• The "@Override" is known as annotation (introduced in JDK 1.5),
which asks compiler to check whether there is such a method in the
superclass to be overridden.
• This helps greatly if you misspell the name of the method to be
overridden.
▫ For example, suppose that you wish to override method toString() in a
subclass.
If @Override is not used and toString() is misspelled as TOString(), it will
be treated as a new method in the subclass, instead of overriding the superclass.
If @Override is used, the compiler will signal an error.
• @Override annotation is optional, but certainly nice to have.
• Annotations are not programming constructs.
• They have no effect on the program output.
• It is only used by the compiler, discarded after compilation, and not
used by the runtime.
Keyword "super"
• The keyword super allows the subclass to access superclass'
methods and variables within the subclass' definition.
• For example, super() and super(argumentList)can be used
invoke the superclass’ constructor.
• If the subclass overrides a method inherited from its
superclass, says getArea(), you can use super.
getArea() to invoke the superclass' version within the
subclass definition.
• Similarly, if your subclass hides one of the superclass'
variable, you can use super.variableName to refer to the
hidden variable within the subclass definition.
Common Root Class - java.lang.Object
• Java adopts a so-called common-root approach.
• All Java classes are derived from a common root
class called java.lang.Object.
• This Object class defines and implements the common
behaviors that are required of all the Java objects running
under the JRE.
• These common behaviors enable the implementation of
features such as multi-threading and garbage collector.
/* * Superclass Person has name and address. */
public class Person
{
// private instance variables
private String name, address;
// Constructor
public Person(String name, String address)
{
this.name = name;
this.address = address;
}
// Getters and Setters
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
// Describle itself
public String toString()
{
return name + "(" + address + ")";
}
}
/* * The Student class, subclass of Person. */
public class Student extends Person {
// private instance variables
private int numCourses;
// number of courses taken so far
private String[] courses;
// course codes
private int[] grades;
// grade for the corresponding course codes
private static final int MAX_COURSES = 30;
// maximum number of courses
// Constructor
public Student(String name, String address)
{ super(name, address); numCourses = 0; courses = new String[MAX_COURSES];
grades = new int[MAX_COURSES]; }
// Describe itself
@Override
public String toString() { return "Student: " + super.toString(); }
// Add a course and its grade - No validation in this method
public void addCourseGrade(String course, int grade)
{ courses[numCourses] = course; grades[numCourses] = grade; ++numCourses; }
// Print all courses taken and their grade
public void printGrades()
{ System.out.print(this);
for (int i = 0; i < numCourses; ++i)
{ System.out.print(" " + courses[i] + ":" + grades[i]); }
System.out.println(); }
// Compute the average grade
public double getAverageGrade()
{ int sum = 0;
for (int i = 0; i < numCourses; i++ ) { sum += grades[i]; }
return (double)sum/numCourses; } }
/* * The Teacher class, subclass of Person. */
public class Teacher extends Person {
private int numCourses; // private instance variables
private String[] courses; // number of courses taught currently
private static final int MAX_COURSES = 5; // course codes
// maximum courses - Constructor
public Teacher(String name, String address)
{ super(name, address); numCourses = 0; courses = new String[MAX_COURSES]; }
// Describe itself
@Override
public String toString() { return "Teacher: " + super.toString(); }
// Return false if the course already existed
public boolean addCourse(String course) {
// Check if the course already in the course list
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) return false; }
courses[numCourses] = course; numCourses++; return true; }
// Return false if the course cannot be found in the course list
public boolean removeCourse(String course)
{ boolean found = false;
// Look for the course index
int courseIndex = -1;
// need to initialize
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) { courseIndex = i; found = true; break; } }
if (found) {
// Remove the course and re-arrange for courses array
for (int i = courseIndex; i < numCourses-1; i++)
{ courses[i] = courses[i+1]; } numCourses--; return true; }
else { return false; }
}
/* * A test driver for Person and its subclasses. */
public class TestPerson
{
public static void main(String[] args)
{ /* Test Student class */
Student s1 = new Student("Tan Ah Teck", "1 Happy Ave");
s1.addCourseGrade("IM101", 97);
s1.addCourseGrade("IM102", 68);
s1.printGrades();
System.out.println("Average is " + s1.getAverageGrade());
/* Test Teacher class */
Teacher t1 = new Teacher("Paul Tan", "8 sunset way");
System.out.println(t1); String[] courses = {"IM101", "IM102", "IM101"};
for (String course: courses)
{
if (t1.addCourse(course))
{
System.out.println(course + " added.");
}
else
{
System.out.println(course + " cannot be added.");
}
}
for (String course: courses)
{
if (t1.removeCourse(course))
{
System.out.println(course + " removed.");
}
else
{
System.out.println(course + " cannot be removed.");
}
}
}
}
 The "instanceof" Operator
• Java provides a binary operator called instanceof which returns true if an object is an
instance of a particular class.
• The syntax is as follows:
The abstract Method and abstract class
• An abstract method is a method with only
signature (i.e., the method name, the list of
arguments and the return type) without
implementation (i.e., the method’s body).
• You use the keyword abstract to declare
an abstract method.
• For example, in the Shape class, we can
declare abstract methods getArea(), draw()
, etc.
• Implementation of these methods is NOT
possible in the Shape class, as the actual
shape is not yet known. (How to compute the
area if the shape is not known?)
• Implementation of these abstract methods will
be provided later once the actual shape is
known.
• These abstract methods cannot be invoked
because they have no implementation.
• An abstract class is incomplete in its definition, since the
implementation of its abstract methods is missing.
• Therefore, an abstract class cannot be instantiated.
• In other words, you cannot create instances from an abstract class
(otherwise, you will have an incomplete instance with missing
method's body).
• To use an abstract class, you have to derive a subclass from
the abstract class.
• In the derived subclass, you have to override the abstract methods and
provide implementation to all the abstract methods.
• The subclass derived is now complete, and can be instantiated.
• (If a subclass does not provide implementation to all
the abstract methods of the superclass, the subclass remains abstract.)
/* * This abstract superclass Shape contains an abstract method * getArea(), to be
implemented by its subclasses. */

abstract public class Shape


{
// Private member variable
private String color;

// Constructor
public Shape (String color)
{
this.color = color;
}

@Override
public String toString()
{
return "Shape of color=\"" + color + "\"";
}
// All Shape subclasses must implement a method called getArea()
abstract public double getArea();
}
public class TestShape
{
public static void main(String[] args)
{
Shape s1 = new Rectangle("red", 4, 5);
System.out.println(s1);
System.out.println("Area is " + s1.getArea());
Shape s2 = new Triangle("blue", 4, 5);
System.out.println(s2);
System.out.println("Area is " + s2.getArea());
// Cannot create instance of an abstract class
Shape s3 = new Shape("green"); // Compilation Error!!
}
}
In summary, an abstract class provides a template for further development.

The purpose of an abstract class is to provide a common interface (or protocol, or contract, or understanding, or naming
convention) to all its subclasses.

Notes:
•An abstract method cannot be declared final, as final method cannot be overridden.
An abstract method, on the other hand, must be overridden in a descendant before it can be used.
•An abstract method cannot be private (which generates a compilation error).
This is because private method are not visible to the subclass and thus cannot be overridden.
The Java's interface
•  Java interface is a 100% abstract superclass which define a set of methods its
subclasses must support.
• An interface contains only public abstract methods (methods with signature and
no implementation) and possibly constants (public static final variables).
• You have to use the keyword "interface" to define an interface (instead of
keyword "class" for normal classes).
• The keyword public and abstract are not needed for its abstract methods as they
are mandatory.
• Similar to an abstract superclass, an interface cannot be instantiated.
• You have to create a "subclass" that implements an interface, and provide
the actual implementation of all the abstract methods.
• Unlike a normal class, where you use the keyword "extends" to derive a
subclass.
• For interface, we use the keyword "implements" to derive a subclass.
• An interface is a contract for what the classes can do.
▫ It, however, does not specify how the classes should do it.
• An interface provides a form, a protocol, a standard, a contract, a specification, a set of rules,
an interface, for all objects that implement it.
• It is a specification and rules that any object implementing it agrees to follow.
• In Java, abstract class and interface are used to separate the public interface of a class from
its implementation so as to allow the programmer to program at the interface instead of the
various implementation.
• Interface Naming Convention: 
▫ Use an adjective (typically ends with "able") consisting of one or more words.
Each word shall be initial capitalized (camel-case).
For example, 
Serializable, Extenalizable, Movable, Clonable, Runnable, etc.
• Which is a better design: interface or abstract superclass?
▫ There is no clear answer.
• Use abstract superclass if there is a clear class hierarchy.
• Abstract class can contain partial implementation (such as instance
variables and methods).
• Interface cannot contain any implementation, but merely defines
the behaviors.
• As an example, Java's thread can be built using
interface Runnable or superclass Thread.
 "final" Class/Variable/Method
• You can declare a class, a variable or a method to be final.
• A final class cannot be sub-classed (or extended).
• A final method cannot be overridden in the subclass.
• A final variable cannot be re-assigned a new value.
▫ A final variable of primitive type is a constant, whose value cannot be changed. 
• Constant Naming Convention: 
▫ a noun, or noun phrase made up of several words.
▫ All words are in uppercase separated by underscore '_'.
For examples, MIN_WIDTH, MAX_VALUE, PI, RED.
• final vs. abstract: 
▫ final is opposite to abstract.
▫ A final class cannot be extended; while an abstract class must be extended and the
extended class can then be instantiated.
▫ A final method cannot be overridden; while an abstract method must be overridden
to complete its implementation.
▫ [abstract modifier is applicable to class and method only.]
Command-Line Arguments
• Java's main(String[] args) method takes an argument: String[] args, i.e.,
a String array named args.
• This is known as "command-line arguments", which corresponds to the augments
provided by the user when the java program is invoked.
• For example, a Java program calledArithmetic could be invoked with additional
command-line arguments as follows (in a "cmd" shell):
java Arithmetic 12 3456 +
• Each argument, i.e., "12", "3456" and "+", is a String.
• Java runtime packs all the arguments into a String array and passes into
the main() method as args.
• For this example, args has the following properties:

You might also like