You are on page 1of 95

Java Programming Essentials

Lecture 07
Course Instructor: Dr Usman Nasir
Course Code: SE331
Spring 2020

Y2020Ver 1.0
Java Class, Association & Inheritance
public class Bicycle {// in file: Bicycle.java

private int speed = 0;


private int gear = 1;

public Bicycle(int speed, int gear) {


this.speed = speed;
this.gear = gear;
}
public void changeGear(int newValue) { gear = newValue; }
public void speedUp(int increment) { speed = speed + increment; }
public void applyBrakes(int decrement) { speed = speed - decrement;}

public String currentState() { return " speed:" + speed + " gear:" + gear; }

}//end of class
public class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on the objects


bike1.speedUp(10);
bike1.changeGear(2);
System.out.println(bike1.currentState());

bike2.speedUp(10);
Output:
bike2.changeGear(2); speed:10 gear:2
bike2.applyBrakes(5); speed:5 gear:3
bike2.changeGear(3);
System.out.println(bike2.currentState());
}
}
Association
— BicycleDemo uses objects of Bicycle
— This makes BicycleDemo has-a relationship with Bicycle

public static void main(String[] args) {


// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
Inheritance in Java
— In the Java programming language, each class can
have one direct superclass, and each superclass has
the potential for an unlimited number of subclasses.
— The extends keyword is used at the beginning of class
declaration
— Example:
public class MountainBike extends Bicycle {
public MountainBike() {
super();
}
}
public class BicycleDemoTwo {
public static void main(String[] args) {
// Create two different MountainBike objects
Bicycle mtbike1 = new MountainBike();// Superclass reference can store
// subclasses’s object
MountainBike mtbike2 = new MountainBike();

// Invoke methods on the objects


mtbike1.speedUp(20);
mtbike1.changeGear(2);
System.out.println(mtbike1.currentState());

mtbike2.speedUp(100);
mtbike2.applyBrakes(5);
System.out.println(mtbike2.currentState()); Output:
}
} speed:20 gear:2
speed:95 gear:1
Java Interface
Java Interface
— An interface is a reference type, similar to a class but
it can contain only constants and method signatures

— Interfaces cannot be instantiated


— Only be implemented by classes or extended by other
interfaces.

— Unless the class that implements the interface is an abstract


class, all the methods of the interface need to be defined in
the class.
— An interface is written in a file with a .java
extension, with the name of the interface matching
the name of the file.
— No need for constructors.
— All of the methods should have signatures only.
— An interface cannot contain instance variables.
— only static and final variables are allowed.
— An interface is not extended by a class; it is implemented
by a class.
— An interface can extend multiple interfaces
public interface Shape {
public void giveArea();
}

// Rectangle
public class Rectangle implements Shape {
public void giveArea( )
{//implementation of giveArea( )
}
}//
Will this code compile?
public interface Shape {
public void hello();
public void giveArea();
}

// Rectangle
NO, why
public class Rectangle implements Shape {
public void giveArea(){}
}
Will this code compile?
public interface Shape {
private int area = 0;
public void giveArea();
}

// Rectangle
NO, why
public class Rectangle implements Shape {
public void giveArea( ){ };
}
— An instance of class that implements an interface can
stored in a reference of that interface.
— Example:
public interface Greeter {
public void sayHello( );
}
public class Face implements Greeter {
public void sayHello( ) { System.out.println(“Hello”); }
}

Greeter myObj;//myObj is a reference of Greeter


myObj= new Face ( ); //new Face() creates an object of Face
myObj.sayHello( );
Find the error!!!
public interface Shape {
public void giveArea();
}
You cannot create instances of
a Java interface by itself
public class Test{
public static void main(String[]args){
Shape myShape= new Shape();
myShape.giveArea();
}
}
Extending Interfaces
— An interface can extend another interface in the
same way that a class can extend another class.
— The extends keyword is used to extend an interface.
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public class Game implements Football {
public void setHomeTeam(String name){ };
public void setVisitingTeam(String name){};

public void homeTeamScored(int points){};


public void visitingTeamScored(int points){};
public void endOfQuarter(int quarter){};
}
Implementing Multiple Interfaces
— A class can implement multiple interfaces

— Example:
//public interface Event{ }
//public interface Sports{ }

public class Game implements Sports, Event


// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
}

