Category Archives: Java

Java Tut – Polymorphism

Polymorphism the most common use of OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic.In java all java objects are polymorphic since any object will pass the IS-A test for their own type and for the class object.
It is important to know that only possible way to access an object is through a reference variable.A reference varibale can only be one type.Once declared, the type of a reference variable cannot be changed.

A reference variable can be declared as a class or interface type

Let us look an example

Now the Deer class is considered to be polymorphic since this has multiple inheritance.Following are true for the above example:

Virtual Methods:
In this section,I will show you how the behavious of overriden methods in java allows you to take advantage of poly

Employees.java

Salary.java

VirtualDemo.java

 

Output:

References:
http://www.tutorialspoint.com/java/java_polymorphism.htm
http://www.javatpoint.com/runtime-polymorphism-in-java

Java Tut – Method Overriding

If subclass has the same method s declared in the parent class, it is known as method overriding in java.

– Method override is used for runtime polymorphism
– Method overriding is used to provide specific implementation of a method that is already provided by its super class.

Rules –
1.Method must have same name is in the parent class
2. method must have separator as in the parent class
3. Must be IS-A relationshp

understanding the problem without method overriding:

Output:

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding:

Output:
May be I did some wrong so output is not coming

Another example :
Java method overriding example of bank

Bank.java

Test2.java

Output:

Reference:
http://www.javatpoint.com/method-overriding-in-java

Java Tut – inheritance

The classs which inherits the properties of other is known as subclass(derived class,child class etc.) and the class whose properties are inherited is known as superclass(base class,parent class).

extends keyword:
extends is the keyword used to inherit the properties of a class, below given is the syntax of extends keyword:

example:
Calculation.java

My_Calculation.java

Output:

Super keyword:
The super keyword is similar to this keyword, following are the scenarios where the super keyword is used

– it is ised to differentiate the members of superclass from the members of subclass, if they have same names,
– It is used to invoke the superclass contructor from subclass
Differentiating the members:
supe
super.method();

Super_classs.java

Sub_class.java

Output:

Invoking Superclass constructor

If you want to call a parametrized constructor of the super class, you need to use the super keyword as shown below:
super(values);

Sample code:

SuperClass.java

SubClass.java

output:

IS-A Relationship:
IS-A is a new way of saying: This object is a type of that object.Let us see how the extends keyword is used to achieve inheritance.

In object oriented terms, the following are true-
Animal is the superclass of Mammal class .
Animal is the superclass of Reptile class
Mammal and Reptile are subclass of Animal class
Dog is the subclass of both Mammal and ANimal classes
Now  if we consider the IS-A relationship,,,we can say-
-Mammal IS-A Animal
-Reptile IS-A Animal
-Dog IS-A Mammal
Hence: Dog IS-A Animal as well

Using the extends keyword the subclasses will inherit all the properties of super class except the private properties.

Now, we can ensure that Mammal is actually an Animal with the use of the instance operator.
Example:
Animal.java

Dogg.java

Output:

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

Genrally the implements keyword s used with classes to inherit the properties of an inheritance.Interfaces can never be extended by a class.
Example:

The instanceof keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal

Output:

Though there is some error in my above code.

HAS-A Relationship
These relationships are mainly based on the usage.This determines whether a certain class HAS-A certain thing.This relationship help to reduce duplication of codes as well as bugs.

let us look into an exampel:

 

More details in the link below.
Types of inheritance:
Java Tutorial

And one thing is Multiple Inheritance is not supported in java.It is illegal below:

 


Reference:
http://www.tutorialspoint.com/java/java_inheritance.htm

 

Difference Between Method Overloading and Method Overriding in Java

Method Overloading:
1) Performed within class
2) Parameters must be different
3)Is the example of compile time polymorphism
4)Return type can be the same or different in method overloading.But you must have to change the parameter.
Method Overriding:
1)Method overriding occurs in two classes that have IS-A(inheritance) relationship
2)Parameters must be the same
3) Is the example of run time polymorphism.
4) Return type must be the same or covariant in method overriding

