Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Java Notes2 Mid

Java Notes2 Mid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Notes2 Mid

Java Notes2 Mid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Java programming language was originally developed by Sun Microsystems which was

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.

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more sophisticated
IDEs available in the market. But for now, you can consider one of the following −

 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/.

Tools You Will Need


For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz
computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).

You will also need the following softwares −

 Linux 7.1 or Windows xp/7/8 operating system


 Java JDK
 Microsoft Notepad or any other text editor

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.

First Java Program


public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please follow the subsequent
steps −

 Open notepad and add the code as above.


 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there
are no errors in your code, the command prompt will take you to the next line
(Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.

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.

Example: class MyFirstJavaClass

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.

Example: public void myMethodName()

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

Print something on Screen


System.out.print(“your message here”);
System.out.print(variable or literal here);
System.out.print(“your message here” + variable or literal here);
System.out.println(“this will print on new line”);

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 −

Access Modifiers − default, public , protected, private

1. Visible to the package, the default. No modifiers are needed.


2. Visible to the class only (private).
3. Visible to the world, all classes (public).
4. Visible to the package and all subclasses (protected).

Non Access Modifiers

5. The static modifier for creating class methods and variables.


6. The final modifier for finalizing the implementations of classes, methods, and
variables.
7. The abstract modifier for creating abstract classes and methods.
8. The synchronized and volatile modifiers, which are used for threads.

public class className {


// ...
}

private boolean myFlag;


static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;

public static void main(String[] arguments) {


// body of method
}

5
First Java Program
public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
*/

public static void main(String []args) {


System.out.println("Hello World"); // prints Hello World
}
}

Explanation:

Why main?

main() is the function from where the program start.

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?

Indicated that main() does not return anything.

What is String args[]?

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)

A class can contain any of the following variable types.


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

public class MyFirstProgram{

//instance variables, access in class because are private,


//different for each object of this class
private int n1;
private String s;

//this is class variable, same for all objects of this


//class, each object will have same value
public static int number;

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.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

7
for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

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.

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/

public static void main(String []args) {


// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}

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.

Following is an example of a constructor −

public class Puppy {

//constructor have same name of class, having no return type


//this have no parameter, it is provided by java as default if
//we never implement our own
public Puppy() {
}

//this has one parameter, can be many as needed


//implementation of this then java will never provide default
//one we should have to implement default
public Puppy(String name) {
// This constructor has one parameter, name.
}
}

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

Following is the syntax of a constructor −

class ClassName {
ClassName() {
}
}

Java allows two types of constructors namely −

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

Public class MyClass {


Int num;
MyClass() {
num = 100;
}
}
Parameterized Constructors

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;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}

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.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.


 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

Syntax: ClassName objectName = new callToAnyOneConstrucor(Parameters if any);

public class Puppy {


public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

10
public static void main(String []args) {
// Following statement would create an object myPuppy

Puppy myPuppy = new Puppy( "tommy" );

//Puppy is class name, new is keyword, Puppy(“tommy”)


//call to parametrized constructor, because this class
//has no default constructor as we implement our own one
}
}

new Keyword
This keyword is used to initialize the object of a class and initialize memory on heap.

Accessing Instance Variables and Methods


of class
Instance variables and methods are accessed via created objects. To access an instance variable,
following is the fully qualified path –
/* First create an object */
ClassName ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.methodName();
/* Call to static members/methods of class */
ClassName.variableName;
ClassName.methodName();

public class Puppy {


int puppyAge;
static int number;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

11
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );
/*Call to static variable*/
Puppy.number = 10;
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.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 {

public static void main(String[] args) {


// TODO code application logic here
int i;
float f;
double d;

Scanner scan = new Scanner(System.in);

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 two data types available in Java −

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types

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.

boolean, byte 1 byte


char, short 2 bytes
int, float 4 bytes
long, double 8 bytes

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");

Wrapper Classes in Java


A Wrapper class is a class whose object wraps or contains a primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store a primitive
data types. In other words, we can wrap a primitive value into a wrapper class object.

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.

Autoboxing: Automatic conversion of primitive types to the object of their corresponding


wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.

import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';

// Autoboxing- primitive to Character object conversion


Character a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();

// Autoboxing because ArrayList stores only objects


arrayList.add(25);

// printing the values from object


System.out.println(arrayList.get(0));
}
}

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';

// unboxing - Character object to primitive conversion


char a = ch;

ArrayList<Integer> arrayList = new ArrayList<Integer>();


arrayList.add(24);

// unboxing because get method returns an Integer object


int num = arrayList.get(0);

// printing the values from primitive data types


System.out.println(num);
}
}

