Final, Finally (Part 3: Final Method)

welcome to part 3 of Final Keyword …

Final Method

We can declare a method as final. A final method cannot be overridden by a child class.

public class Dhaka {
    public final void uCanNotOverrideMe (){
        System.out.println("wow!");
    }   
}

public class Khulna extends Dhaka {
     public final void uCanNotOverrideMe (){
        System.out.println("wow!");  
     }
}

// Compile error: uCanNotOverrideMe() in Khulna cannot override uCanNotOverrideMe() in Dhaka; overridden method is final

If you don’t want a child class to override a method for some of the requirements, then you can use final methods.

enjoy!

Advertisements

Final, Finally (Part 2: Final Class)

welcome to part 2 of Final Keyword. Lets Start …

Final Class

We can declare a class as final. After that we cant create child class under that final class.

example time.


public final class King {
    public static void main (String args []){
        System.out.println("king Arthur");   
    }
}

public class Test extends King {
    
}

// compile error: cannot inherit from final King

so why on earth you want a final class,

1. Final classes (Immutable) are read-only.
2. Thread safe, no synchronization overhead.

a very good explanation

Enjoy 🙂

Final, Finally (Part 1: Final Variables)

Well The Java keyword final has nothing to do with this tv series 🙂

Final Variable

A final variable cannot be changed after it has been assigned a value.

Java convention says that you should write you final constants in uppercase and use underscore (_) to separate multiple words. Here is a basic example

public class Test {
    public static void main (String args []) {
        final int SECOND = 60;
        final String WATCH_NAME = "SNOW";
        System.out.println(SECOND);
        System.out.println(WATCH_NAME);
    }
}

Let’s messing around

        final int SECOND = 60;
        final String WATCH_NAME = "SNOW";
        System.out.println(SECOND);
        System.out.println(WATCH_NAME);
        SECOND = 60; // error

Compile time error: cannot assign a value to final variable SECOND

hm seems nice

public class Test {
        final int SECOND = 60;
        final String WATCH_NAME = "SNOW";
}

public class IwantToChangeYou {
    public static void main (String args []) {
        Test t = new Test();
        t.SECOND = -60; // error
    }
}

Compile time error in IwantToChangeYou class: cannot assign a value to final variable SECOND in class.

public class Test {
    final int SECOND = 60;
    final String WATCH_NAME = "SNOW";
    Test(int val){
        this.SECOND = val; // error
    }
}

public class IwantToChangeYou {
    public static void main (String args []) {
        Test t = new Test(60);
    }
} 

Compile time error in Test class: cannot assign a value to final variable SECOND.


/* A blank final is a final variable whose declaration lacks an initializer. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared */

public class IwantToChangeYou {
    
    final int SECOND; 
    
    IwantToChangeYou(){
        this.SECOND = 60;
    }
   
    public static void main (String args []) {
        System.out.println("yes we can set the final value at run time!");
    }
    
}
// but if we use static final we cant do this 

public class IwantToChangeYou {
    
    static final int SECOND; // A blank final is a final variable whose declaration lacks an initializer. 
    
    IwantToChangeYou(){
        this.SECOND = 60;
    }
   
    public static void main (String args []) {
        System.out.println("yes we can set the final value at run time!");
    }
    
}

// option a
static final int SECOND  = 10; 

//option b
public class IwantToChangeYou {
    
    static final int SECOND;
    
    static {
        SECOND = 10;
    }
   
    public static void main (String args []) {
        System.out.println("yes we can set the final value at run time!");
    }
    
}

// we can also use local final variables

public class IwantToChangeYou {
    
    public static void main (String args []) {
        System.out.println("whhat");
    }
    
    public int whaaat(final int NO_WAY){
        int lol = NO_WAY;
        return lol;
    }
}


// Compile time error when we tried to change it
 public int whaaat(final int NO_WAY){
        NO_WAY = 99; // error
        int lol = NO_WAY;
        return lol;
}

public class IwantToChangeYou {
    static final int NO_WAY;
    static int OK;
    IwantToChangeYou(int a){
        this.OK = a;   
        System.out.println("id 1");
    }
    static {
        System.out.println("id 2");
        NO_WAY = OK;
    }  
}

public class Test {
    public static void main (String args []) {
        IwantToChangeYou hm = new IwantToChangeYou(77);
        System.out.println("set final static variable "+hm.NO_WAY);
    } 
}