Overloading Example:

 

Overriding Example:

Java Tut – Exception Handling

The exeption handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained

In here we learn
What is exception: From dictionary: Exception is a n abnormal condition.
In java, exception is an event that disrupt he flow of the program.It is an object which is thrown at runtime.

What is exception handling. Exception handling is a mechanism to handle runtimer errors such as ClassNotFound,IO,SQL,Remote etc.

The core advantage of excepion handling is to maintain the normal flow of the application.Exception normally disruts the normal flow of the application that is wh we use exception handling:
Let take the scenario:
1) Checked Exception: e.g: IOException,SQLException
The classes that extend throwable class except RuntimeException and Error are known as checked exceptions.Checked exceptiions are checked at compile time.

2} Unchecked exceptions: The classes that extend RuntimeExceptiona re known as unchecked exceptions e.g: ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsException etc. Uncheked exceptions are not checked at compile time rather checked at run time.

3)Error: Error is irrecoverable e.g:OutOfMemoryError, VirtualMachineError, VirtualMachineError, AssertionError etc.

Java exception handliung keywords:

1.Try
2. catch
3. finally
4. throw
5. throws

1) Scenario where ArithemeticException occurs::

2) Scenario where NullPointerException occurs
E.g:

3) Scenario where NumberFormatException occurs:
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException

4)Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, It would result ArrayIndexOutOfBoundsException as shown below:

throw vs throws:
Throw: You cannot throw multiple exceptions.
Throws: You can declare multiple exceptions e.g: public void method() throws IOException,SQLException etc.

Java throw example:

Java throws example:

Java throw and throws example:

for further learning you can check out this link for reference: http://www.javatpoint.com/exception-handling-in-java

Java Files and I/O

it needs java.io package containers .All these streams represent an input source and an output destination.
Stream:
A stream can be defined as a sequence of data there are two kinds of streams
InputStream:It is used to read data from a source
OutputSTream:It is used for writing data o a destination

Here is a hierarchy of classes to deal with Input and Output streams:
Java I/O StreamsThe two important streams are FileInputSTrea and FileOutputSTream which would be discussed in this tutorial:
Following constructor will create a input stream object to read the file:

Once you have InputStream object in hand,  then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

And there is OutPutStream that can be discussed later.It is almost same like:

And there are some other class for filereading and writing and creating directories.

Byte stream:

Character Streams:

Standard Streams:
Standard Input: System.in
Standard Output: System.out
Standard Error: System.err
Just like STDIN,STOUT,STDERR in C/C++
example to demonstrate inputstream and outputstream:

 

 

Java Date & Time and Regex

Java provides he Date class available in java.util.*; packages, this class encapsulates the current date & time.

contructors: Date() , Date(long millisec)
Methods:
boolean after(Date date)
int compareTo(Date date)
boolean equals(Object date)
example:

Java Regex
Will work on regex later but it use java.util.regex package for pattern matching with regular expressions

Java Arrays

j
Java Arrays:

Creating Arrays:

The array elements are accessed throughthe index.Array indices are 0 based; that is, they start from 0 to arrayRefVar.length-1
double[] myList=new double[10];

Output:

foreach loops

Output:

Passing Arrays to Methods:

Returning an Array from a method:

The array class:

java.util.arrays for soritng and searching arrays,comparing and filling arrays.
public static int binarySearch(Object[] a,Object key)

public static boolean equals(long[] a1,long[] a2)

public static void fill(int[] a,int val)

public static void sort(Object[] a)

Java – String, String Buffer and String Builder Classes

Creating strings:

 

output: hello
StringBuffer:
public StringBuffer append append(String s)
public stringBuffer append(boolean b)
public StringBuffer append(char c)
replace(),delete(), reverse(),capacity(),length(),setCharAt(int index,char ch),setLength(),String subString(int start),String subString(int start,int end)

one example in buffer class:

length() and capacity() method

output:

For more example:
I will see in future
– Java the complete reference(Best examples here)
– Oracle Java Library
– Android Reference
– Tutorials point for explanation

 