Stack vs. Heap


Stack and heap are two important memory areas. Primitives are created on the stack while
objects are created on heap. This will be further clarified by looking at the following diagram
that is taken from Java.

16
Java Literals
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.

Literals can be assigned to any primitive type variable. For example −

byte a = 68;
char a = 'A';

Java - Variable Types


This chapter will explain various variable types available in Java Language. There are three
kinds of variables in Java −

 Local variables
 Instance variables
 Class/Static variables

Local Variables

 Local variables are declared in methods, constructors, or blocks.


 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.

public class Test {


public void pupAge() {
int age;
age = 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
Output
Puppy age is: 7

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 {

// this instance variable is visible for any class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {

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 {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" +
salary);
}
}

19
Output
Development average salary:1000

Java - Basic Operators


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −

 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 −

Assume integer variable A holds 10 and variable B holds 20, then –

Operator Description Example


Adds values on either side of the
+ (Addition) A + B will give 30
operator.
Subtracts right-hand operand from
- (Subtraction) A - B will give -10
left-hand operand.
Multiplies values on either side of
* (Multiplication) A * B will give 200
the operator.
Divides left-hand operand by right-
/ (Division) B / A will give 2
hand operand.
Divides left-hand operand by right-
% (Modulus) B % A will give 0
hand operand and returns remainder.
++ (Increment) Increases the value of operand by 1. B++ gives 21
-- (Decrement) Decreases the value of operand by 1. B-- gives 19

20
The Relational Operators
There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example


Checks if the values of two operands are
== (equal to) equal or not, if yes then condition becomes (A == B) is not true.
true.
Checks if the values of two operands are
!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condition becomes true.
Checks if the value of left operand is greater
> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less
< (less than) than the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
>= (greater than or
than or equal to the value of right operand, (A >= B) is not true.
equal to)
if yes then condition becomes true.
Checks if the value of left operand is less
<= (less than or equal
than or equal to the value of right operand, (A <= B) is true.
to)
if yes then condition becomes true.

The Bitwise Operators


Java defines several bitwise operators, which can be applied 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 as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001


21
~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example


Binary AND Operator copies a bit to the (A & B) will give 12 which
& (bitwise and)
result if it exists in both operands. is 0000 1100
Binary OR Operator copies a bit if it (A | B) will give 61 which
| (bitwise or)
exists in either operand. is 0011 1101
Binary XOR Operator copies the bit if it (A ^ B) will give 49 which
^ (bitwise XOR)
is set in one operand but not both. is 0011 0001
(~A ) will give -61 which is
~ (bitwise Binary Ones Complement Operator is 1100 0011 in 2's
compliment) unary and has the effect of 'flipping' bits. complement form due to a
signed binary number.
Binary Left Shift Operator. The left
operands value is moved left by the A << 2 will give 240 which
<< (left shift)
number of bits specified by the right is 1111 0000
operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 will give 15 which
>> (right shift)
number of bits specified by the right is 1111
operand.
Shift right zero fill operator. The left
operands value is moved right by the
>>> (zero fill right A >>>2 will give 15 which
number of bits specified by the right
shift) is 0000 1111
operand and shifted values are filled up
with zeros.

The Logical Operators


The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then –

Operator Description Example


Called Logical AND operator. If both the
&& (logical and) operands are non-zero, then the condition (A && B) is false
becomes true.

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.

The Assignment Operators


Following are the assignment operators supported by Java language −

Operator Description Example


Simple assignment operator. Assigns values C = A + B will assign value of A +
=
from right side operands to left side operand. B into C
Add AND assignment operator. It adds right
+= operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.
Subtract AND assignment operator. It
-= subtracts right operand from the left operand C -= A is equivalent to C = C – A
and assign the result to left operand.
Multiply AND assignment operator. It
*= multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.
Divide AND assignment operator. It divides
/= left operand with the right operand and assign C /= A is equivalent to C = C / A
the result to left operand.
Modulus AND assignment operator. It takes
%= modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
bitwise exclusive OR and assignment
^= C ^= 2 is same as C = C ^ 2
operator.
bitwise inclusive OR and assignment
|= C |= 2 is same as C = C | 2
operator.

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.

Category Operator Associativity


Postfix expression++ expression-- Left to right
Unary ++expression –-expression +expression –expression ~ ! Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> >>> Left to right
Relational < > <= >= instanceof Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= ^= |= <<= >>= >>>= Right to left

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.

Sr.No. Statement & Description

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 −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

To determine the value of the whole expression, initially exp1 is evaluated.

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

Java - Loop Control


There may be a situation when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

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 −

Sr.No. Loop & Description

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.

Sr.No. Control Statement & Description

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.

Enhanced for loop in Java

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection
of elements including arrays.

Syntax

Following is the syntax of enhanced for loop −

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.

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


System.out.print( name );
System.out.print(",");
}
}
}

Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

