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 – 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 – 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 – 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.