Java Tut – Character Class

Some escape sequence here :
\t,\b,\n,\r,\f,\’,\”,\\
example:

output:

The character class offers a number of useful class(i.e: static) methods for manipulating characters.You can create character object with the Character constructoir:

we normally use primitive though:
char ch=’a’;
Unicode for uppercase greek omega letter
char cunicode=’\u039A’;
char c=’test(‘x’);
Character methods:
Here is the list of the important intance  methods taht all subclasses of t

the character class implement
:
those are available in java.lang
Character Class isLetter(“c”),isDigit(“5”),
Character.isWhiteSpace(‘\n’);
Character.isWhitespace(‘\t’);

String toString(char ch)
ch — primitve character type
the method returns a string object representing the speciifed character value, that is, a one character string.
Character.toString(‘c’);
Character.toString(‘C’);
result:
c
C

 

Java Tut – Numbers

Normally when we work with numbers, we use primitive data types such as byte,int,long,double, etc

e.g:
int i=400;
float gpa=13.65;
byte mask=0xaf;
In develoment we need to use objects instead of primitive data types.So java provides wrapper classes

All the weapper classes are the subclasses of the abstract class Number.
Number Subclasses
The object of the wrapper class contains or wraps it respective primitive data type.converting primitive data types into object called boxing, and this is taken care by the compiler.so while passing the wrapper class you just need to pass the value of the primitive data type to the constructor of the wrapper class.

And the wrapper object will be converted back to a primitive data type and this process is called un boxing.The Number class is part of the java.lang package.

example:

output:
15
When x is assigned integer value the compiler boxes the integer because x is integer object.Later, x is unboxed so that they can be added as integer.
Number Methods:
Here is the list of the instance methods that all the subclasses of teh Number class implement:

xxxxValue() method:
Syntax:
here is a separate method for each primitive data type:

example:

Output:

compareTo() method:
Two different types cannot be compared, both the argument and the Number object invoking(ডাকা) should be the same type:
Syntax:

Parameters:
referenceName – this could be a Byte,Double,Integer,Float,Long or Short
Return Value:
– If the integer in referenceName is equal to argument object then 0 is returned.
– If the Integer is less than the argument than 1 is returned.
– If the Integer is greater than the argument than -1 is returned

Example:

Output:

equals() Method:
Syntax:
public boolean equals(Object o)
Parameters:
Here is the detail of parameters:
o — is any object
Return Value:
The method returns True or false if the arguments is not null and is an object of the same type and with the same numeric value.There are some extra requirements for Double and Float objects that are described in the Java API documentation.
Example:

Output:

 

Java Max() method:
The method gives the maximum of the two arguments.The arguments can be int,float,long,double
Syntax:
This method has following variants:

Parameters: This method accepts any primitive data type as parameter
Return value: This method returns the maximum of the two arguments
Example:

Output:

exp():
Syntax:

double exp(double d)
example:

out:

toRadians()
syntax:

 

Parameter: d  a double data type
Return value: This method returns a double value
example:

output:


floor() method/ceil method:

This method floor gives the largest integer that is less than or equal to the argument.

This method ceil gives the smallest integer that is greater than or equal to the argument.
Syntax:

Parameter:A double or flaot primitive data type
Return Value: This method returns the largest integer that is less than or equal to the argument.Returned as double.
example:

output:

toString() method:

This method is used to get a string object representing the value of the number object.

If the method takes a primitive data type as an argument, then the String object representing the primitive data type value is returned.

If the method takes two arguments,then a String representation of the first argument in the radix specified by the second argument will be returned.

i — An int for which string representation would be returned

valueOf():

output:

parseInt() or parseXXXX():

This method is used to get the primitive data type of a certain String.parseXXX() is a static method can have one argument or two.

Parameters:
s — This is a string representation of deciaml
radix – This would be used to convert String s into integer

Return Value:
parseInt(String s): This returns an integer(decimal only)
parseInt(int i): This returns an Integer, given a string representation of decimal,binary,octal or hexadecimal(radix equals 10,2,8 or 16 respectively) numbers as input.