Java - Numbers Class


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

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.

Following is an example of boxing and unboxing −

public class Test {

public static void main(String args[]) {


Integer x = 5; // boxes int to an Integer object
x = x + 10; // unboxes the Integer to a int
System.out.println(x);
}
}
Output
15

29
Following is the list of the instance methods that all the subclasses of the Number class
implements

Sr.No. Method & Description

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.

Java - Character Class


Normally, when we work with characters, we use primitive data types char.
Example
char ch = 'a';

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

Character ch = new Character('a');

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.

Following table shows the Java escape sequences −

Escape Sequence Description


\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.

Character Methods

Following is the list of the important instance methods that all the subclasses of the Character
class implement −

Sr.No. Method & Description


isLetter()
1
Determines whether the specified char value is a letter.
isDigit()
2
Determines whether the specified char value is a digit.
3 isWhitespace()

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.

Java - Strings Class


Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write −

String greeting = "Hello world!";

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.

public class StringDemo {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

33
String Methods

Here is the list of methods supported by String class −

Sr.No. Method & Description


char charAt(int index)
1
Returns the character at the specified index.
int compareTo(Object o)
2
Compares this String to another Object.
int compareTo(String anotherString)
3
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
4
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
5
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
6
Returns true if and only if this String represents the same sequence of characters as
the specified StringBuffer.
static String copyValueOf(char[] data)
7
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
8
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
9
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
10
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
11
Compares this String to another String, ignoring case considerations.
byte getBytes()
12
Encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.

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.

Declaring Array 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

The following code snippets are examples of this syntax −

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

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

Following statement declares an array variable, myList, creates an array of 10 elements of


double type and assigns its reference to myList −

double[] myList = new double[10];

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.

Input and output in Arrays


public class TestClass {
public static void main(String[] args) {
int[] a;
a = new int[5];
Scanner s = new Scanner(System.in);
//taking input using loop
for (int i = 0; i <= 4; i++) {
a[i] = s.nextInt();
}
//print array using loop
for(int i : a){
System.out.println(i);
}
}
}
Multidimensional Array in Java
In such case, data is stored in row and column-based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

int[][] arr=new int[3][3];//3 row and 3 column

39
Input and output in Multidimensional Arrays
public class TestClass {

public static void main(String[] args) {


int[][] a;
a = new int[2][2];
Scanner s = new Scanner(System.in);
//taking input using loop
for (int i = 0; i <= 1; i++) {
for (int j = 0; j <= 1; j++) {
a[i][j] = s.nextInt();
}
}
//print array using loop
for (int i = 0; i <= 1; i++) {
for (int j = 0; j <= 1; j++) {
System.out.print(a[i][j]);
}
}
}
}

Jagged Array in Java


If we create different number of columns in each row then it is called Jagged Array. Look at
Example: -
public class TestClass {
public static void main(String[] args) {

//declaring a 2D array with odd columns


int arr[][] = new int[3][]; // 3 rows
arr[0] = new int[3]; //3 columns in 1st row
arr[1] = new int[4]; //4 columns in 2nd row
arr[2] = new int[2]; // 2 columns in 3rd row
//initializing a jagged array
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++; //insert values in array
}
}
//printing the data of a jagged array
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();//new line
}
}
}

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.

