Java Notes2 Mid
Java Notes2 Mid
initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and
its widespread popularity, multiple configurations were built to suit various types of platforms.
For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.
Java is – Features
Object Oriented − In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
Platform Independent − Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation dependent aspects
of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.
Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
Multithreaded − With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
Distributed − Java is designed for the distributed environment of the internet.
Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of run-
time information that can be used to verify and resolve accesses to objects on run-time.
1
History of Java
James Gosling initiated Java language project in June 1991 for use in one of his many set-top
box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's
office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of
random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
Notepad − On Windows machine, you can use any simple text editor like Notepad
(Recommended for this tutorial), TextPad.
Netbeans − A Java IDE that is open-source and free which can be downloaded from
https://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded from https://www.eclipse.org/.
When we consider a Java program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods,
and instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
2
Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Let's look at how to save the file, compile, and run the program. Please follow the subsequent
steps −
Basic Syntax
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case.
3
Method Names − All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case.
Program File Name − Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match, your program will not compile).
But please make a note that in case you do not have a public class present in the file
then file name can be different than class name. It is also not mandatory to have a public
class in the file.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.
System is a class provided by java, out is the static member and instance of PrintStream class,
print and println is method of PrintStream class.
String Concatenation
In Java strings can be concatenated with + operator, any other data type will become string if
it is concatenated with string using + operator.
“This is string” + “ This is 2nd string”
“This is string” + 2 // this 2 will concatenate with string
4
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are called
identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character, identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There
are two categories of modifiers −
5
First Java Program
public class MyFirstJavaProgram {
Explanation:
Why main?
Why public?
Since main() method is called by JVM so it must be public to call from out side.
Why static?
If main is not static then the JRE have to create an object of the class in which main
method is present and call the main method on that object (In OOP based languages method
are called using the name of object if they are not static). It is made static so that the JRE can
call it without creating an object. Also to ensure that there is only one copy of the main method.
Why void?
Way of specifying input from command line arguments while run the program from
command line.
Java Variables
Following are the types of variables in Java −
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)
public myMethod(){
//Local Variables, only access in this method, will
//destroy when method ends execution
int n1;
String s;
}
}
Java Keywords
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
7
for goto if implements
volatile while
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters
available inside any comment are ignored by Java compiler.
8
Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
Typically, you will use a constructor to give initial values to the instance variables defined by
the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once you
define your own constructor, the default constructor is no longer used.
Syntax
class ClassName {
ClassName() {
}
}
No argument Constructors
Parameterized Constructors
9
No argument Constructors
As the name specifies the no argument constructors of Java does not accept any parameters
instead, using these constructors the instance variables of a method will be initialized with fixed
values for all objects.
Most often, you will need a constructor that accepts one or more parameters. Parameters are
added to a constructor in the same way that they are added to a method, just declare them inside
the parentheses after the constructor's name.
// A simple constructor.
class MyClass {
int x;
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
10
public static void main(String []args) {
// Following statement would create an object myPuppy
new Keyword
This keyword is used to initialize the object of a class and initialize memory on heap.
11
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Java Package
In simple words, it is a way of categorizing the classes and interfaces. When developing
applications in Java, hundreds of classes and interfaces will be written, therefore categorizing
these classes is a must as well as makes life much easier. Collection of classes is called package.
Import Statements
In Java if a fully qualified name, which includes the package and the class name is given, then
the compiler can easily locate the source code or classes. Import statement is a way of giving
the proper location for the compiler to find that particular class.
For example, the following line would ask the compiler to load all the classes available in
directory java_installation/java/io −
import java.io.*;
12
Take input from Keyboard
The Scanner class from the package java.util is used to take input from the keyboard.
Following are the steps to take input:
Import the util package
Create object of Scanner class
Call method to Scanner class according to the input type
import java.util.Scanner;
public class JavaTest {
System.out.print("Enter an Integer");
i = scan.nextInt();
System.out.print("Enter a Float");
f = scan.nextFloat();
System.out.print("Enter a Double");
d = scan.nextDouble();
}
}
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
13
Java - Basic Datatypes
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals, or characters in these variables.
There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by
the language and named by a keyword. Let us now look into the eight primitive data types in
detail.
Reference Datatypes
Reference variables are created using defined constructors of the classes. They are used
to access objects. These variables are declared to be of a specific type that cannot be
changed. For example, Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
14
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify
the arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in
this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
15
Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of
a wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double etc.
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
16
Java Literals
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.
byte a = 68;
char a = 'A';
Local variables
Instance variables
Class/Static variables
Local Variables
17
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
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.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access
modifiers.
Instance variables have default values. 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.
Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.
import java.io.*;
public class Employee {
18
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
Output
name : Ransika
salary :1000.0
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. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the program
stops.
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 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.
When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.
import java.io.*;
public class Employee {
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
19
Output
Development average salary:1000
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators −
20
The Relational Operators
There are following relational operators supported by Java language.
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 as follows −
a = 0011 1100
b = 0000 1101
-----------------
Assume Boolean variables A holds true and variable B holds false, then –
22
Called Logical OR Operator. If any of the two
|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.
Called Logical NOT Operator. Use to reverses the
! (logical not) logical state of its operand. If a condition is true !(A && B) is true
then Logical NOT operator will make false.
23
Precedence of Java Operators
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
24
Java - Decision Making
Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Java programming language provides following types of decision making statements. Click the
following links to check their detail.
if statement
1
An if statement consists of a boolean expression followed by one or more statements.
if...else statement
2
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false.
nested if statement
3
You can use one if or else if statement inside another if or else if statement(s).
switch statement
4
A switch statement allows a variable to be tested for equality against a list of values.
25
The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to replace
if...else statements. It has the following general form −
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of
the entire expression.
Programming languages provide various control structures that allow for more complicated
execution paths.
26
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
while loop
1
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
2
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop
3
Like a while statement, except that it tests the condition at the end of the loop body.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.
break statement
1
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection
of elements including arrays.
Syntax
for(declaration : expression) {
// Statements
27
}
Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
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.
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,
Example
int i = 5000;
float gpa = 13.65;
double mask = 0xaf;
However, in development, we come across situations where we need to use objects instead of
primitive data types. In order to achieve this, Java provides wrapper classes.
All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the
abstract class Number.
28
The object of the wrapper class contains or wraps its respective primitive data type. Converting
primitive data types into object is called boxing, and this is taken care by the compiler.
Therefore, while using a 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 unboxing. The Number class is part of the java.lang package.
29
Following is the list of the instance methods that all the subclasses of the Number class
implements
xxxValue()
1
Converts the value of this Number object to the xxx data type and returns it.
compareTo()
2
Compares this Number object to the argument.
equals()
3
Determines whether this number object is equal to the argument.
valueOf()
4
Returns an Integer object holding the value of the specified primitive.
toString()
5
Returns a String object representing the value of a specified int or Integer.
parseInt()
6
This method is used to get the primitive data type of a certain String.
abs()
7
Returns the absolute value of the argument.
ceil()
8 Returns the smallest integer that is greater than or equal to the argument. Returned as
a double.
floor()
9 Returns the largest integer that is less than or equal to the argument. Returned as a
double.
rint()
10
Returns the integer that is closest in value to the argument. Returned as a double.
round()
11 Returns the closest long or int, as indicated by the method's return type to the
argument.
min()
12
Returns the smaller of the two arguments.
max()
13
Returns the larger of the two arguments.
exp()
14
Returns the base of the natural logarithms, e, to the power of the argument.
log()
15
Returns the natural logarithm of the argument.
pow()
16
Returns the value of the first argument raised to the power of the second argument.
sqrt()
17
Returns the square root of the argument.
30
sin()
18
Returns the sine of the specified double value.
cos()
19
Returns the cosine of the specified double value.
tan()
20
Returns the tangent of the specified double value.
asin()
21
Returns the arcsine of the specified double value.
acos()
22
Returns the arccosine of the specified double value.
atan()
23
Returns the arctangent of the specified double value.
atan2()
24
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.
toDegrees()
25
Converts the argument to degrees.
toRadians()
26
Converts the argument to radians.
random()
27
Returns a random number.
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };
However in development, we come across situations where we need to use objects instead of
primitive data types. In order to achieve this, Java provides wrapper class Character for
primitive data type char.
The Character class offers a number of useful class (i.e., static) methods for manipulating
characters. You can create a Character object with the Character constructor –
The Java compiler will also create a Character object for you under some circumstances. For
example, if you pass a primitive char into a method that expects an object, the compiler
31
automatically converts the char to a Character for you. This feature is called autoboxing or
unboxing, if the conversion goes the other way.
Example
// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
Escape Sequences
A character preceded by a backslash (\) is an escape sequence and has a special meaning to the
compiler.
The newline character (\n) has been used frequently in this tutorial in System.out.println()
statements to advance to the next line after the string is printed.
Character Methods
Following is the list of the important instance methods that all the subclasses of the Character
class implement −
32
Determines whether the specified char value is white space.
isUpperCase()
4
Determines whether the specified char value is uppercase.
isLowerCase()
5
Determines whether the specified char value is lowercase.
toUpperCase()
6
Returns the uppercase form of the specified char value.
toLowerCase()
7
Returns the lowercase form of the specified char value.
toString()
8
Returns a String object representing the specified character value that is, a one-
character string.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters.
33
String Methods
34
byte[] getBytes(String charsetName)
13
Encodes this String into a sequence of bytes using the named charset, storing the result
into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
14
Copies characters from this string into the destination character array.
int hashCode()
15
Returns a hash code for this string.
int indexOf(int ch)
16
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
17
Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
int indexOf(String str)
18
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
19
Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
String intern()
20
Returns a canonical representation for the string object.
int lastIndexOf(int ch)
21
Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex)
22
Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
int lastIndexOf(String str)
23
Returns the index within this string of the rightmost occurrence of the specified
substring.
int lastIndexOf(String str, int fromIndex)
24
Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.
int length()
25
Returns the length of this string.
35
boolean matches(String regex)
26
Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int
len)
27
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
28
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
29
Returns a new string resulting from replacing all occurrences of oldChar in this string
with newChar.
String replaceAll(String regex, String replacement
30
Replaces each substring of this string that matches the given regular expression with
the given replacement.
String replaceFirst(String regex, String replacement)
31
Replaces the first substring of this string that matches the given regular expression
with the given replacement.
String[] split(String regex)
32
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
33
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
34
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
35
Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
36
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
37
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
38
Returns a new string that is a substring of this string.
39 char[] toCharArray()
36
Converts this string to a new character array.
String toLowerCase()
40
Converts all of the characters in this String to lower case using the rules of the default
locale.
String toLowerCase(Locale locale)
41
Converts all of the characters in this String to lower case using the rules of the given
Locale.
String toString()
42
This object (which is already a string!) is itself returned.
String toUpperCase()
43
Converts all of the characters in this String to upper case using the rules of the default
locale.
String toUpperCase(Locale locale)
44
Converts all of the characters in this String to upper case using the rules of the given
Locale.
String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.
static String valueOf(primitive data type x)
46
Returns the string representation of the passed data type argument.
37
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.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers.
Example
You can create an array by using the new operator with the following syntax –
Syntax
dataType[] arrayRefVar = new dataType[arraySize];
The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to arrayRefVar.length-1.
Example
38
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.
39
Input and output in Multidimensional Arrays
public class TestClass {
40
Output
012
3456
78
41
Object Oriented Programming In JAVA
Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java
supports the following fundamental concepts −
Polymorphism
Inheritance
Encapsulation
Abstraction
Classes
Objects
Instance
Method
Message Passing
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as
well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type support.
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging
the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields
and behavior is shown via methods.
So, in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
42
Classes in Java
A class is a blueprint from which individual objects are created.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance variables
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In
the above example, barking(), hungry() and sleeping() are methods.
A class can have any number of constructors. We already discussed about constructors.
Each instance variable and methods of a class can have any type of access modifier. We
already discussed about access modifiers.
Object of class is created by same as in Java’s own class: ClassName objName = new
ClassName(); which calls to default or any other constructor.
43
A Simple Case Study
For our case study, we will be creating two classes. They are Employee and EmployeeTest.
Employee is the class without any main() method. This is blueprint of Employee we will use
this in EmployeeTest class which contains main() method. However we can use it any other
class as we needed.
String name;
int age;
String designation;
double salary;
In order for us to run this Employee class there should be a main method and objects should be
created. We will be creating a separate class for these tasks.
Following is the EmployeeTest class, which creates two instances of the class Employee and
invokes the methods for each object to assign values for each variable.
44
public class EmployeeTest {
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Output
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
Syntax
45
Now the object of sub class can call the members or methods of super class if these are declared
as public or protected.
Methods overriding
As a sub class’s object can call public and protected methods of super class, sub class can also
rewrite the same method which is already available in super class and also change the
implementation details of that method (can’t change its signature). After doing this the sub
class’s object can call to sub class method. The rewriting process of super class method into
sub class is known as method overriding. The method implement with final keyword can not
be override in sub class.
Methods overloading
If a class contains multiple methods with the same name but different signatures these methods
are known as overloaded methods. A class contains many constructors as well and this is called
constructor overloading. Whenever a call is performed on such methods the compiler can
identify from the signature of methods and will call appropriate method.
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
Encapsulation
Encapsulation is the process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from outside. It permits the
elements of the class to be accessed from outside only through the interface provided by the
class. Setters and Getters are used for this purpose. Example, setValues() and getValues().
Abstraction
Abstraction means to focus on the essential features of an element or object in OOP, ignoring
its extraneous or accidental properties. The essential features are relative to the context in which
the object is being used.
46
Example − When a class Student is designed, the attributes enrolment_number, name, course,
and address are included while characteristics like pulse_rate and size_of_shoe are eliminated,
since they are irrelevant in the perspective of the educational institution.
this keyword
This keyword is used to the reference of the same class in which this keyword is used. For
example, if you want to call a constructor of the class from the constructor of the same class
then this keyword does this job. Similarly, if you declare same local variable as instance
variables then this keyword is used to differentiate between them.
47
public class Employee {
this(10,”no name”);
}
//public setters and getters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}//end of setters and getters
//a method to display data on console
public void display(){
System.out.println("Employee ID:" + id + "Employee
Name:" + name);
}
//overloaded display method
public void display(int i){
System.out.println("Employee ID:" + id + "Employee
Name:" + name);
}
48
There is no use of super keyword because we never make any inheritance here. Now we will
extend a class from our Employee class to clarify the use of inheritance, overriding and
super keyword.
Now we make Test class to test them and show output as well…
49
public class Test {
public static void main(String[] args){
//create object of Employee class
//by calling its parameterized const.
Employee e = new Employee(89,"M Ali");
e.display(); //call to Employee class display()
Output:
Employee ID:89
Employee Name:M Ali
Employee ID:91
Employee Name:Umer
Qual:Phd
This is using constructor methods, now we will use setters and getters to set values…
50
Output:
Employee ID:89
Employee Name:Ali
Employee ID:91
Employee Name:Umer
Qual:Phd
You can see the use of inheritance; it is clear that it gives reusability of code. If there is no
inheritance then we need to re-implement the code for id and name in our Teacher class.
Think that there is not only a Teacher in real world. There are two many other employees as
well who can reuse this Employee class.
51
Now we will discuss polymorphism using code.
An object can have many shapes if it is in “is-a” relationship. For example, in our Employee
and Teacher class a Teacher is an Employee. We can create an object of Employee and assign
it reference of Teacher…
Employee e = new Teacher();
Here you can see that e is the object of Employee but refer to Teacher. This is known as
Polymorphism.
Before diving into the code example let us discuss two more concepts.
Static Polymorphism (Compile time binding or early binding)
Dynamic Polymorphism (run time binding or late binding)
The binding which can be resolved at compile time by compiler is known as static or early
binding.
Look in our Employee class, there are two display methods i.e. display() and display(int i) these
two are different in signatures but having same name called overloaded method. When we use
a polymorphic object as in our previous example e refer to the Teacher but on object of
Employee. Now e.display(1) will clearly call to Employee’s display(int i) this will resolved
at compile time and called early binding or compile time binding.
On the other hand, run time binding resolved at run time and is performed by overridden
methods. For example, if we call e.display() here display is in Employee and overridden in
Teacher with same name and same signature. Now compiler will decide at runtime which
method is to be called because the object e is Employee’s object but refer to the Teacher. So,
it will call to Teacher’s display at run time. This is known as late binding, run time binding and
dynamic binding.
Output:
Employee ID:10
Employee Name:Ali
52
public class Test {
public static void main(String[] args){
Output:
Employee ID:10
Employee Name:Ali
Qual:Phd
In the generalization process, the common characteristics of classes are combined to form a
class in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-
class. It represents an “is – a – kind – of” relationship. For example, “car is a kind of land
vehicle”, or “ship is a kind of water vehicle”.
Specialization
53
Aggregation or Composition
Aggregation or composition is a relationship among classes by which a class can be made up
of any combination of objects of other classes. It allows objects to be placed directly within
the body of other classes. Aggregation is referred as a “part–of” or “has–a” relationship,
with the ability to navigate from the whole to its parts.
For example, we have a class named “Car” and another class named “CarEngine” as we know
that the car class has its own behaviors and attributes and CarEngine has its own, but a Car
must has an engine. So, we can directly create and object of CarEngine inside Car class as a
instance object of car.
Abstract Classes
Abstract classes are used to define only part of an implementation not complete
implementation. Because, information is not complete therefore the object of abstract class
cannot be instantiated. However, like regular classes, they can also contain instance variables
and methods that are full implemented. The class that inherit from abstract class is responsible
to provide details.
Any class with an abstract method (a method has no implementation like public void method();
) must be declared as abstract.
If a class inherits the abstract class and provide implementation of all abstract methods of its
super class then it will become concrete class (object can be created and instantiate). But if sub
class never gives implementation of any one abstract method of its super class then it will also
become abstract and abstract keyword is written with class name.
“abstract” keyword is used to declare a method or a class to be abstract.
Abstract classes may or may not contain abstract methods, i.e., methods without body
public void get();
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it. Otherwise subclass will also become an abstract class.
Lets we discuss this using code example.
54
Here we have an abstract class having only one abstract method.
public abstract class Shape {
//this is abstact method
//class is also declared as abstract
//it must be extends from other class
//sub class need to be provide implementation
//of this method
Remember abstract method has no implementation details like virtual methods in C++.
The class which inherits it will responsible for providing information of all abstract
methods. The object of the Shape class cannot be instantiated. The Shape class may have
no abstract methods as well and other instance variables too.
Now we extend this Shape class with other class to provide implementation of abstract
methods in Shape class.
public class Circle extends Shape {
//contructor
public Circle() {
//assign fix value for example
x = 5;
y = 5;
radius = 10;
}
55
public class Test {
public static void main(String[] args){
//create object of circle
//this will initiate values
//by calling const.
Circle c = new Circle();
//call to clculateArea()
c.calculateArea();
}
}
Output:
Area = 314.15999999999997
This is useful when we want to force child classes to provide its own implantation of some
methods. For example, a Rectangular class is created and inherited with Shape, now we know
that the formula to calculate area or rectangular is different. So, it will provide its own
implementation.
Abstract class can also provide fully implemented methods. Abstract class can only be
extending and there is no multiple inheritance in Java. For this purpose, we use interfaces.
Interfaces
Interfaces are special java type which contains only a set of methods prototypes, but does not
provide the implementation of methods. All methods inside interface are abstract by default
so it can be called a pure abstract class with zero implementation of methods. Interface can
also contain static final constants.
Keyword interface is used to define an interface in Java.
public interface Speaker{
//here is only one method, but may be many as needed
public void speak(); //no implementation
}
56
//this is interface
//using interface keyword, not class
public interface Speaker {
//only method, may be many as needed
public void speak();
}
Now we will implement this interface in our other classes. The class who implement this
interface must provide the implementation details of speak() method.
public class Coach implements Speaker{
//here we must implement speak()
@Override
public void speak() {
System.out.println("Sports talk...");
}
}
We create three classes here and implements our Speaker interface in all three. You can see
all three classes provide different implementation of speak() method because speaks are
different according to class in which it is implemented.
Now we create Test class to test all these classes.
57
public class Test {
public static void main(String[] args){
//here we create object of Speaker interface
//but can't initialize it with Speaker
//because Speaker class has no implementation
Speaker sp = null;
//with Lecturer
sp = new Lecturer();
sp.speak(); //call to Lecturer speak()
}
}
Output:
Politician talks...
Sports talk...
About Java talks...
Here we also use polymorphism, Speaker’s object changes it shape to Politician, Coach then
Lecturer, using same memory area.
Interfaces are very useful where we want to force classes to provide implementation of some
methods and multiple interfaces can be implanted in one class. It is a contract between class
and interface to implement all the methods of interface.
This is used where we know that a method is necessary but implementation is different for each
class. For example, break() is necessary in every car but different cars have different break()
58
mechanism. So, they can implement its own break mechanism and interface force them to
implement this break() method, because it is necessary in every class.
Java itself provided a lot of interfaces which will we use and provide our own implementation
as we needed. Java’s interfaces will be used extremely throw-out our course.
In the above example if we want to change in understand() of subject then we need to change
in Topic class’s understand() because implantation of understand() is in Topic and Subject class
contains the object of Topic class. Aggregation is also an example of tight coupling.
Loose coupling: In simple words, loose coupling means they are mostly independent. If the
only knowledge that class A has about class B, is what class B has exposed through its interface,
then class A and class B are said to be loosely coupled.
59
public interface Topic
{
void understand();
}
class Topic1 implements Topic {
public void understand()
{
System.out.println("Got it");
}
}
class Topic2 implements Topic {
public void unserstand()
{
System.out.println("understand");
}
}
public class Subject {
public static void main(String[] args)
{
Topic t = new Topic1();
t.understand();
}
}
In the above example we create and interface called topic and then different topic implement
their own understand() method according to their needs and not dependent on Topic directly.
Subject class then call to any Topic class using polymorphic object of Topic class. This is loose
coupling between classes. Interfaces are the example of loose coupling.
Cohesion
In object-oriented design, cohesion refers all about how a single class is designed. Cohesion is
the Object-Oriented principle most closely associated with making sure that a class is designed
with a single, well-focused purpose. The more focused a class is, the cohesiveness of that class
is more. The advantages of high cohesion is that such classes are much easier to maintain (and
less frequently changed) than classes with low cohesion. Another benefit of high cohesion is
that classes with a well-focused purpose tend to be more reusable than other classes.
60
In the above figure you can see class A is low cohesion all the methods are in class A. The
focus is divided in class A i.e. checkEmail() is differ from validateEmail() and all other
methods.
In high cohesion system all these methods are divided in single class for each point of focus.
The implementation details are divided in each class.
High cohesion is when you have a class that does a well-defined job. Low cohesion is
when a class does a lot of jobs that don’t have much in common.
High cohesion gives us better maintaining facility and Low cohesion results in
monolithic classes that are difficult to maintain, understand and reduces re-usability
In general coupling is the concept of between two classes i.e. how much a class depend on
other class. On the other hand, cohesion is the concept of how a class can be well defined and
easy to maintain.
A better system design is to be less coupled and high cohesive.
61