// Filename: Football.java
public interface Football {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
}
public class Game implements Sports, Football {
public void setHomeTeam(String name){ };

public void homeTeamScored(int points){};


public void visitingTeamScored(int points){};
}
Tagging Interfaces
— Tagging interface is an interface with no methods
— There are two basic design purposes of tagging
interfaces
— Creates a common parent
— Adds a data type to a class

— The most common use of extending interfaces


occurs when the parent interface does not contain
any methods.
Default method in interface
— Java has introduced a new default method to java
interface in JDK 8 and above.
— This allows us to give a default implementation to
our interface methods.
— If any class implements default method then this
implementation hides interface default
implementation.
— we use default keyword before method.
public interface IHumanBodyPart {

public void oldExistingMethod();

default public void newDefaultMethod() {


System.out.println("Default method in interface
JDK 8");
}
}
public class Face implements IHumanBodyPart{
@Override
public void oldExistingMethod()
{
System.out.println("oldExistingMethod in Face");
}

}//end of class
public class Hand implements IHumanBodyPart{
@Override
public void oldExistingMethod(){
System.out.println("oldExistingMethod in
Hand");
}
@Override
public void newDefaultMethod() {
System.out.println("newDefaultMethod
overridden in Hand");
}}//end of class
public static void main(String[] args) {
IHumanBodyPart reference= new Face();
reference.oldExistingMethod();
reference.newDefaultMethod();
IHumanBodyPart referenceTwo= new Hand();
referenceTwo.oldExistingMethod();
referenceTwo.newDefaultMethod();
System.out.println("__________________");

Face referenceOfFace= new Face();


referenceOfFace.newDefaultMethod();
}//end of main
Output
oldExistingMethod in Face
Default method in interface JDK 8
__________________
oldExistingMethod in Hand
newDefaultMethod overridden in Hand
__________________
Default method in interface JDK 8
Abstract Class
Abstract Class
— An Abstract class is used to specify the default
functionality of an object and let its sub-classes to
explicitly implement the functionality.
/* An abstract class StringedInstrument */
public abstract class StringedInstrument {
protected String name;
protected int numberOfStrings;

abstract public void play();


public void hello(){ };//normal
method
}
public class ElectricGuitar extends StringedInstrument {
public ElectricGuitar(String aName, int
numberOfStrings) {
super(); this.name = aName;
this.numberOfStrings = numberOfStrings;
}
@Override
public void play() {
System.out.println("An electric " + numberOfStrings
+ " string, " + name + " is playing!!");
}
}
public class TestElectricGuitar {

public static void main(String[] args) {


ElectricGuitar testOne=new ElectricGuitar("Fender",5);
ElectricGuitar testTwo=new ElectricGuitar("Gibson",6);
StringedInstrument testThree= new ElectricGuitar("PRS",5);
testOne.play();
testTwo.play(); Output:
testThree.play(); An electric 5 string, Fender is playing!!
An electric 6 string, Gibson is playing!!
} An electric 5 string, PRS is playing!!
}
Abstract Class vs. Interface
— All methods in an interface are implicitly abstract.
— On the other hand, an abstract class may contain both abstract
and non-abstract methods.
— A class may implement a number of Interfaces, but can
extend only one Abstract class.
— Abstract classes can implement interfaces without even
providing the implementation of interface methods (but
the class extending such need to give implementations).
— Variables declared in a Java interface is by default final.
An abstract class may contain non-final variables.
— Data members of a Java interface are public by
default.
— A member of an abstract class can either be private,
protected or public.
— An interface is absolutely abstract and cannot be
instantiated.
— An abstract class also cannot be instantiated, but can
be invoked if it contains a main method.
Think!!!
public interface Sports {
public void setHomeTeam(String name); }
public abstract class Football implements Sports{
abstract public void homeTeamScored(int goal); }
public class RealMadrid extends Football{
@Override
public void homeTeamScored(int goals)
{};
public void visitingTeamScored(int points){};
}//will this compile??
public class RealMadrid extends Football{
@Override
public void setHomeTeam(String name){ }
@Override
public void homeTeamScored(int myGoals)
{}
public void visitingTeamScored(int points){}
}
//will this compile??
Final Methods
— In Java using Final keyword at the start of its method
declaration will prevent it from being overridden.
— It will give a compilation error.
public class Shape {
final void showattributes() {
System.out.println("Inside class shape "); }
}

public class Rectangle extends Shape {


// A subclass which inherits from Shape
void showattributes() { System.out.println("Inside class
rectangle"); }
} //showattributes() cannot be overridden
Final Class
— Using keyword final with class will prevent
inheritance by making a class final.
— When a class is declared as final, its methods also
become final.
— An abstract class cannot be declared as final because
an abstract class is incomplete and its subclasses need
to provide the implementation.
/* A final class Shape */
public final class Shape {
final void showattributes() {
System.out.println("Inside class shape "); }
}

public class Rectangle extends Shape {


/* A subclass which extends for shape */
}
ArrayList
Arrays
— Java programs keep data in lists using Arrays
— Java Array
— String[ ] list = new String[3];
Or
— String list [] = new String[3]; //old school

— Cell of an array is a place where data may be stored. The cells


are numbered from 0 up to one less than the length of the
array.
— An element is the data that has been placed in a cell.
— Once an array object has been constructed number of cells
does not change.
ArrayList class
— Java includes the ArrayList class that works as a list of
ordered element.
— ArrayList implements List interface, thus an ordered
collection.
— The ArrayList will automatically increase to
accommodate elements.
— ArrayList operations are slightly slower than array
operations.
— In an ArrayList only object references can be stored not
primitive data (int or double).
import java.util.* ;
public class ArrayListExample{
public static void main ( String[ ] args) {
// Create an ArrayList that holds references to String
ArrayList<String> names = new ArrayList<String>();
// Add three String references
names.add("Malik"); names.add("Bashir"); names.add("Zameer");
// Access and print out the three String Objects
System.out.println(“Element 0: " + names.get(0) );
System.out.println(”Element 1: " + names.get(1) );
System.out.println(”Element 2: " + names.get(2) );
}
Element 0: Malik
} Element 1: Bashir
Element 2: Zameer
— ArrayList is a generic type thus require the type of
object to construct.
— The type the object is declared inside angle brackets:
— ArrayList<E> myArray = new ArrayList<E>(); //
myArray is a reference to an ArrayList that holds references
to objects of type E
— ArrayList<Integer> list = new ArrayList<Integer>();
— ArrayList <Customer> c_list = new
ArrayList<Customer>();
— Must import the java.util package to use ArrayList.
public class Customer{
public Customer(int aId, String aName){ customerId=aId;
customerName=aName; }
public String toString() { return "Customer: id: "+customerId+"
"+customerName; }
private int customerId; private String customerName;}
___________________________________________________________
import java.util.*;
public class Example2{
public static void main ( String[ ] args) {
List <Customer> listCustomer = new ArrayList<Customer>();
listCustomer.add(new Customer(1,"Ali"));
Customer cust2=new Customer(2,"Sameer"); Example2
listCustomer.add(1,cust2); Customer: id: 2 Sameer
System.out.println("Example2 \n”+listCustomer.get(1));
}}
ArrayList Capacity and Size
— You can declare an initial capacity of ArralyList in
constructor
— ArrayList<String> names = new ArrayList<String>(5);
— Initial capacity by default is 10
— Capacity in not equals to size
— In ArrayList size is determined by number of element in the
arraylist object.
— Arraylist.size() returns the size (number of element in any
array
— ArrayList index runs from 0 to size-1
import java.util.* ;
public class ExampleThree{
public static void main ( String [] args) {
ArrayList<String> names = new ArrayList<String>(22);
// Capacity starts at 22, but size starts at 0
System.out.println("initial size: " + names.size() );
// Add three String references
names.add("Ali"); names.add("Bashir"); names.add("Careem");
System.out.println("new size: " + names.size() );
// Access and print out the Objects
initial size: 0
for ( int j=0; j<names.size(); j++ )
new size: 3
System.out.println("element " element 0: Ali
+ j + ": " + names.get(j) ); element 1: Bashir
} element 2: Careem
}
— add(E elt) method adds the element to the end of an
ArrayList.
— set( int index, E elt ) sets an element to the given
index.
— The index should be in the range 0 to size-1.
— Method can not skip over empty cells when it adds an
element, list can not have gaps in it.
What will be the output?
import java.util.* ;
public class ExampleFour {
public static void main ( String[ ] args) {
List<String> names = new ArrayList<>();//only in JDK8
names.add("Kareem");names.add("Bashir"); names.add("Nazir");
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
names.set(0, "Zubair");
System.out.println(“----------”);
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
}}
element 0: Kareem
element 1: Bashir
element 2: Nazir
----------
element 0: Zubair
element 1: Bashir
element 2: Nazir
What will be the output?
public class ExampleFour {
public static void main ( String[] args) {
ArrayList<String> names = new ArrayList<String>(5);
names.add("Kareem");names.add("Bashir");
names.add("Nazir");
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
names.set(4, "Zubair");
System.out.println("----------");
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
}}
element 0: Kareem
element 1: Bashir
element 2: Nazir

java.lang.IndexOutOfBoundsException: Index: 4, Size: 3


at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.set(ArrayList.java:444)
— To remove an element from a list we use the
remove(int index) method.
— It removes an element without leaving a hole and other
object are moved to fill the gap.
— boolean isEmpty() is used to check if an ArrayList has
elements.
— The value null in a cell counts as data. An empty cell is not
the same as a cell that contains null.
— To remove all elements from a list, use
— void clear()
What will be the output?
import java.util.* ;
public class ExampleFour {
public static void main ( String[ ] args) {
ArrayList<String> names = new ArrayList<String>();
names.add("Kareem");names.add("Bashir"); names.add("Nazir");
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
names.remove(1);
System.out.println(“--------------”);
for ( int j=0; j<names.size(); j++ )
System.out.println("element " + j + ": " + names.get(j) );
}}
Output!!
element 0: Kareem
element 1: Bashir
element 2: Nazir
----------
element 0: Kareem
element 1: Nazir
What will this code print?
public class NullExample {
public static void main ( String[] args){
ArrayList<String> nullList = new ArrayList<String>();
System.out.println( "Case A:" + nullList.isEmpty() ); Case A: true

nullList.add( null );
System.out.println( "Case B:" + nullList.isEmpty() ); Case B: false
nullList.remove( 0 );
System.out.println( "Case C:" + nullList.isEmpty() ); Case C: true
nullList.add( "" );
System.out.println( "Case D:" + nullList.isEmpty() ); Case D: false
nullList.clear( );
System.out.println( "Case E:" + nullList.isEmpty() ); }} Case E: true
Searching for an Element
— Linear search within an ArrayList starts from the
first element.
— A method int indexOf(Object element) does linear search
— int indexOf(Object element) returns the index of the first
occurrence of element
— returns -1 if element is not found.

System.out.println( “Item Index: " + list.indexOf("Ali" ));


ArrayList & Iterator
— A loop can be used to access the elements of an
ArrayList one by one
— Another option is to use an Iterator object.
— To get an Iterator object, use this method of ArrayList:
Iterator<E> iterator() // Returns an iterator

— Methods in Iterator
— boolean hasNext() // Returns true if not all elements have
been visited
— E next() // Returns the next element of the list,
— void remove() // Remove from the list the element just
returned by next()
import java.util.* ;
public class IteratorExample{
public static void main ( String[ ] args) {
ArrayList<String> names = new ArrayList<String>();
names.add( “Javaid Ch" ); names.add( "Dr Moeed" );
names.add( "Waseem Badami" ); names.add( "Kashif Abbasi" );
names.add( "Sana Bucha" );
Element: Javaid Ch
// Create an iterator for the list Element: Dr Moeed
Iterator<String> iter = names.iterator(); Element: Waseem Badami
// Use the iterator to visit each element Element: Kashif Abbasi
while ( iter.hasNext() ) Element: Sana Bucha
System.out.println("Element: "+ iter.next() );
}
}
— The enhanced for loop (a.k.a "for each" loop) can be
used with any class that implements the Iterable
interface, such as ArrayList.
public class IteratorExampleTwo{
public static void main ( String[] args) {
ArrayList<String> names = new ArrayList<String>();
names.add( "Gen. Aziz" ); names.add( ”Gen. Moeed" );
names.add( ”Lt. Badami" ); names.add( ”Col. Kashif Abbasi" );
int i=0;
for ( String nm : names ){
System.out.println("Element: "+i+" "+ nm );
i++;
}
Element: 0 Gen. Aziz
}
Element: 1 Gen. Moeed
} Element: 2 Lt Badami
Element: 3 Col Kashif Abbasi
Using Wrapper classes with ArrayList
— To put an int into an ArrayList we put the int inside of an
Integer object (Integer is a wrapper class).

public class WrapperExample{


public static void main ( String[] args) {
ArrayList<Integer> data = new ArrayList<Integer>();
data.add( new Integer(10) );
data.add( new Integer(33) );
data.add( new Integer(170) );
for ( Integer val : data )
System.out.print( val + " " ); 10 33 170
}
}
Set & Map
Hash Set class
— This creates a collections of object and uses a hash
table for storage
— Execution time of basic operations is constant
— No order is maintained
— HashSet does not allow duplicates insertion of
elements
Example: HashSet
import java.util.HashSet;

public class FindDups {


public static void main(String args[]) {
HashSet set = new HashSet();

for (int i=0; i < args.length; i++) {


if (! set.add(args[i])) {
System.out.println("Duplicate detected: " + args[i]);
}
}
System.out.println(set.size() + " distinct words detected: " + set);
}
}
Running the Example
C:\> java FindDups i came i saw i left
Duplicate word detected: i
Duplicate word detected: i
4 distinct words detected: [came, i, left, saw]
Maps
— Map stores associations between keys and values
— Given a key you finds a value
— Key/values are objects
— Keys are unique
— Maps are not collections, but provide a collections
view (act like a collection in java with similar
methods)
Map: Methods
— Object get(Object key)
— Returns the value to which this map maps the specified
key.
— Object put(Object key, Object value)
— Associates the specified value with the specified key in this
map (optional operation).
— Object remove (Object key)
— Removes the mapping for this key from this map if it is
present (optional operation).
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(10, "Ali");
map.put(12, "Jamal");
map.put(12, "Asad");//What should happen to duplicates
map.put(14, null);
System.out.println("Size of map is:- " + map.size());
System.out.println(map);
if (map.containsKey(10)) {System.out.println("value for key \"10\" is:- " +
map.get(10)); }
map.clear(); OUTPUT
System.out.println(map); } Size of map is:- 3
}//end of class {10=Ali, 12=Asad, 14=null}
value for key "10" is:- Ali
{}
Hashtable
— Hashtable use key and value to store data like maps
— Both HashMap and Hashtable use hashing technique
to store unique keys.
— Hashtable doesn't allow any null key or value.
— HashMap does allows one null key and multiple null
values.
— Hashtable is legacy code
Example: using Hashtable
public class MyStudent {
private String rollNumber;
private String studentName;

public MyStudent(String rollNumber, String studentName, int age) {


this.rollNumber = rollNumber;
this.studentName = studentName;
}
@Override
public String toString(){
return this.rollNumber+" "+this.studentName;
}
}//end of class
import java.util.*;
public class StudentHashTable {
public static void main(String args[ ]) {
Hashtable<String, MyStudent> hashTbl = new Hashtable<>();

// Input the values


MyStudent one = new MyStudent("1","Ali");
hashTbl.put ("1", one);

hashTbl.put ("2", new MyStudent("2","Saleem"));


hashTbl.put ("3", new MyStudent("z","Zulu"));

// Printing the Hashtable


System.out.println (hashTbl); }
} Output:
{3=z Zulu, 2=2 Saleem, 1=1 Ali}
Comparing objects
— Java super class java.lang.Object provides two
important methods for comparing objects:
— equals( )
— hashcode( )
— Default implementations
— public boolean equals(Object obj)
— two objects are equal if and only if they are stored in the
same memory address.
— public int hashcode( )
— returns a unique random integer that is unique for each
instance
— The default implementation is not enough to thus
developers must provide their own implementation
in order to force equality of object.

— In practice, developers should override both


methods to achieve a fully working equality
mechanism
Student class (Simple)
public class Student {

private int id;


private String name;

public Student(int id, String name) {


this.name = name;
this.id = id;
}
}
— See how logic fails
Student alex1 = new Student(1, "Alex");
Student alex2 = new Student(1, "Alex");
//Both are same
System.out.println("alex1 = " + alex1.hashCode());
System.out.println("alex2 = " + alex2.hashCode());
System.out.println("alex1 and alex2 = " + alex1.equals(alex2));//
not equal due to default implementation

Output
989898989
667676766
false// ???

Fix equals only??


— See how logic fails
Student alex1 = new Student(1, "Alex");
Student alex2 = new Student(1, "Alex");
//both are same
HashSet<Student> set=new HashSet<Student>();
System.out.println(set.add(alex1));
System.out.println(set.add(alex1));
System.out.println(set.add(alex2));

Output
true
false
true// Should this happen??

Fix hashCode only??


public class Student {
private int id;
private String name;
public Student(int id, String name) { this.name = name; this.id = id; }
public int getId() { return id; }

@Override
public int hashCode() {
return getId();
}

@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Student))
return false;
if (obj == this) return true;
return this.getId() == ((Student) obj).getId();
}
}
— Of hashcodes are not equals just return false
if (obj.hashCode() != this.hashCode())
return false;
class Entry {
private String name, number;
public Entry( String n, String num ) { name = n; number = num; }
public String getName() { return name ; }
public String getNumber() { return number ; }

public boolean equals( Object other ) {


return getName().equals( ((Entry)other).getName() ); }

public String toString() { return "Name:" +getName() + "; Num: "


+getNumber();
}}
public class PhoneBookTest {
public static void main ( String[] args) {
ArrayList<Entry> phone = new ArrayList<Entry>();

phone.add( new Entry( "Amir", "123 4567") );


phone.add( new Entry( "Farooq", "123 6780") );
phone.add( new Entry( "Hameed", "789 1234") );
phone.add( new Entry( "Zubair", "446 0210") );

// Look for Hameed in phone. The indexOf() method uses the


// equals(Object) method of each object in the list.

Entry target = new Entry( "Hameed", null );


int spot = phone.indexOf( target ) ;
System.out.println( "indexOf ( ) returns: " + spot ) ;
}
} indexOf ( ) returns: 2
Exercise
— Override int hashCode()
— Note
— Number is a String

— Integer.parseInt() can be used


— Make sure it is safe. Use try - catch
“Always code as if the guy who ends up
maintaining your code will be a violent
psychopath who knows where you live”
― John Woods
Java Style Guide

Quick fix
Java Programming Style Guide
— Programming style guides are guidelines that cover
aesthetic issues of formatting, code writing
conventions or coding standards.
— Java coding follows these hard-and-fast rules universally
— Some famous style guides are
— Java Sun Style guide
— Google Java Style Guide
— https://google.github.io/styleguide/javaguide.html
— Some style that you should adhere to during Java
coding
Case Conventions
— Variables, fields and methods:
— start with lowercase, use caps for new words (camelCase):
— name
— sayHello
— Classes:
— start with uppercase, use caps for new words (PascalCase
aka UpperCamelCase):
— Greeter
— ArrayList
— Constants:
— use all caps, underscores to separate words
— PI
— MAX_VALUES
Property Access
— Common to use get/set prefixes:
— public String getName()
— void setName(String newValue)
— Boolean property has is/set prefixes:
— public boolean isPolite()
— public void setPolite(boolean newValue)
Braces
— "Allman" brace style: braces line up.
public String sayHello()
{
return "Hello, " + name + "!";
}

— "Kernighan and Ritchie or K&R" brace style: saves a line.


public String sayHello() {
return "Hello, " + name + "!";
}
— Most IDEs support both "Allman" & "K&R" style nowdays
but K&R is most preferred.
Fields & Methods placement
— One style where fields are before methods and other way
around:
public class Greeter
{
private String name;
public Greeter(String aName) { . . . }
public giveSalute(){}
}
— All fields should be private.
— Keep overloaded constructors together with no other code in
between (not even private members).
— What ever you do (field first or at the end) make sure it is
consistent.
Miscellaneous
Spaces around operators, after keywords, but not
after method names:
Bad Good
if(x>Math.sqrt (y)) if (x > Math.sqrt(y))

Don't use C-style arrays:


Bad Good
int numbers[] int[] numbers

No magic numbers
Bad Good
h = 31 * h + val[off]; final int HASH_MULTIPLIER = 31;
h = HASH_MULTIPLIER * h + val[off];
— Always use
@Override with overridden methods
Will explain this later
Thank you!!
— Read up and do exercise on ArrayList, HashSet and
HashMap, HashTable
— Exam Questions from this lecture
— Problem statement to Interface, Abstract classes
— Code output or finding errors etc….
— Converting wrong code and fix it.
— Using ArrayList, HashSet etc……
— Finding errors in Java and correcting it

You might also like