JAVA UNIT - 1 Lecture Notes
JAVA UNIT - 1 Lecture Notes
Class:
➢ A class is a user defined blueprint or prototype (template) from which objects are created.
➢ It represents the set of properties or methods that are common to all objects of one type.
➢ It has definitions of methods and data.
Data Hiding & Encapsulation
Using private access modifiers(access specifiers), we can hide data from other classes.
Binding data and its operations together into a single unit is known as encapsulation.
A java class is the example of encapsulation.
Abstraction
Hiding internal details (implementation details) and showing functionality is known as
abstraction.
For example phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
Existing class: Super Class / Base Class / Parent Class
New class: Sub Class / Derived Class / Child Class
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Expressions
Any unit of code that can be evaluated to a value is an expression.
Example-1: 10+15
Example-2: (x*y)/z;
Type Casting:
Convert a value from one data type to another data type is known as type casting.
Widening Type Casting: Converting a lower data type into a higher one.
It is also known as implicit conversion or casting down. It is done automatically.
It is safe because there is no chance to lose data.
It takes place when the target type must be larger than the source type.
Example:
int x = 7;
//automatically converts the integer type into long type
long y = x;
Narrowing Type Casting: Converting a higher data type into a lower one.
It is also known as explicit conversion or casting up.
It is done manually by the programmer.
If we do not perform casting then the compiler reports a compile-time error.
Example:
double d = 166.66;
int i = (int) d; //converting double data type into int data type
Operators:
1) Unary Operators: expr++, expr--, ++expr, –expr
Example:
int counter = 0;
System.out.println(counter); // Outputs 0
System.out.println(++counter); // Outputs 1
2) Arithmetic: *, /, %, +, -
Example:
int a=10;
int b=5;
System.out.println(a+b);//15
3) Relational: <, >, <=, >=
Example:
int x = 10, y = 20, z = 10;
System.out.println(x < y); // Outputs true
4) Equality: ==, !=
Example:
int x = 10, y = 20;
if(x==y)
System.out.println(“Both Same”);
else
System .out.println(“Both Not Same”);
5) Bitwise Operators:
Bitwise OR (|):
This operator is a binary operator, denoted by ‘|’.
It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example, a = 5 = 0101 (In Binary), b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
________
0111 = 7 (In decimal)
Bitwise AND (&):
This operator is a binary operator, denoted by ‘&’.
It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0.
For example, a = 5 = 0101 (In Binary), b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
Bitwise XOR (^):
This operator is a binary operator, denoted by ‘^’.
It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it
gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
Bitwise Complement (~) –
This operator is a unary operator, denoted by ‘~’.
It returns the one’s complement representation of the input value, i.e, with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
Bitwise Compliment Operation of 5
~ 0101
________
1010 = 10 (In decimal)
Right shift operator (>>):
Shifts the bits of the number to the right and fills the voids left with the sign bit (1 in case of
negative number and 0 in case of positive number).
The leftmost bit and a depends on the sign of initial number.
Similar effect as of dividing the number with some power of two.
Example 1:
a = 10
a>>1 = 5
Example 2:
a = -10
a>>1 = -5
Left shift operator (<<):
Shifts the bits of the number to the left and fills 0 on voids left as a result.
Similar effect as of multiplying the number with some power of two.
Examples:
a = 5 = 0000 0101
b = -10 = 1111 0110
Wrapper Classes:
Byte, Short, Integer, Long, Float, Double, Character & Boolean are the wrapper classes in java.
One of the main use of these classes is data type conversion.
Control Structures
while Loop:
to execute a statement or code block repeatedly as long as an expression is true
Syntax:
while (expression)
{
Statement(s) to be executed if expression is true
}
do...while Loop
Syntax:
do
{
Statement(s) to be executed;
}
while (expression);
for Loop:
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Arrays
Array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
One Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Example:
int a[]=new int[5];
int a[]={};
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
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Array of Objects
class Student
{
private int sno;
private String sname;
public void init(int x, String y)
{
sno=x;
sname=y;
}
public void display()
{
System.out.println(sno);
System.out.println(sname);
}
}
class Test
{
public static void main(String args[])
{
Student s[]=new Student[5];
s[0]=new student();
s[0].init(1,"xxx");
s[0].display();
s[1]=new student();
s[1].init(2,"yyy");
s[1].display();
s[2]=new student();
s[2].init(3,"zzz");
s[2].display();
}
}
Garbage Collector
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
finalize()
This method is called just before an object is garbage collected(similar to a destructor in C++).
finalize() belongs to Object class.
finalize() method overrides to dispose system resources, perform clean-up activities and
minimize memory leaks.
Example:
class Test
{
public static void main(String[] args)
{
Test t1 = new Test();
obj = null;
System.gc(); // calling garbage collector manually
System.out.println("end of garbage collection");
}
protected void finalize()
{
System.out.println("finalize method called");
}
}
Note: we cant rely on finalize() because this may not be called when the object falls out of
scope.
Strings
String basically represents sequence of char values.
In Java, string is an object that represents a sequence of characters. The java.lang.String class is
used to create a string object.
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created.
Example:
1. String s1=”Shiva”; // string literal created on the string pool
2. String s2=new String(“Ravi”) // an exclusive string object created on the pool
Java String class methods
1. charAt(int index):
Returns char value for the given index.
Example:
String string = "animals";
System.out.println(string.charAt(0)); // a
2. length():
returns string length
Example:
String string = "animals";
System.out.println(string.length()); // 7
3. equals() & equalsIgnoreCase():
To check whether two strings contain same data or not.
Example:
System.out.println("abc".equals("ABC")); // false
4. substring():
looks for characters in a string. It returns parts of the string.
Example:
String string = "animals";
System.out.println(string.substring(3)); // mals
5. indexOf( ):
looks at the characters in the string and finds the first index that matches the desired value.
indexOf can work with an individual character or a whole String input.
It can also start from a requested position.
Example:
System.out.println(string.indexOf("al")); // 4
System.out.println(string.indexOf("al", 5)); // -1
6. contains():
returns true or false after matching the sequence of char value.
Example:
System.out.println("abc".contains("b")); // true
7. startsWith() and endsWith():
Example:
System.out.println("abc".startsWith("a")); // true
System.out.println("abc".startsWith("A")); // false
System.out.println("abc".endsWith("c")); // true
System.out.println("abc".endsWith("a")); // false
8. replace():
The replace() method does a simple search and replace on the string
Example:
System.out.println("abcabc".replace('a', 'A')); // AbcAbc
System.out.println("abcabc".replace("a", "A")); // AbcAbc
9. toLowerCase(): returns a string in lowercase.
Example: System.out.println("Abc123".toLowerCase()); // abc123
10. toUpperCase(): returns a string in uppercase.
Example: String string = "animals";
System.out.println(string.toUpperCase()); // ANIMALS
11. trim(): removes whitespace from the beginning and end of a String.
Example:
System.out.println("abc".trim()); // abc
System.out.println("\t a b c\n".trim()); // a b c
Inheritance
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
➢ It is an important part of OOPs (Object Oriented programming system).
➢ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
➢ When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
➢ Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Types of Inheritance:
1. Single: When a class inherits another class, it is known as a single inheritance.
2. Multi Level: When there is a chain of inheritance, it is known as multilevel inheritance.
3. Multiple: When one class inherits multiple classes, it is known as multiple inheritance.
Multiple and hybrid inheritance is supported through interface only.
4. Hierarchical: One base class is used to create many sub classes.
5. Hybrid: uses more than on type of inheritance.
Multiple Inheritance
When one class inherits multiple classes, it is known as multiple inheritance.
In java Multiple and Hybrid inheritance is supported through interfaces only.
Java does not support Multiple Inheritance with classes because of Diamond Problem in Hybrid
Inheritance.
Diamond Problem:
class A
{
int a = 10;
};
class B extends A
{
B()
{
a = 20;
}
};
class C extends A
{
C()
{
a = 30;
}
};
Let “ D “ be the class extends B and C classes.
Then the instance variable ‘a’ of class A is inherited twice to class D through two different paths.
So now when we try to access the variable ‘a’ in class D, we get the ambiguity because it could
not figure out which of the two copies of ‘a’ to be used is not known.
final keyword
final with a variable:
The value of the variable is fixed.
Example:
final int x=10; // x value is 10 fixed, cant change
final methods:
Class Test
{
final float sum(int x, int y)
{
System.out.println(x+y);
}
}
The method sum() cant be overridden in sub classes if any for the class ‘Test’.
final class:
final class Test
{
// attributes
// methods
}
As the class ‘Test’ is final, we can’t create derived classes for this class.
Forms of Inheritance:
The substitutability means that when a child class acquires properties from its parent class, the
object of the parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect an instance of A we can use an
instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
Specialization
Most commonly used inheritance and sub classification is for specialization.
Child class is a specialized form of parent class.
Always creates a subtype, and the principles of substitutability is explicitly upheld.
Example:
Java AWT Components
TextComponent (Parent class)
TextArea (Derived class)
TextField (Derived class)
Specification
Two different mechanisms are provided by Java, interface and abstract, to make use of
subclassification for specification.
The parent class specifies some behavior, but does not implement the behavior. Child class
implements the behavior.
Subtype is formed and substitutability is explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is used for definitions of the
properties provided by its parent.
Example: Java 1.1 Event Listeners: ActionListener, MouseListener
Construction
Child class inherits most of its functionality from parent, but may change the name or parameters
of methods inherited from parent class to form its interface.
This type of inheritance is also widely used for code reuse purposes. It simplifies the
construction of newly formed abstraction.
Not a form of subtype, and often violates substitutability.
Example: Stack class defined in Java libraries
Extension(Generalization)
The child class generalizes or extends the parent class by providing more functionality
The child doesn't change anything inherited from the parent, it simply adds new features
Example, ColoredWindow inheriting from Window
Limitation
The child class limits some of the behavior of the parent class.
Example, you have an existing List data type, and you want a Stack
Inherit from List, but override the methods that allow access to elements other than top so as to
produce errors. Is not a subtype, and substitutability is not proper.
Combination
This types of inheritance is known as multiple inheritance in Object Oriented Programming.
Although the Java does not permit a subclass to be formed be inheritance from more than one
parent class, several approximations to the concept are possible.
Example:
class Hole extends Ball implements PinBallTarget
{
// body of class
}
Benefits of Inheritance
➢ Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
➢ Inheritance can save time and effort as the main code need not be written again.
➢ Inheritance provides a clear model structure which is easy to understand.
➢ An inheritance leads to less development and maintenance costs.
➢ With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class.
➢ In inheritance base class can decide to keep some data private so that it cannot be altered
by the derived class.
Costs of Inheritance
➢ Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
➢ Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
➢ The changes made in the parent class will affect the behavior of child class too.
➢ The overuse of inheritance makes the program more complex.
Object Class:
The Object class is the parent class of all the classes in java by default.
Methods of Object Class:
hashCode(): Returns the hashcode number for this object.
equals(Object obj): Compares the given object to this object.
clone(): creates and returns the exact copy (clone) of this object.
toString(): eturns the string representation of this object.
notify(): wakes up single thread, waiting on this object's monitor.
wait(): causes the current thread to wait until another thread notifies (invokes notify() or
notifyAll() method).
finalize(): is invoked by the garbage collector before object is being garbage collected.