// expected output ??
// well its 0, because static block executed first when a class initialized
/*
id 2
id 1
set final static variable 0
*/

References
link
link

Enjoy!

Java SE 7 Certification

From now i will post some tips and tricks about Oracle Java Certification.

For Java SE there are two certificates

Oracle Certified Associate, Java SE 7 Programmer and Oracle Certified Professional, Java SE 7 Programmer.

To get this two certificate you have to give two exams

1Z0-803
Java SE 7 Programmer I and

1Z0-804
Java SE 7 Programmer II

If you already have a certificate like Oracle Certified Professional, Java SE 6 Programmer or Oracle Certified Professional Java SE 5 Programmer or Sun Certified Java Programmer (any edition) then you can upgrade your certificate by giving an upgrade exam which is

1Z0-805
Upgrade to Java SE 7 Programmer

Topic

1Z0-805 Upgrade to Java SE 7 Programmer

Language Enhancements

Develop code that uses String objects in switch statements
Develop code that uses binary literals and numeric literals with underscores
Develop code that uses try-with-resources statements (including using classes that implement the AutoCloseable interface)
Develop code that handles multiple Exception types in a single catch block
Develop code that uses the diamond with generic declarations

Design Patterns

Design a class using a Singleton design pattern
Apply object composition principles (including has-a relationships)
Write code to implement the Data Access Object (DAO) pattern
Design and create objects using a factory pattern

Database Applications with JDBC

Describe the interfaces that make up the core of the JDBC API (including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations)
Identify the components required to connect to a database using the DriverManager class (including the jdbc URL)
Construct and use RowSet objects using the RowSetProvider class and the RowSetFactory interface
Use JDBC transactions (including disabling auto-commit mode, committing and rolling back transactions, and setting and rolling back to savepoints)
Submit queries and read results from the database (including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections)
Create and use PreparedStatement and CallableStatement objects

Concurrency

Identify code that may not execute correctly in a multi-threaded environment.
Use collections from the java.util.concurrent package with a focus on the advantages over and differences from the traditional java.util collections.
Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks package to support lock-free thread-safe programming on single variables.
Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools.
Use the parallel Fork/Join Framework

Localization

Describe the advantages of localizing an application
Define a locale using language and country codes
Read and set the locale with a Locale object
Build a resource bundle for a locale
Call a resource bundle from an application
Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes (including number format patterns)

Java File I/O (NIO.2)

Operate on file and directory paths with the Path class
Check, delete, copy, or move a file or directory with the Files class
Read and change file and directory attributes, focusing on the BasicFileAttributes, DosFileAttributes, and PosixFileAttributes interfaces
Recursively access a directory tree using the DirectoryStream and FileVisitor interfaces
Find a file with the PathMatcher interface
Watch a directory for changes with the WatchService interface

1Z0-803 Java SE 7 Programmer I

Java Basics

Define the scope of variables
Define the structure of a Java class
Create executable Java applications with a main method
Import other Java packages to make them accessible in your code

Working With Java Data Types

Declare and initialize variables
Differentiate between object reference variables and primitive variables
Read or write to object fields
Explain an Object’s Lifecycle (creation, “dereference” and garbage collection)
Call methods on objects
Manipulate data using the StringBuilder class and its methods
Creating and manipulating Strings

Using Operators and Decision Constructs

Use Java operators
Use parenthesis to override operator precedence
Test equality between Strings and other objects using == and equals ()
Create if and if/else constructs
Use a switch statement

Creating and Using Arrays

Declare, instantiate, initialize and use a one-dimensional array
Declare, instantiate, initialize and use multi-dimensional array
Declare and use an ArrayList

Using Loop Constructs

Create and use while loops
Create and use for loops including the enhanced for loop
Create and use do/while loops
Compare loop constructs
Use break and continue

Working with Methods and Encapsulation

Create methods with arguments and return values
Apply the static keyword to methods and fields
Create an overloaded method
Differentiate between default and user defined constructors
Create and overload constructors
Apply access modifiers
Apply encapsulation principles to a class
Determine the effect upon object references and primitive values when they are passed into methods that change the values

Working with Inheritance

Implement inheritance
Develop code that demonstrates the use of polymorphism
Differentiate between the type of a reference and the type of an object
Determine when casting is necessary
Use super and this to access objects and constructors
Use abstract classes and interfaces