public class Dog {


private String breed;
private int age;
private String color;

public void barking() {


}

public void hungry() {


}

public void sleeping() {


}
}

A class can contain any of the following variable types.

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

Members of class can be accessed with . operator as we discussed earlier.

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.

public class Employee {

String name;
int age;
String designation;
double salary;

// This is the constructor of the class Employee


public Employee(String name) {
this.name = name;
}

// Assign the age of the Employee to the variable age.


public void empAge(int empAge) {
age = empAge;
}

/* Assign the designation to the variable designation.*/


public void empDesignation(String empDesig) {
designation = empDesig;
}

/* Assign the salary to the variable salary.*/


public void empSalary(double empSalary) {
salary = empSalary;
}

/* Print the Employee details */


public void printEmployee() {
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + 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 {

public static void main(String args[]) {


/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created


empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();

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

Inheritance (is – a relationship)


Inheritance is used to implement “is-a” relationship between classes. It saves code rewriting
and promotes reusability of code.
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Syntax

public class Super {


.....
.....
}
public class Sub extends Super {
.....
.....
}

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.

The super keyword


After method overriding the sub class’s object can call only its own class method which is also
available in super class. The super keyword can be used inside sub class overridden method to
call super class method as super.methodOfSuperClass(). Similarly, super keyword can also
used inside sub class constructor to call the constructor of its super class as super(). In sub
class constructor the super call must be in first line. However, the default constructor of
super class will automatically be called when object of sub class is created.

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.

Setters and Getters


Setters and Getters are methods to allow private instance variables to be visible outside the
class. We can say we use public setters and getters to allow access to our private members
of class. This is known as encapsulation. We can’t give asceses directly but gives by public
interfaces (public setters and getters).

Let’s summarize all these concepts with the help of code.


Read all comments carefully and compare them with all concepts. Hope you will understand
them…

47
public class Employee {

//as we know that every employee has a id and name


private int id;
private String name;

//parameterized constructor to initialize values


//of instance variables
public Employee(int id, String name){

//here id and name are also local vars


//this keyword is used with instance of same name
this.id = id;
this.name = name;
}

//as now java not give default constructor


//so we implement our own
public Employee(){

//here let we call to parameterized const.


//using this keyword
//this will call parameterized conts.

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.

public class Teacher extends Employee{


//yes Teacher is-a employee and has
//id and name too, but we extend it
//with Employee so no need to implement
//but Teacher has qual too so implement here
//qualification may not be common in all Employees
private String qual;
//default constructor
public Teacher(){
//this will auto call to default
//constructor of Employee class
qual = "";
}
//parameterized constructor to intimiaze values
public Teacher(int id, String name, String qual){
//call to Employee const. to set name and id
super(id,name); //must be on first line
this.qual = qual; //this is specific in Teacher class
}
//setters and getters
public void setQual(String qual){
this.qual = qual;
}
public String getQual(){
return qual;
}
//a method to display values of a teacher
//the same method is already present in Employee
//so this method is called overridden
@Override
public void display(){
//here we call display() of super class
//to display name and id
super.display();
System.out.println("Qual:" + qual);
}
}

Read comments carefully and compare them with concepts…

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()

//create object of teacher class


//by calling parametrized const.
//this will also call to super const.
//because we write super() in sub const.
Teacher t = new Teacher(91,"Umer","Phd");

//call to Teacher class display()


//this will also call to super.display()
t.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…

public class Test {


public static void main(String[] args){
//create object of Employee
Employee e = new Employee();
//set values of instance variables
e.setId(89);
e.setName("Ali");
e.display(); //call to Employee class display()

//create objeect of Teacher


Teacher t = new Teacher();
//set values of instance variables
//setId and setName are in super class
//but can be accessed via Teacher sub class
//beauty of inheritance
t.setId(91);
t.setName("Umer");
t.setQual("Phd");
//call to Teacher class display()
//this will also call to super.display()
t.display();
}
}

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.

public class Test {


public static void main(String[] args){

//e is polymorphic object


Employee e = new Teacher(10,"Ali","Phd");

//this call to display(int i) in Employee


//early binding
e.display(1);
}
}

Output:
Employee ID:10
Employee Name:Ali

52
public class Test {
public static void main(String[] args){

//e is polymorphic object


Employee e = new Teacher(10,"Ali","Phd");
//this call to display() in Teacher
//late binding
e.display();
}
}

Output:
Employee ID:10
Employee Name:Ali
Qual:Phd

Generalization and Specialization


Generalization

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

Specialization is the reverse process of generalization. Here, the distinguishing features of


groups of objects are used to form specialized classes from existing classes. It can be said that
the subclasses are the specialized versions of the super-class.

The following figure shows an example of generalization and 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.

public class Car{


private CarEngine carEngine; //this is aggrefation
……
……
}

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

public abstract void calculateArea();

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 {

private int x, y, radius;

//contructor
public Circle() {
//assign fix value for example
x = 5;
y = 5;
radius = 10;
}

//providing implementaion of abstract mehtod


//in super class Shape -> calculateArea()
@Override
public void calculateArea() {
double area = 3.1416 * (radius * radius);
System.out.println("Area = " + area);
}
}

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
}

Keyword implements is used to implement the interface inside a class.


Implementation the interface is like signing a contract. A class that implement interface must
implement all the methods of that interface. If it is not then the class would not compile.
The relationship between class and interface is “respond to”. The class must respond all
methods inside interface.
Let’s discuss it using code example in Java.

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...");
}
}

public class Lecturer implements Speaker{


//here we must implement speak()
@Override
public void speak() {
System.out.println("About Java talks...");
}
}

public class Politician implements Speaker{


//here we must implement speak()
@Override
public void speak() {
System.out.println("Politician talks...");
}
}

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;

//let intilize it with Politician object


sp = new Politician();
sp.speak(); //call to Politicain speak()

//now with Coach


sp = new Coach();
sp.speak(); //call to Coach speak()

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

Unlike inheritance, multiple interfaces can be implemented by one class.


public class MyClass implements Interface1, Interface2,
Interface3{

//here implement all the methods of all the interfaces


//remember class can also have their own implementation
//like a regular class

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.

Coupling and Cohesion in Java


In object-oriented design, Coupling refers to the degree of direct knowledge that one element
has of another. In other words, how often do changes in class A force related changes in class
B.
Tight coupling : In general, Tight coupling means the two classes often change together. For
example, a class A contains the object of class B (Aggregation) then these are tightly coupled,
change in B need to be change in A.
class Subject {
Topic t = new Topic(); //here tightly coupled
public void startReading()
{
//implementation in Topic, if change then change in
//Topic too.
t.understand();
}
}
class Topic {
public void understand()
{
System.out.println("Tight coupling concept");
}
}

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

You might also like