You are on page 1of 65

DATA TYPES -VARIABLES AND

LITERALS
Data Types:

➢ Data is an important part of a program which is said as the ingredient of a program


➢ Variables are meant to store data.
➢ Data is stored only a8er the variable is declared.
➢ Data can be both signed and unsigned.
➢ Nega<ve numbers are stored in the form of 2’s complement

There are Basic built-in datatypes in the compiler of java.


There are four categories of primi<ve datatypes:

• Integral – they can have any numerical value without decimal point.
• Float – Have numerical value with decimal point.
• Char – for storing characters.
• Boolean – for storing true or false.

• Integral data type is divided depending on the size


o byte
o short
o int
o long.
o
➔ Floa<ng point is divided depending on the precision size –
• float -- decimal point is known as float as the decimal point is floated away.

Example: 163.25 is wriRen in the form of man<ssa and exponent as


16325*10^2 i.e 16325E-2.
IEEE standard number 754.
• double – for more precise value a8er decimal.

➔ Char values have 2 bytes (*Java uses Unicode).


• ASCII codes are subset of UNICODE

For A-Z = 65-90


a-z = 97-122
0-9 = 48-57

➔ Boolean – True is represented using ‘true’.


False is represented using ‘false’.

Variables

➢ Variables are names given to store data in memory alloca<on.


➢ Variables are to be declared and ini<alised.

➢Rules to name variables:


• variable names differ in upper and lower cases.
• contains alphabets, numbers and _, $.
• variables may start with an alphabet or _, $.
• it should not contain built-in words like int, float, if, while etc.
• it should not contain the built-in class names.
• name can be as long as possible.
• follow camel cases example- Roll Number, Average Marks.

Literals
➢ constant values(numbers) used in a program.
➢ there are different types of literals:
• int literals- represen<ng integer type.
• float and double literals- represen<ng decimal type.
• char literals-represen<ng characters in single quotes.
• string literals-represen<ng characters in double quotes.

➢ Literals are wriRen based upon the data types:


➔ int literal – int, short and byte.
• int literals can be represented in different number systems:
Decimal.
Binary.
Octal.
Hexadecimal.
• L or l – long.
• F or f – float.
• D or d – double.
• ’’ – char.
• true/false – Boolean.

➢ www.unicode.org
STRING CLASS AND PRINTING
String object:
➢ String is a built-in class available in java.

➢ A string is a collection of characters.

➢ Simplest method for creating a string is String str1=”Java


program”;
➢ Variable of type object are called as reference.

➢ String object is referred to as a literal.

➢ References are used for holding or pointing objects.

➢ String literal is taken in “ “.

➢ Keyword new is taken to create an object in heap.

➢ Constructors are methods or functions used for creating string


object.
➢ There are three types of constructors:
• String(char [ ]).

Array of characters is taken and is converted into string.


• String(byte [ ]).

Array of bytes is taken and is converted into a string.


• String(string).

A string literal is taken in this method.

New string is created using this method.


➢ Java maintains a pool of string constants.

➢ Whenever new is applied the object is created in heap memory


and the memory occupied by the object literal is in pool.
➢ When same literal is used java does not create another object.

➢ When new is applied the object in pool may or may not be


created.
➢ String objects are immutable/ they cannot be modified.

Methods of string class:


➢ The methods creates a new string before giving the results.

➢ The new object is then created in heap memory.

#1.
➢ str.length(): it returns the length of the string mentioned.

➢ str.toLowerCase(): it converts the given characters of string


into lower case.
➢ str.toUpperCase(): it converts the given characters of string
into upper case.
➢ str.trim(): it is used to remove the leading and tailing spaces
from the array if there are any.
➢ str.substring(int begin): it returns a new string by giving the
part of a string from where the index is given.
➢ str.substring(int begin, int end): it works same as the above
but the starting and ending index both can be given in the
substring.
➢ str.replace(char old, char new): it replaces the old character
with the new character.
#2.
➢ str.startsWith(string s): to find the particular starting word
of a the string/to find the initials.
➢ Str.endsWith(string s): to find particular ending word of the
string.
➢ str.charAt(int index): to find the particular character present
on the index given.
➢ str.indexOf(String s): to find the index of the given character.

➢ str.lastIndexOf(string s): to find the index of the given


character from the end of the array.

#3.
➢ str.equals(string s): to check whether the contents of two
strings are equal or not.
➢ str.equalsIgnoreCase(string s): to check whether the contents
of two strings are equal or not but it does not depend upon the
case of characters.
➢ str.compareTo(string s): to compare two strings according to
the dictionary order(in accordance with the ASCII codes for
cases of characters).
➢ str.valueOf(int i): to convert different types of data into
string data type.

Regular Expressions:
They are used to define the symbols.
Matching symbols:
➢ these symbols are meant for single alphabets.

➢ ‘.’ it means any letter or the symbol from the keyboard.i.e for
single alphabet it is true.
➢ [abc]: range or set of characters/ the string is true if the
alphabet is either a or b or c.
➢ [abc][vz]: range of multiple symbol/the string is true if first
symbol is among a,b &c and second symbol is among v & z.
➢ [^abc]: the string is true if the symbol is other than a, b, & c.

➢ [a-z 1-7]: the string is true if the symbol is from the range a-z
or 1-7.
➢ A|B: it is true for single alphabets fro either A or b.

➢ XZ: to check whether the string maybe either a single or


multiple alphabets.

Meta characters:
➢ \d: it will be true if it is a digit among 0-9.

➢ \D: it will be true if it is any symbol other than digits.

➢ \s: it will be true if there is just a space.

➢ \S: it will be true if there are any symbols other than space.

➢ \w: it will be true if it is either alphabet or digits.

➢ \W: it will be true if it is any symbol other than alphabets or