Handling Exceptions

Differentiate among checked exceptions, RuntimeExceptions and Errors
Create a try-catch block and determine how exceptions alter normal program flow
Describe what Exceptions are used for in Java
Invoke a method that throws an exception
Recognize common exception classes and categories

1Z0-804 Java SE 7 Programmer II

Java Class Design

Use access modifiers: private, protected, and public
Override methods
Overload constructors and methods
Use the instanceof operator and casting
Use virtual method invocation
Override the hashCode, equals, and toString methods from the Object class to improve the functionality of your class.
Use package and import statements

Advanced Class Design

Identify when and how to apply abstract classes
Construct abstract Java classes and subclasses
Use the static and final keywords
Create top-level and nested classes
Use enumerated types

Object-Oriented Design Principles

Write code that declares, implements and/or extends interfaces
Choose between interface inheritance and class inheritance
Apply cohesion, low-coupling, IS-A, and HAS-A principles
Apply object composition principles (including has-a relationships)
Design a class using a Singleton design pattern
Write code to implement the Data Access Object (DAO) pattern
Design and create objects using a factory pattern

Generics and Collections

Create a generic class
Use the diamond for type inference
Analyze the interoperability of collections that use raw types and generic types
Use wrapper classes, autoboxing and unboxing
Create and use List, Set and Deque implementations
Create and use Map implementations
Use java.util.Comparator and java.lang.Comparable
Sort and search arrays and lists

String Processing

Search, parse and build strings (including Scanner, StringTokenizer, StringBuilder, String and Formatter)
Search, parse, and replace strings by using regular expressions, using expression patterns for matching limited to: . (dot), * (star), + (plus), ?, \d, \D, \s, \S, \w, \W, \b. \B, [], ().
Format strings using the formatting parameters: %b, %c, %d, %f, and %s in format strings.

Exceptions and Assertions

Use throw and throws statements
Develop code that handles multiple Exception types in a single catch block
Develop code that uses try-with-resources statements (including using classes that implement the AutoCloseable interface)
Create custom exceptions
Test invariants by using assertions

Java I/O Fundamentals

Read and write data from the console
Use streams to read from and write to files by using classes in the java.io package (including BufferedReader, BufferedWriter, File, FileReader, FileWriter, DataReader, ObjectOutputStream, ObjectInputStream, and PrintWriter)

Java File I/O (NIO.2)

Operate on file and directory paths with the Path class
Check, delete, copy, or move a file or directory with the Files class
Read and change file and directory attributes, focusing on the BasicFileAttributes, DosFileAttributes, and PosixFileAttributes interfaces
Recursively access a directory tree using the DirectoryStream and FileVisitor interfaces
Find a file with the PathMatcher interface
Watch a directory for changes with the WatchService interface

Building Database Applications with JDBC

Describe the interfaces that make up the core of the JDBC API (including the Driver, Connection, Statement, and ResultSet interfaces and their relationship to provider implementations)
Identify the components required to connect to a database using the DriverManager class (including the jdbc URL)
Submit queries and read results from the database (including creating statements, returning result sets, iterating through the results, and properly closing result sets, statements, and connections)
Use JDBC transactions (including disabling auto-commit mode, committing and rolling back transactions, and setting and rolling back to savepoints)
Construct and use RowSet objects using the RowSetProvider class and the RowSetFactory interface
Create and use PreparedStatement and CallableStatement objects

Threads

Create and use the Thread class and the Runnable interface
Manage and control thread lifecycle
Synchronize thread access to shared data
Identify code that may not execute correctly in a multi-threaded environment.

Concurrency

Use collections from the java.util.concurrent package with a focus on the advantages over and differences from the traditional java.util collections.
Use Lock, ReadWriteLock, and ReentrantLock classes in the java.util.concurrent.locks package to support lock-free thread-safe programming on single variables.
Use Executor, ExecutorService, Executors, Callable, and Future to execute tasks using thread pools.
Use the parallel Fork/Join Framework

Localization

Read and set the locale by using the Locale object
Build a resource bundle for each locale
Call a resource bundle from an application
Format dates, numbers, and currency values for localization with the NumberFormat and DateFormat classes (including number format patterns)
Describe the advantages of localizing an application
Define a locale using language and country codes

source

Enjoy and Happy Programmers Day 🙂