Java Tut – Decision Making

If statement:

e.g:

output:

If-else statement:

example:

output:

if..else if…else statement:
Syntax:

example:

output:

nested if statement in java:
It is alwys legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statements.

we can also nest else if…else in the similar way as we have nested the if statement

output:

Switch statements in Java
A switch statement allows a variable to be tested for equality against a list of values.Each value is called a case and the variable being switched on is checked for each case.
Syntax:

example:

output:

 

The ? : Operator
it is known as conditional operator in some previous post i have shown it.It can repalce the if…else statements.
Syntax:
exp1?exp2:exp3;

where exp1,exp2 and exp3 are expressions, initially exp1 is evaluated,
– If the value of exp1 is true, then the vaue of exp2 will be the value whole expression
– If the value exp1 is false, then exp3 is evaluated and its value becomes the value of the entire expression.

Java Tut – Loop

Java programming language provides the following types of loop to handle looping requirements.Click on the following links to check the detail.
While Loop:
Syntax for while loop:

e.g:

output:

For Loop:
Syntax for for loop is:
for(iitialization;Boolean_expression;update)
{
//statements
}
the update statement can be left blank with a semicolon at the end.
example :

out:

do..while loop:
do{
//Statements
}while(boolean_expression)

e.g:

output:

 

Loop Control Statements:
break statements:
example:

output:

continue statements:

– In a for loop, the continue keyword causes control to immediately jump to the update statement.

– In a while loop or do-while loop, control immediately jumps to the boolean expression.

output:

 

Enhanced for loop in Java:
it included from Java 5, the enhanced for loop was introduced.This is mainly used to traverse collection of elements including arrays.
Syntax:

Declaration: The newly declared block variable, which is a type compatible with the elements of the array you are accessing.

Expression: This evaluates to the array you need to loop through.The expression can be an array variable or method call that returns an array.
e.g:

output:

 

Java Tut – Operators

Arithmetic operator – Just like other languages
+,-,*,%,/++,– etc.

Relational Operators: ==,!=,>,<,>=,<= etc.
e.g:

Bitwise Operators: Java defines several bitwise operators,which can be pplied to the integer types,long,int,short,char, and byte

Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a=60 and b=13; now in binary format they will be a s follows:
a=00111100
b=00001101
——————
a&b=00001100
a|b=00111101
Some operators:
& bitwise and, | bitwise inclusive or,^ bitwise exclusive XOR,~ bitwise compliment,<< left shift,>> right shift,>>> zero fill right shift
e.g:

Logical Operators:
&& logical AND,|| logical OR,! logical NOT
e.g:
assume boolean variable a holds true,b holds false.

Assignment Operator:

= simple assignment operator, += Ass and assignment operator c+=a is equivalent to c=c+a,-=,*=,/=,&=,%=,<<=,>>=,^=,|=

Conditional Operator/ternary operator:
syntax:
variable x= (expression)?value if true:value if false
e.g:

Instance of operator:
This  operator is used only for object reference variables.The operator checks whether the object is of particular type(class type or interface type).instance of operator is written as:

e.g:

output:

another example will still return true if the object being compared is the assignment compatible with the type on th right.

output:

 

Java Tutorial – Modifiers

Java language has a wide variety of modifier, including the following:
Java Access Modifiers
Non Access Modifiers

To use a modifier, you include its keyword in the definition of a class,method or variable.The modifier preceds the rest of the statement, as in the following examples(Italic ones)

 

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 package, the default.No modifiers are needed.
Visible to class only(Private)
Visible to word(Public)
Visible to the package and all subclasses(Protected)

Non Access Modifiers:
Java provides a number of non access modifiers toa chieve 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.

Access Control Modifiers:
Default access modifier – No keyword:
Default access modifier means we don’t explicitly declare an access modifier for a class,field,method etc.

A variable or method declared without any access control modifier is available to any other class in the same package.The fields in an interface are implicitly public static final and the methods in an interface are by default public.
Example:
variable and methods can be declared without any modifiers,as in the following examples:

Private Access Modifier – private:
Methods, Variables and Constructors that are private can only be accessed within the declared class itself.

Private access modifier is the most restricitve access level.Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hide data from the outside of the world.The following class uses private access control:

here format variables of the logger class is private, so there’s no way for other classes to retrieve or set its value directly.

So to make this variable available at the outside world, we defined two public methods: getFormat(), which returns the value fo format,a nd setFormat(String), which set it’s value.
Public:
The main() method of an application has to be public.Otherwise, it could not be called by a Java Interpreter(Such as Java) to run the class.
Example:
The following function uses public access control:

Prtotected Access Modifier – protected

Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of protected member class.

The protected access modifier cannot be applied to class and interfaces.Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, wehile preventing a nonrelated class from trying to use it.
example:

The above parent class use protected access control, to allow its child class override openSpeaker() method.

Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer.If we define it as public, then it would become accessible to all the outside world.But our intensio is to expose this method to its subclass only, thats why we used protected modifier 🙂 .

Access control and Inheritance:
The following rules for inherited method are enforced.
-Method declared public in a superclass also must be public in all subclasses.
– Method declares protected in a superclass must either be protected or public in subclasses; they cannot be priavte.
– method declared without access control(no modifier was used) can be declared more private in subclasses.
– method declared private are not inherited at all, so there is no rule for them

Java 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 implementation of classes,methods and variables.
– The abstract modifier for creating abstarct classes and methods.
– The synchronized and volatile modifiers, which are used for threads.

Static Variables:
the static key word is used to create variables that will exist independently of any instances created for the class.Only one copy of the static variable exists regardless of the number of instances of the class.

Static variables are also known as class variables.Local variables cannot be declared static.

Static Methods:

The static key word is used to create methods that will exist independently of any instances created for the class.

Static methods do not use any instance variables of any object of the class they are defined in.Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.

Class variables and methods can be accessed during the class name followed by a dot and the name of the variable or method.

example:
The static modifier is used to create class methods and variables as in the following example:

result would be :

Final Modifier:
Final Variables:

A final variable can be explicitly initialized only once.A reference variable declared final can never be reassigned to refer to an different object.

However the data within the object can be changed.So the state of the object can be changed but not the reference.

final variables with the final modifier often is used with static to make the constant a class variable.

Final Methods:
A final method cannot be overriden by any subclasses.As mentioned previously the final modifier prevents a method from being modified in a subclass.

The main intention of making a method final would be that the content of the method should not be changed by any outsider.

example:

You declasre methods using final modifier in the class declaration, as in the following example.

final Classes:
The main purposes of using a clas sbeing declared as final is to prevent the class from being subclassed.If a class is marked as final then no class can inherit any feature from the final class.
example:

The abstract Modifier:
abstract class:
An abstract class can nver be instantiated.If a class is declared as abstract then the sole purpose is for the class to be extended.

A class cannot be both abstract and final.Since a final class cannot be extended.If a class contains abstract methods then the class should be declared abstract.Otherwise a compile error will be thrown.

An abstract class may conatin both abstract methods as well as normal methods.

example:

Abstract methods:
an abstract method is a method declared with out any implementation.The methods body is provided by the subclass.Abstract methodsa can never be final or strict.

Any class that  extendsan abstract class must implement all the abstarct methods of the super class unless the subclass is also an abstract class.

If a class contains one or moree abstract methods then the class must be declared abstract.An abstract class does not need to contain abstract methods.

The abstract method ends with a semicolon.Example:public abstract sample();

The Synchronized Modifier:
synchronized modifier used to indicate that a method can be accessed by only one thread at a time.This modifier can be applied with any of the four access level modifiers.
Example:

The transient Modifier:
An instance variable is marked transient to indicate ther JVM to skip the particular variable when serializing the object containing it.

This modifier is included in the statement that creates the variable,preceing the class or data type of the variable.
example:

The Volatile Modifier:

You can see this link for detailed and perfect explanation
reference: http://www.tutorialspoint.com/java/java_nonaccess_modifiers.htm