digits.
String matching with regular expressions:
➢ Quantifiers : these are used to define the number of symbols
you want.
• ’*’ it represents number of occurrences of any of the
characters for zero or more times.
• ’+’ it represents number of occurrences of any of the
character for one or more times.
• ’?’ it represents number of occurrences of any of the
characters for zero or one time.
• {X} it represents any of the characters for the size of X
value given.
• {X, Y} it represents any of the characters for the min
and max size given.
OPERATOR AND EXPRESSIONS
Arithme(c operator and expressions:
➢ +, -, *, /, %.
➢ These operators can be applied on any type of data except Boolean.
➢ % operator works on >loat and double data types without taking the
decimal point in quotient but the divisor and dividend contain the
decimal point.
➢ To write down the expression one should be familiar with the
precedence of operators.
➢ *, /, % have higher precedence than +, -.
➢ To change the precedence of operators () are used.
➢ The mechanism of converting data type internally by the compiler is
known as “COERCION”.
➢ Data types of expression:
• The addition, subtraction, multiplication or division
between the byte, short and int results as int as they belong
integer type of data.
• Byte and short are provided by java for backward
compatibility.
• If >loat is used in the expression then the result is >loat.
• If Double is used in the expression then the result is double.
• When char is used the result is int type as char is part of
int(codes).

Increment / decrement operators and


expressions:
➢ Post++, post- -, ++pre, - -pre.
➢ Pre and Post operators both work in same way.
➢ In pre increment/decrement >irst the value is incremented/
decremented and then utilized.
➢ In post increment/decrement >irst the value is utilized and then
incremented/decremented.
➢ The data types remain the same on application of these operators.
➢ These operators cannot be applied to Boolean type of data.

Bitwise operators:
➢ These perform operations on bits of data.
➢ These operations are faster compared to other operators.
➢ Bitwise operators available in java are:
➔ AND &
• result is true if both are true.
➔ OR |
• result is true if any one of the values is true.
➔ NOT ~
• result is inversed.
➔ XOR ^
• result is true if any one of it is true.
➔ Right shift >>
• numbers are shifted to right by one unit and the empty space is
>illed by ‘0’.
➔ Unsigned right shift >>>
• this operator extends the right shift operator.
➔ Left shift <<
• numbers are shifted to left by one unit and the empty space is
>illed by ‘0’.
➢ These operators can be performed on only integer type of data.

Bit Merging and Masking:


➢ One of the aplication of bitwise operators.
➢ They are used to check whether the bits are marked as zero or one.
➢ The process of setting one of the bit as ‘1’ is known as merging (using
or operator).
➢ To check if the bit is on or not by using and operator is known as
masking.
➢ 4 bits is also known as nibble.
➢ XOR operation is used for Swapping two numbers without inserting
any third number.

Widening and Narrowing:


➢ It is related to conversion of data type of given data item.
➢ Widening: the process of storing the data of smaller size data type
into a larger size data type can be done automatically by the compiler.
• The compiler directly converts the data type without showing
any errors i.e from source data type to the destination data
type.
• Since it is done internally it is said as automatically.
• The source and destination data type should be compatible.
• it is also known as upcasting.
➢ Narrowing: the process of storing the data of larger size data type
into a smaller size data type.
• due to difference in size it may lead to loss of data.
• it is not compatible.
• typecasting is required for narrowing.
➢ Boolean is compatible only with Boolean.
LOOPS
➢ Loops are repeating statements.
➢ There are four types of loops.
➢ In loops the steps are repeated till the given condition is reached.

WHILE, DO…..WHILE LOOP


➢ While loop:
!syntax: while(condition)
{
----------
----------
}
Example program

class Test
{
Public static void main(string args[])
{
int i=1,n=100;
while(i<n)
{
System.out.println(i);
i=i*2;
}
}
}

➢ The steps are executed if the condition is true.


➢ The condition is checked Cirst and the process is followed.
➢ It is a pre-tested loop
➢ If the condition is false then the process is never executed.
➢ Do…while loop
!syntax: do
{
------
------

}while(condition)

class test
{
public static void main(string args[])
{
int i=1,n=100;
Do
{
System.out.println(i);
i=i*2;
}while(i<n)

➢ First the process is followed and then the condition is checked.


➢ It is a post-tested loop.
➢ If the condition is false then the process is executed atleast once.
➢ The both loops work for the same purpose.
➢ But do….while loop is more suitable than while loop.

For loop:
➢ For loop is a counter controlled loop.
➢ It is the most frequently used loop.
➢ Syntax: for(initialization; condition; updation)
{
------
-------
}
class test
{
public static void main(string args[])
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}

➢ At Cirst step a variable is initialised.


➢ At next step the condition Is checked.
➢ At third step the body is executed.
➢ At fourth step the updation is done.

Nested loop:
➢ For loop inside a for loop is he example of nested loop.
➢ The above one is used commonly.
➢ The working of the body is more than one dimensional.
➢ Nesting of any two types of loops can be done.
➢ Nested for loop may create the dimensional loops.
Example program for nested for loop
class test
{
public static void main(string args[])
{
for(int i=1;i<5;i++)
{
for(int j=1;j<5;j++)
{
System.out.println(i+”,”+j);
}
}
}
}
ARRAYS
One-Dimensional ARRAY:
➢ Array is a collection of similar data elements.
➢ In java the array size is given after creating the new object.
As int A[]= new int[x];
Where A[] is the reference and int[x] is the object.
Where object is created in the heap.
And the reference is either in stack or heap.
➢ Location of characters in array can be accessed by using their index.
➢ Every array in java has length as its property which can be accessed
by using “array-name.length”.
➢ For loops are most frequently used for arrays.
➢ Using for loop all the elements in the arrays can be accessed/
elements in array can be transveresed using arrays.
➢ Java has introduced for each loop for accessing arrays in version java
1.5 or java 5.
➢ For each loop: syntax for(type var : array)
{
Statements using var;
}
Example program:
class test
{
public static void main(String args[])
{
int A[]={2,4,6,8,10}
for(int i=0;i<A.length;i++)
{
System.out.println(A[i]);
}
for(int i=A.length-1;i>=0;i--)
{
System.out.println(A[i]);
}
}
}

Two-Dimensional ARRAY:
➢ Two-dimensional array are suitable for matrices and tabular form.
➢ Syntax for creating two-dimensional array in java is
: int A[][] = new int [3][4].
➢ It is also known as array of arrays or collection of arrays
➢ Object is created In heap but the reference may or may not be created
in heap.
➢ Array_name.length gives number of rows.
➢ Array_name[index].length gives the number of columns.
Example program:
class test
{
public static void main(String args[])
{
int A[][];
for(int i=0;i<A.length;i++)
{
for(int j=0;j<A[0].length;j++)
{
System.out.println(A[i][j]);
}
System.out.println(“\n”);
}
}
}

➢ In for each loop the array have no integer elements but the reference
elements.
➢ Syntax of for each loop for two dimensional array:
for(type var :array)
{
for(type var1 :type var)
{

Statements using
var(type var 1);
}
}
Example:
class test:
{
public static void main(String args[])
{
int A[];
for(int x[]:A)
{
for(int y:x)
{
System.out.println(y);
}
System.out.println(“\n”);
}
}
}

➢ Jagged array is a type of array in which the members are of different


sizes.
➢ In jagged array the members of arrays are created separately
according to their sizes using their indices.
METHODS
What are methods:
➢ Methods are members of classes which provide functionality for
classes.
➢ We can write our own methods in the classes.
➢ The functions performing on the data are known as methods.
➢ When a method returns a value then the method itself takes the
value.
➢ A method will have its own copy of variable.
➢ Skeleton of method:
returnType methodName(parameter list) !signature/header
{
--------------
--------------
}
Example program:

class test
{
static int max(int x, int y)
{
x++;
if(x>y)
return x;
else
return y;
}
public static void main(String args[])
{
int a=10,b=15,c;
c=max(a,b);
System.out.println(c);
}
}
Passing object as parameters:
➢ To call a method from main method it is needed to be maid static.
➢ When the method is called the value of actual parameters are copied
in formal parameters which is the only parameter passing method in
java.
➢ The address of object in formal and actual parameter is Same.
➢ String cannot be modiIied as it is immutable.
➢ A method can also return an object.
Example program:

class test
{
static void update(int A[])
{
A[0]=25;
}
public static void main(String args[])
{
int A[]={2,3,4,5,6};
update(A);
System.out.println(A[0]);
}
}

➢ A method can have its object as the return type.

Parameter passing in java.


➢ Whoever is calling a method is called as a caller or a method call.
➢ The method which is called by a caller is known as called method.
➢ The parameters/arguments passed in calling method are called as
actual parameters.
➢ And the parameters of a called method are called as formal
parameters.
➢ Formal parameters are nothing but input into a method where the
return type is known as output to a method.
➢ The contents of actual parameters are copied in formal parameters is
the only method of parameter passing in java.
➢ Passing of objects also follow the same method.
➢ Parameter passing for primitive datatypes the values are copied in
formal parameters, whereas in parameter passing of objects the
reference of the object id is copied in formal parameters.
➢ In short the primitive datatypes are passed by value and the objects
are passed by reference.
Example program:

class test
{
int add(int x, int y)
{
int z;
z=x+y;
return z;
}
public static void main(String args[])
{
int a=10,b=5,c;
c=add(a,b);
System.out.prinlt(c);
}
}

Method overloading:
➢ Method overloading means writing more than one method having
same names but different parameter list or data types.
➢ Compiler will call the corresponding method depending upon the
parameter list.

Variable arguments:
➢ It is nothing but writing a single method which can run for number of
parameters of same data types.
➢ For example – void show(int …x)
Where … represents the variable arguments.
➢ It is similar to ellipsis in c/c++.
➢ The parameters passed are converted into an array.
➢ The parameters can be directly passed using an anonymous array.
➢ Variable argument should always be the last parameter.
➢ Printf is based on variable arguments in version 1.7 java.

Command line arguments:


➢ Java programs can utilize command line arguments.
➢ Dos Iile is used for command line arguments.
➢ There are different commands like.
• cls: to clear the screen.
• dir : to display the contents of the disk.
• cd windows : to change the directory.
➢ C: \Windows> dir v*.*
• the above is command line in which
Dir is command and v*.* is an argument
RECURSION
➢ A recursive method is the one which will call itself.
➢ When the recursive function can not call itself further because of the
base condition it will return back along the same path.
➢ Not to make the program lengthy loops are used instead of recursive
functions.
➢ The recursions are used in problem solving.
Object-Oriented Programming
➢ Principles Of Object-Oriented Programming
• Principles of Object-Oriented programming are
• 1.Abstraction.
• 2.Encapsulation.
• 3.Inheritance.
• 4.Polymorphism.

▪ 1.Abstraction
• Abstraction means hiding internal details and showing the required
things.

For Example
Consider a man driving a car, while driving he focus on using of steering, gear,
accelerator etc.
He does not require to know the inner mechanism of the car.

▪ 2.Encapsulation
• Encapsulation is the process of grouping data in a single section.

For Example
Complete television is single box where all the mechanism are hidden inside the
box all are capsuled.

▪ 3.Inheritance
• Inheritance means designing an object or a class by re-using the
properties of the existing class and object.
• Inheritance is same as specialization.
For Example
A old style television (idiot box) is transformed with extra features into slim and
smart television where it re-used the properties of old television.

▪ 4.Polymorphism
• Polymorphism is a concept in which we can execute a single
operation in different ways.
• polymorphism is same as generalization.

➢ Class VS Object
• Object is deEined in terms of its properties and behaviour.
• Operation of behaviours will affect the properties.
• Anything in the world can be deEined in the terms of properties and
behaviour.
• For a single class wee can have many objects.
• Multiple number of objects can be created by one single class

For example
A house or a car or a television is an object but the design or blueprint of the
objeect is a class.

Example Program
class Television
{
private int channel;
private int volume;

public void changechannel()


public void changevolume()
}
class test
{
public static void main()
{
Television t=new Television();
t.changechannel(10);
}
}

• In java there is an area inside main memory which is known as


method area which contains all the methods.
• The deEinitions of the will be present inside the heap, as the objects
will be based on the deEinitions so the objects are also present in
heap.

➢ Data Hiding
• Usually data is hidden and the operations are made visible and
operations or methods are performed over the data

For example
Actual operation of the television is performed in the circuitry which is done by
pressing a button.so the circuitry is data and operations are methods where the
data is hidden inside the box.

Example Program
class Rectangle
{
public int length;
public int breadth;

public int area()


{
return length*breadth;
}
public int perimeter ()
{
Return 2*(length+breadth);
}
class test
{
public static void main()
{
Rectangle r=new Rectangle();
}
}

• In above example there is given two data members length and


breadth which are the properties of the class.
• And the area and perimeter is the method of the class where both the
methods are performing the operations on the given data.
• For hiding the data, the data members will have the stricter (private)
success modiEier.
• So, when the data is made private, we can’t access that data outside
the class.

➢ Types of Proper:es
• Read and writable property.
• getLength() method will allow us to read the property and
setLength() method will allow us to write the property .
• Read only property.
• When there is no modiEication to the property then read only
property is used.
• Write only property.
• Only set method is used for writing the property where no get
method is used.

➢ Constructors
• A method is required for Initialization of properties at the time of
construction of an object, this method is known as constructor.
• Constructor is a method of class called when an object is created.
• Every class will have a default constructor provided by java compiler.
• Constructor will not have any return type.
• There are two types of constructors
o 1. parameterized
o 2. Non-parameterized.
• Non-parameterized constructors is a replacement for default
constructors.
• Constructors can be overloaded.
INHERITANCE
➢ Generaliza)on VS specializa)on

Common thing in Generalisation and Specialisation is they are in the


form of Hierarchy
It is Like a Parent Class and Child Class(or)Base Class and
Derived Class(or) Super Class and Sub Class.

➢ Generalization
In Generalisation group of classes are referred with Super class with
single name.
Generalisation means Bottom Up.
In Generalisation A Super Class Is made by Grouping Multiple Sub
Classes.
Generalisation is achieved using Interfaces.

For Examples
* Generalization
1.Smart Phone - I phone
Samsung
Vivo

2.Vehicle -Car
Bike
Ship

3.Shape -Triangle
Rectangle
Circle

For achieving Generalisation Abstract Classes are Used.


➢ Specialization
In Specialisation a new Sub Class is Generated by borrowing the
features of existing concrete class and adding new features to it.
Specialisation means Top Down.
In specialisation a new Class is derived from an existing Super Class.
Specialisation is achieved using Inheritance.

For Examples
*Specialization

.I Phone X -> I Phone XS


2.Innova -> Fortuner
3.Circle -> Cylinder
4.Guitar -> Electric Guitar

➢ What Is Inheritance?
I Inheritance is the process of acquiring features of an existing Class
into a New Class.
A Class will have Properties and Method.

For Example
A cylinder can acquire all the properties of circle Plus it can have extra
feature
Where we can write a class cylinder inheriting from class circle

A Cuboid can Acquire All the Propertied of A Rectangle Plus Extra feature

Example Program
class Circle
{
private double radius;
public Circle( )
{
radius =0.0;
}
public double area();{}
public double perimeter();{}
};

class Cylinder extends Circle


{
private double height;
public Cylinder()
{
height=0.0;
}
public double volume();{}
};
class test
{
public static void main()
{
Circle c1=new Circle();
Cylinder c2=new Cylinder();
}
}

Circle and Cylinder are the two classes where circle class is having radius
and Cylinder Class acquire the property(radius) of circle with an extra
property that is height.
Cylinder is the Extension of Circle.
extends is the keyword used for Inheritance.
Circle Class Is Parent Class.
Cylinder Class is the Derived Class, Derived Class is also known as
Specialised Class.
In the given example upon the object c1 and c2 the constructors are called
automatically.
In object c1 methods area and perimeter are called
In object c2 methods area.

➢ Constructors in Inheritance
Constructors are the methods of class which are automatically called
when an object is created.
Constructors are executed from Top to Bottom Class.
To make the child class object Pirstly the parent class constructor must be
created

Example Program
class Parent
{
public Parent()
{
System.out.println(“Parent Constructor”);
}
}
class Child extends Parent
{
public Child()
{
System.out.println(“Child Constructor”);
}
}
class Grandchild extends Child
{
public Grandchild()
{
System.out.println(“Grand Child Constructor”);
}
}
class inheritanceDemo
{
Grandchild g=new Grandchild();
}
In the given example Parent Class have its constructor where “parent
constructor” is executed, and Child Class have its constructor where “Child
Constructor”, is executed and Grandchild Class have its constructor where
“Grandchild Constructor” is executed.
In the given example program if a Grandchild class object is created then
as we know Grandchild class inherits Child class constructor and Child class
inherits Parent class constructor so the Grandchild object Pirst executes the
top most class then level by level.


For Example
Car companies manufacture a platform (skeleton of a car)
They will give the shape to a car then first they will create a base which has engines ,seats
etc. and above that they will put a cabin on it so the platform will be same for more of the
cars of that company only the outer body of the cars will be different

Relating to the given program here the platform is the parent class and the base and cabin
created is the child class where the base and cabin is inheriting from the platform

➢ Method Overriding
RedePining the method of the Super Class in the Sub Class.
Method will be called depending on the object.
Method overriding is achieved in Inheritance.
class super
{
public void display()
{
System.out.println(“Hello”);
}
}
class sub extends super
{
public void display()
{
System.out.println(“Hello Welcome”);
}
}

When the sub class object is called then the display method inherited
from the super class is shadowed and the sub class display method is
executed.
Super Class method never be called upon the object of Sub Class.
In the given example program the super class have a method called
display which is saying hello and another class sub class is taken where it
inherits the display method from super class and redePines the method.
When a super class reference holding the object of sub class and
overridden method is called then method of object will be called it is
Dynamic Method Dispatch.

➢ Dynamic Method Dispatch


It is useful for achieving Runtime Polymorphism.

Example Program
class Super
{
Void meth1()
{
System.out.println(“meth1”);
}
Void meth2()
{
System.out.println(“super meth2”);
}
}
class Sub extends Super
{
Void meth2()
{
System.out.println(“sub meth2”);
}
Void meth3()
{
System.out.println(“meth3”);
}
}
class test
{
public.static.void.main()
{
Super s=new Sub();
}
}

In the given example meth2 is redePined in the sub class.


Super Class reference can have Object of Sub Class but a Sub Class
reference cannot have Super Class Object.
A Super Class Reference can hold the Object of Sub Class but it can call only
those methods which are present in super class.
Methods are called depending on the object not the reference then the
overridden object is called it is Runtime Polymorphism.
Dynamic Method Dispatch means calling a Method dynamically because
program make the decision at runtime for which object to be called.
➢ Do’s and Don’ts of Overriding
Signature must be same in method overriding.
If the method name is different the method is not overridden but it is
overloaded.
Argument may be different but the parameter must be same.
Return type must be same, if it is not same then the method is neither
overridden nor overloaded.
Final and static methods cannot be overridden.
Method can be overridden with same or lenient (public, protected) access
speciPiers but the stricter(private) access speciPiers cannot be used in sub
class.

➢ Polymorphism using Overloading and Overriding


Polymorphism is one of the principles of Object-oriented-programming,
polymorphism means one name different actions.
Poly means ’many’, morphism means ’forms’.
Polymorphism is achieved using method overriding and overloading.
In method overloading access speciPiers, return types are same but
number of parameters or type of parameters are different.
In overloading number or type of argument will decides which method is
to be called.
Overloading is achieved in same class whereas overriding is achieved in
inheritance.
In method overriding signature is same but in overloading signatures
must be different.
Method calls are different in overriding it depends on object.
Method overriding is used for runtime polymorphism and method
overloading is used for compile time polymorphism.
ABSTRACT CLASSES
➢ What is an Abstract Class?
• There are two types of classes Abstract class and Concrete class
• If abstract keyword is used before the class then it is an Abstract
Class if nothing is written before class then it is a Concrete class
• Object of an Abstract class cannot be created but object of Concrete
class can be created
• reference of abstract class is allowed

Example program
//asuper bstract class
abtract class Super
{
Super()
{
System.out.println(“Super”);
}
void meth1()
{
System.out.println(“meth1”);
}
abstract void meeth2();
}

//concrete class
class sub extends Super
{
Void meth2()
{
System.out.println(“meth2”);
}
}
class test
{
public static void main()
{
Super s1; // reference of abstract is allowed
sub s2 =new sub();
}
}
• Method which is not having a body is known as Abstract method,
the method must be declared as abstract
• The abstract method is unde7ined method
• A class is Abstract class if at least one of the methods is abstract
• If any other class inherits abstract class then that class also becomes
abstract class but to become a concrete class the subclass must
override the unde?ined method
• A class becomes useful if it overrides all the methods of abstract class
• Abstract classes are used for imposing standards and sharing
methods
• Sub classes are meant for following standards

➢ Do’s and Don’ts of Abstract Class


• An Abstract class cannot be ?inal because if it is made ?inal then it
cannot be extended whereas abstract class is meant for
inheritance
• An Abstract method cannot be ?inal because if it made ?inal then it
cannot be overridden whereas Abstract method is meant for
overriding
• Abstract Class and method can neither be ?inal nor static
• A Sub class must override an abstract method or else it will become
abstract class
Sta$c and Final
➢ Sta$c Members
• Static Keyword is used for representing Meta Data (data about data).
• It is useful for representing the information of a class.
• Static members belongs to a class and they can be shared by all the
objects of the class and all the objects have their own non-static
members .
• All the object can use the static variable as a shared data.
• Static members can be accessed just by using class name.
• The static members of a class are created in the method area.
• Static methods can access only static members.

Example Program
class HondaCity
{
static long price=10;
int a,b;
static double OnRoadPrice(String city)
{
Switch(city)
{
Case “Delhi”:
return price+price*0.1;
case “Mumbai”:
return price+preice*0.09;
}
}
}
class test
{
public static void main()
{

• From the given example the “price=10” is the meta data of the class
HondaCity.
➢ Sta$c Blocks
• Set of statements are written in the form of blocks and are made
static.
• It is used to initialise static data member.
• It is executed before the main method at the time of class sloading.

➢ Final Members
• Values of Linal variables are Lixed, once the value is assigned then it
can’t be modiLied.
• Final variables are written in capital letters.
• Final variable can be initialised while declaring the variable, or it can
be initialised in a static block, or else it can be initialised inside
constructor of a class.
• As constructors can be overloaded then the Linal variable must be
initialised in every constructor.
• Final method cannot be overridden.
• A Linal class cannot be extended.

Example Program
class My
{
final int MIN=1;
final int NORMAL;
final int MAX;

static
{
NORMAL=5;
}
My()
{
MAX=10;
}
}

➢ Singleton Class
• A class which can create only one object is called singleton class.
• Constructors are made private to and object of the singleton class is
written in static method.
• In singleton class getInstance() method is used.
Excep&on Handling
➢ What are Excep,ons?
• Exceptions are Runtime Errors.
• There are various types of errors
o Syntax Error
o Logical Error
o Runtime Error.
o
• Syntax Error
• Syntax and Logical errors are faced by Programmers, and runtime
errors are faced by user.
• Spelling or grammatical mistakes are syntax errors, for example
using uninitialised variable it and using unde@ined variable etc and
missing a semicolon etc.
• Syntax errors can be removed with the help of compiler.

• Logical Error
• Logical error is a bug in program that it to operate incorrectly, for
example missing parenthesis in the calculation.
• Logical errors are removed with the help of debugger.

• Runtime Error.
• Mishandling of a program causes Runtime error.
• Causes of runtime errors are bad input, unavailability of resources.
• Major problems with runtime errors is program will crash.
• Exception handling is process of responding to the runtime errors.
➢ How to Handle Excep,ons
• Try and Catch Exceptions

Example program
public class MyClass
{
public static void main(String[] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println(“Something went wrong.”);
}
}
}

• The try statement allows you to de@ine a block of code to be tested for
errors while it is being executed.

• The catch statement allows you to de@ine a block of code to be


executed, if an error occurs in the try block.

• The try and catch keywords come in pairs.

• A try block can have Multiple catch blocks

• Try and catch block can be nested.

• When a try catch block is present in another try block then it is called
a nested try catch block.
➢ Class Excep,on
• Object is the mother class for all the java classes.
• Exception is the parent class for all the exceptions.
• ClassNotFoundException this exception is raised when the object is
used but the class is not found.
• IOException accessing input output, mostly accessing @iles where
@iles are not there or @ile is corrupted one of the famous exception is
the FileNotFoundException.
• InterruptedException it is related to Multithreading if a thread
stops abnormally it throws an Interrupted exception
• NumberFormatException when input is given as a number string
form but not have a proper number, then it throws
NumberFormatException.
• RuntimeExceptions under these there are ArithmeticExceptions,
IndexOutOfBoundException, NullPointerException.

• Exception classes are categorised into two types checked exception


and unchecked exception.
• Checked exception must be handle by try and catch, java compiler
forces you to write try and catch.
• Unchecked exception are not mandatory to be handled Only Runtime
Exceptions are the unchecked exceptions.

• Methods of class exceptions used for Error Message


o string getMessage()
o string toString()
• these method returns a string with a message written about
exception, purpose of both the methods is same, but the usage of both
the methods are different.
➢ Throw VS Throws
• throw keyword is used to throw an exception logically.

• Only one exception can be thrown at a time by using throw keyword.


• It is used within the method.
• It is followed by instance variable.
• throws is used for declaring that a method may throw exception
• throws is written in signature of method

Example program
public class GFG {
public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
e.printStackTrace();
}
}
}

Example program
import java.io.IOException;

public class UseOfThrowAndThrows {

public static void main(String[] args)


throws IOException
{
}
}
➢ Try with Resources

• All the things that are outside the program are resource to a program.
• Heap is also a resource to a program.
• Whenever a program needs a resource it should acquire it and when
do not need we should return it.
• To write an object in heap we write new.
• In java heap memory objects are deallocated automatically by
garbage collector.
• Finally keyword is used in association with a try/catch block.
• Finally keyword is meant to execute whether an exception occurs or
not.
• Resources are needed to be closed in @inally block.
• The try-with-resources statement is a try statement that declares one
or more resources.
• The try-with-resources statement ensures that each resource is
closed at the end of the statement. 

Example program
static String readFirstLineFromFile(String path) throws
IOException
{
try (BufferedReader br =new BufferedReader(new
FileReader(path)))
{
return br.readLine();
}
}
MULTI-THREADING
WHAT IS MULTI_PROGRAMMING:
➢ Running more than one program that is running multiple programs
on a single machine or a computer is known as multi-programming.
➢ The idea of multiprogramming started from the utilisation of the CPU
when it is idle as the CPU works for just few time in the whole hour.
➢ There are different form of multi-programming.
➔ Multi-user: more than one user using the machine / running their
programs simultaneously.
• for connecting more than one user to single computer the
DUMMY TERMINALS were used.
• here the ROUND ROBIN fashion was introduced as the
programs were executed simultaneously.
• UNIX and LINUX are famous operating systems for the multi-
user environment.
• Multi-user machines were known as TIME_SHARING
machines.
➔ Multi-Tasking: single user runs multiple tasks simultaneously.
• here the CPU runs the programs alternatively on high rate.
• WINDOWS and MacOS(OS X) operating system supports
this type of environment.
➔ MULTI_THREADING: it is a type of multi-threading where there are
different tasks going on under a single application.
• threads are light weighted compared to the task.
• CPU runs the threads alternatively where the user fells the
threads running all together.
• examples: animation, application, gaming, websites,
webserver
CONTROL FLOW OF A PROGRAM
➢ A single program in java contains one control Flow.
➢ Entry point of the program is main method which executes at First.
➢ Example program:

class Test
{
static void display( )
{
s.o.p(“HELLO”);
}
p.s.v main(…)
{
display( );
s.o.p(“WORLD”);
}
}

➢ The second method which executes is the calling method.


➢ The third method which Is executed is the called method.
➢ The above program is example explaining that the main method is the
only thread which controls the Flow of the program.
➢ It is just like getting a reference of a page while reading a book.
➢ If there is an inFinite loop in the display method then the Flow of
program does not executes further so there needs to be two Flow of
controls to execute the program.

MULTITHREADING USING THREAD CLASSES


➢ Java provides thread class and runnable interface to achieve
multithreading.
➢ Thread class contains the actual mechanism for multithreading.
➢ In java a class can extend from only one class.
➢ Runnable interface is used to extends class from some other class
➢ To achieve multithreading there need to be a class extending another
class.
➢ Example program using thread class:

class MyThread extends Thread


{
public void run( )
{
Int i=1;
while(ture)
{
s.o.p(i+”hello”);
i++;
}
}
}
class Test
{
p.s.v main( )
{
MyThread t=new MyThread();
t.start( );
int i=1;
while(true);
{
s.o.p(i+”world”);
i++;
}
}
}

➢ Run is the starting point of a program for multithreading.


➢ There should be a class having all the features for multithreading like
the one in the above program.
➢ the object of thread class is created in the main method.
➢ The start method call the thread class and runs the method which is a
built in method of thread class.


➢ Example program using runnable interface:

class My implements Runnable


{
public void run( );
{
Int i=1
while(true)
{

s.o.p(i+“hello”);
i++;
}
}
}
class Test
{
p.s.v main( )
{
My m=new My( );
Thread t=new Thread(m);
t.start( );
int i=1;
while(true)
{
s.o.p(i+”world”);
i++;
}
}
}
Interfaces are implemented.
➢ The class becomes abstract if it does not implements all the features
of interface.
➢ In the above program it gives the example that the object also runs
when the thread runs.

STATES OF A THREAD
➢ The First state of the thread is new it stores the object of the thread.
➢ To run the object of thread the start method is called.
➢ When start method is called then it is entered into the ready state
where it is ready to run.
➢ Then it enters into the running state.
➢ After completing the task it will enter into the terminated state.
➢ A thread which is terminated is just like a thread which is killed.
➢ Therefore the different states of thread are
NEW ! READY ! RUNNING ! TERMINATED
➢ While running the thread may also enter into different states like:
• WAIT STATE: waiting for acquiring some resource or made to
wait by some other thread.
• TIME WAIT STATE: to make the thread to delay for some time
using the sleep method, it is also known as sleep state
• WAIT AND NOTIFY: where the thread is to be in the waiting
state to get to its chance till it gets notiFied.
• BLOCKED STATE: it is just like entering into the monitor where
the thread is being locked for some time, it is similar to waiting
state.

THREAD PRIORITIES
➢ JAVA supports thread priorities from 1-10.
➢ Execution of threads depends upon scheduler.
➢ If a thread is having higher priority then it should get some
preference over other threads.
➢ In java there are different levels of priority that are:
• MIN_PRIORITY=1.
• NORM_PRIORITY=5.
• MAX_PRIORITY=10.
for example:
In MS Word one thread takes the input from the keyboard, another thread
checks for the spellings which works simultaneously, another thread which
works to auto save the document.
In the above the First priority is given to the thread which takes the input

➢ The priority of default thread is always 5.


➢ The higher priority is given to the thread which gets the input or the
data.
➢ The thread with higher priority gets the more CPU time.
➢ Multithreading features are provided by the operating systems but in
java JVM have its own scheduler.

THREAD CLASS
➢ Object of the thread class can be created.
➢ Whenever a thread is created it gets some IDE.
➢ Threads can be identiFied by mentioning their names.
➢ There are different constructors to give the thread classes:
➔ Thread( )
• it is a default class.
➔ Thread(Runnable r)
• the thread contains the runnable interface.
➔ Thread(Runnable r, String name)
• the thread class have its own name with runnable interface.
➔ Thread(ThreadGroup g, String name)
• thread group to manage various threads together.
For example:
Different types of balloons or balls in an animation having their own
thread classes is the example for the thread group.

➔ Thread(String name)
• the thread class have its own name.

➢ There are various getter and setter methods:


➔ long getId( )
• to get the id of particular thread.
➔ String getName( )
• to get the name of the thread mentioned.
➔ int getPriority( )
• to know the current priority of the thread.
➔ Thread.state getState( )
• to get to know the state of the thread .
➔ ThreadGroup getthreadGroup( )
• to know the group to which the thread belongs.

➔ void setName(String name)


• to set the Name of the thread class.
➔ void setPriority(int p)
• to set the priority of the thread class.
➔ void setDaemon(Boolean d)
• to set a background thread with least priority with no user
interaction.

For example:
The garbage collector in the JVM which have the least priority.
➢ There are different methods for the enquirying the thread classes:
➔ boolean isAlive( )
• to check if the thread is alive or terminated.
➔ boolean isDaemon( )
• to check if the thread is acting as a daemon or not.
➔ boolean isInterrupted( )
• to check whether the thread is interrupted by some other
methods or not.

➢ There are different instance methods for the thread classes:


➔ void interrupt( )
• it is used to interrupt the thread mostly in the state of waiting
or sleeping.
➔ void join( )
• instead of terminating the thread is been kept waiting to join
with other thread until it is completed using the join method.
➔ void join(long millis)
• it is used to join the main function with other for a period of
time.
➔ void run( )
• it has the actual functionality of thread and it can be overided
➔ void start( )

➢ There are different static methods for the thread classes:


➢ These can be called by just using the class name.
➔ Int activeCount( )
• it gives the number of threads active in a particular group.
➔ Thread currentThread( )
• to get the reference of the current or the running thread.
➔ void yield( )
• To give the indication for the thread with higher priority to
wait for sometime to let the threads with low mpriority to
Finish their job.
➔ void dumpStack( )
• to know the contents in the stack or to know the depth of the
stack.

SYNCHRONIZATION
➢ DeRinition: it is the coordination or understanding between two
entities.
➢ In multithreading it is usually used between threads.
➢ Terms important to learn synchronization in multithreading:
➔ Resource Sharing:
• it is like more than one thread accessing same resource like
File, network connection, data objects etc
• if there is an object in the heap then it can be accessed by
multiple threads.
• then than object becomes the shared resource.

➔ Critical Section:
• the lines of code in a thread which are accessing the
shared resource/object is the critical section.
• it is said to be a piece of code which is critical.

➔ Mutual Exclusion:
• the mutual exclusion states that the accessing of one
thread prevents the accessing of another.

➔ Locking/Mutex:
• Mutex is the variable used for locking the threads.
• if the mutex variable is set to zero then it is free or it is
not occupied.
• when the time period of one thread is Finished then the
another thread cannot access the object as the mutex will
not remain zero.
• thread two can access the object if and only if the mutex
is zero again.
• for every shared resource there should be a lock which is
being applied by the thread itself.
• here the threads are responsible for mutual exclusion.
• mutex was not useful as the threads would be
overlapping each other if the mutex was not being locked
by the First one.

➔ Semaphore:
• semaphore was like an operating system before the
introducing of java to control the coordination of threads
as they should not overlap.
• it was supported by UNIX operating system.
• the semaphore creates the scenario where the thread
which have been occupying the object would signal the
other after its work is Finished.
• it creates a block queue where the upcoming thread is to
be in waiting state.
• the methods used here are wait( ) and signal( ).
• here the operating system have the mutual exclusion.
➔ Monitor:
• here the object itself takes the responsibility for the
mutual exclusion.
• it can be achieved using object orientation.
• the complete mechanism is inside the object itself.
• the read and write method, the data and the block queue
belongs to the shared object itself as it can be accessed
by any of the threads at a particular time.
• Here java makes sure than one thread is accessed at a
time.
• example program:
class MyData
{
void display (String str)
{
synchronize(this)
{
for(int
i=0;i<str.length();i++)
{
s.o.p(str.charAt(i));
}
}
}
}
class MyThread1 extends Thread
{
Mydata d;
MyThread1(MyData dat){d=dat;}
public void run()
{
d.display(“Hello World”);
}
}
class MyThread2 extends Thread
{
Mydata data;
MyThread2(MyData dat)
{data=dat;}
public void run()
{
d.display(“Welcome”);
}
}
class Test
{
p.s.v.main(…)
{
MyData d=new Mydata( );
Mythread1 t1=new
MyThread1(d);
MyThread2 t2=new
MyThread(d);
t1.start( );
t2.start( );
• the classes Mythread1 and Mythread2 access the data
from the display class which is the shared object.
• the synchronize method is used to execute the classes
separately in the above example.
• synchronize method prints the data separately from both
thread in other words it prevents the data to be
overlapped.
• the for loop inside the synchronize prints one method at
a time.
• The other method for synchronization is to write the
synchronize at the signature method of the display class
so the whole method is being synchronized.

➔ Inter-thread communication:
• it is the communication between the synchronized
threads.
• it is the communication between a single producer
thread and a consumer thread.
• the inter-thread communication refers to the
synchronization between the producer thread and the
consumer thread to access the write and read method
simultaneously.
• to achieve the communication the Flag=t and Flag=f, are
used.

➔ Race condition:
• here there is a single producer thread and multiple
consumer threads.
• here all consumers do not execute at once they do in a
round robin fashion.
• when the count is zero then it is the producers turn.
• and when the count is not zero then it is the consumers
turn.
• since there are more than one consumer any of the
consumer can access it.
• the notify method can open any thread her as they may
not be in an order.
• The race condition states that
• If one thread is accessing the shared resource and
all other are blocked then once the thread has Finished.
• working it will inform the thread and any of the threads
may access the object just like in a race.
• So, in the above the count method is used to control the
race.
• the race condition can be avoided by the inter-thread
condition.
• example program:
class MyData
{
int value=0;
boolean flag=true;
synchronised void set(int v)
{
while(flag!=true)
wait( );
value=v;
flag=false;
notify( );
}
synchronized int get( )
{
int x=0;
while(flag!=false)
wait( )
X=value;
flag=true;
notify;
return x;
}
}

class Producer extends Thread


{
MyData d;
Producer(Mydata dat){d=dat;}

public void run( )


{
Int i=1;
while(ture)
{
d.set(i);
s.o.p(“producer: “+i);
i++;
}
}
}

class consumer extends thread


{
MyData d;
In the above example:
• the inter-thread communication part is achieve by the
programmer itself.
• the producer will be writing in the shared object and the
consumer will be reading from the shared object.
• the shared object, have three things one is the data or the
value given, second is the set method to write the data
and the third is the get method to read the data.
• as the set and get methods are synchronised only one
thread is allowed to enter.
• If the Flag is true then it is producers turn and if the Flag is
false then it is the consumers turn
• wait( ) and notify( ) is to bring in the communication
between the threads.
INTERFACES
➢ What are Interfaces?
• Inheritance is used for borrowing methods.
• Abstract is used for achieving polymorphism as well as Inheritance.
• Inheritance is completely used for achieving Polymorphism.
• Interface can be call as Abstract Class with all abstract methods.
• All the methods are by default abstract.
• Classes are extended but Interfaces are implemented.
• In Interface we can have reference of interface and the object of the
class which is implemented.
• In java a class can extend from one class only but if a class is
implementing an interface then it can implement from multiple
interfaces.
Example Program
interface test1
{
void meth1();
void meth2();
}
class test2 implements test1
{
public void meth1()
public void meth2()
}
class test
{
public static void main(0
{
test1 t=new test2
}
}

➢ Do’s and Don’ts of Interfaces


• By default, methods are Public and Abstract.
• As methods are to be implemented by the classes, they can’t be made
private.
• IdentiAiers can be used in interfaces but the identiAiers must be given
in Upper cases.
• IdentiAiers are by default Ainal and static.
• Method inside an interface cannot have body but the method can
have body if the method is static.
• Static members can be accessed in main method by using interface
name and dot operator.
• An interface can be extended from another interface.

➢ Interface VS Mul7ple Inheritance


• In C++ one class can inherit from multiple classes.
• Multiple Inheritance in java is achieved using Interfaces.
• Interfaces are perfect than using Multiple Inheritance.
• Way of thinking in java is more perfect than C++.

You might also like