Java Unit2
Java Unit2
Strings: A string is a sequence of characters. Java provides class String to deal with character data.
The objects of String class are immutable
String Methods: String class has number of methods that allow us to perform various operations
on strings. Some of them are
class Stringex{
public static void main(String ar[]){
String s1 = "Andhra";
String s2 = "Loyola College";
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.equals(s2));
System.out.println(s1.compareTo(s2));
System.out.println(s1.length()+"\t"+s2.length());
System.out.println(s1.concat(s2));
System.out.println(s2.indexOf('C'));
System.out.println(s1.charAt(1));
}
}
Output:
andhra
ANDHRA
false
-11
6 14
AndhraLoyola College
7
n
String Comparison: By using compareTo ( ) and equals ( ) methods we can compare strings.
When JVM encounter statement String s1 = "Hello"; it creates object with a reference number.
and statement String s2 = new String ("Hello"); creates object with a different reference
number.
Consider the following Program
class StringComparision{
public static void main(String ar[]){
String s1 = "Hello";
String s2 = new String("Hello");
// Comparision using ==
System.out.println("**Comparision using == **");
if(s1==s2)
System.out.println("Both are Same");
else
System.out.println("Not same");
//comparision using equals() method
System.out.println("**Comparision using equals() method **");
if(s1.equals(s2))
System.out.println("Both are Same");
else
System.out.println("Not same");
}
}
Output:
**Comparision using == **
Not same
**Comparision using equals() method **
Both are Same
== operator compares the reference numbers hence it display both strings as Not Same.
Where as equals( ) method compares contents so it return the strings with same content as “Both are
same”
Immutability of Strings: Strings are immutable, which means once they are created, they cannot
be modified.
class Immutable{
public static void main(String ar[]){
String s1 = "Core";
String s2 = "Java";
s1 = s1+s2;
System.out.println(s1);
}
}
Output: CoreJava
It seems s1 is modified but the fact is JVM creating new object and assigns it to s1
Introduction to OOPs:
Procedure Oriented Approach
High Level languages like C, COBOL, FORTRAN follows Procedure Oriented Programming Approach. In
Procedure Oriented Programming Approach Problem is decomposed into small tasks, we use functions to
accomplish these tasks.
Problems in Procedure Oriented Approach
1. Emphasis is on writing functions
2. Large programs are divided into sub programs / functions
3. Most functions share global data.
4. Data move openly around the system from function to function
5. Functions transform data from one form to another.
6. Employs Top-Down Approach
7. Expansion To add new data and function in POP is not so easy
Examples of POP are : C, VB, FORTRAN, Pascal.
Characteristics:
1. Emphasis on data rather than procedures
2. Programs are divided into objects.
3. It follows Bottom Up approach.
4. Data is hidden and not accessible by outside world.
5. Data and methods are encapsulated into single unit.
6. Objects communicate with each other through methods.
7. Provides an easy way to add new data and methods.
8. Data cannot move easily from function to function, it can be kept public or private so we can control the
access of data.
9. Data hiding concept provides more security.
Class: A class is blueprint to create objects. A class is a collection of objects of similar types. Class is a user
defined data type which is used to group all the related data and functions. Once we create a class we can create
any number of objects to that particular class.
Syntax for class creation:
class class_name
{ // some data/some fields
// some functions/methods
}
Encapsulation: Wrapping up of data and methods into a single unit is called Encapsulation. With this data is
not accessible to the outside world, thus provides data hiding. Encapsulation is achieved by writing classes. In a
class data represented as fields and methods are used to perform tasks. The insulation of data from direct access
by the program is called Data Hiding.
Data Abstraction: Data abstraction refers to the act of representing essential features without including the
background details or explanations .Abstraction is process of hiding the implementation details and showing
only the functionality. Abstraction in java is achieved by using interfaces and abstract class.
Inheritance: Deriving a new class from an existing class is called inheritance. The old class is Super Class and
the new class is Sub class. It is the reusability concept where a sub class can acquire the properties of super
class. Inheritance defines is-a relationship between a superclass and its subclasses.
For example, the bird” Eagle” is a part of the class of “Flying Bird”, which is again a “Bird”. So class “Bird” can
be taken as super class the sub classes are “FlyingBird”, “NonFlyingBird” .as illustrated in the fig, the principle
behind this sort of division is that each derived class shares common characteristics with the class from which it
is derived.
Polymorphism: Polymorphism is the ability to take more than one form. For example an operation may exhibit
different behaviour in different instances. The behaviour depends upon the types of data used in the operation for
example consider the operation of addition. For two numbers the operation will generate a sum. If the Operands
are strings then the operation would produce a third string by concatenation. The following fig illustrates single
function name can be used to handle different actions
Dynamic binding: Binding refers to the linking of a procedure call to the code to be executed in response to
the call. Dynamic binding means that the code related with a given procedure call is not known until the time of
the call at run time. Dynamic binding is associated polymorphism and inheritance.
Message Passing: The process by which one object interact with other object is called message passing.
Class :A class is a user-defined data type with template that serves to define its properties. A class is a
collection of fields (data) and methods (procedure or function) that operate on that data.
Defining a Class
The basic syntax for a class definition:
Adding Methods :
• A class with only data fields has no life.
• Objects created by such a class cannot respond to any messages.
• Methods are declared inside the body of the class but immediately after the declaration of
data fields.
The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
Adding Method to Class Circle
class Circle
{
double r; // radius of circle
double area()
{
return 3.14d * r * r;
}
}
Object: An object is instance of a class. It is a basic runtime entity.by using objects we can represent
any real time entity.
Every object will have Properties (State) and Actions (Behavior).
Properties – data to describe object
Actions – tasks/operations performed by the object
To create object we use a reference variable, new operator.
Defining objects:
Circle aCircle;
Circle bCircle;
Note: aCircle, bCircle simply refers to a Circle object, not an object itself.
bCircle = aCircle;
Constructors:
1. Constructors is a special type of method in java which enables an object to initialize itself when
it is created.
2. Constructors name is same as class name.
3. They do not specify return type, not even void. because it return the instance of class itself.
4. Constructor is automatically invoked when object is created.
}
ACCESS SPECIFIERS (or access modifiers): are keywords in object-oriented languages that sets
the accessibility of the classes , methods and others members
THERE ARE 4 TYPES OF JAVA ACCESS SPECIFIERS:
i. DEFAULT (friendly)
ii. PRIVATE
iii. PROTECTED
iv. PUBLIC
DEFAULT ACCESS SPECIFIER:
No keyword is required to specify default access specifier
When no access modifier is specified for a class, method or data member it is said to be
having
the default access specifier by default.
Default access specifier are accessible within the same package.
PRIVATE ACCESS SPECIFIER:
The private access specifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in
which
they are declared.
Any other class of same package will not be able to access these members.
Classes or interface can not be declared as private.
Return type can be void or int etc. .The method name is valid identifier. The parameters are written in
parentheses separated by commas.
Method Body: It is the method definition which has group of statements that has actual logic to
perform a task.
Understanding Methods: We can create a method to perform a task , consider the following example
which add two integers.
class Sum{
void sum(int x, int y){ //Method Header
System.out.println("Sum"+(x+y)); //Method Body
}
public static void main(String ar[]){
int a = 20, b = 30;
Sum s = new Sum();
s.sum(a,b); //Calling a method
}
}
Output:
Sum 50
In this example Consider the method header here method name is sum return type is void and this method takes
two integers as arguments , in the method body it is calculating sum of two integers which are supplied as
parameters .
The statement s.sum(a,b) will perform calling the method for execution.
Static Methods: Static members are those which belongs to the class and you can access these
members without instantiating the class. Static members are called using class name. Static methods
can access only static data. The static fields have the same value in all the instances of the class. These
are created and initialized when the class is loaded for the first time.
// Static method Program
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
public static void main(String args[])
{
int result= Calculate.cube(5);
System.out.println(result);
}
}
Output: 125
Static blocks in Java : Java supports a special block, called static block (also called static clause)
which can be used for static initializations of a class. This code inside static block is executed only once
the first time the class is loaded into memory. static blocks are executed before constructors.
A class can have any number of static initialization blocks, and they can appear anywhere in
the class body. The runtime system guarantees that static initialization blocks are called in the order that
they appear in the source code
class Test1 {
static int i;
static {
i = 10;
}
public static void main(String args[]) {
System.out.println(Test1.i);
}
}
Output: 10
The keyword ‘this’:
The this keyword refers to the current object in a method or constructor. The most common use
of the this keyword is to eliminate the confusion between class attributes and parameters with the same
name (because a class attribute is shadowed by a method or constructor parameter). If you omit the
keyword in the example above, the output would be "0" instead of "5". this can also be used to: Invoke
current class constructor Invoke current class method Return the current class object Pass an argument
in the method call Pass an argument in the constructor call
class Test
{
int a; int b;
Test(int a, int b)
{
this.a = a; this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10, 20);
object.display();
}
Output: a = 10 b = 20
Instance Methods: instance methods are declared in a class which act upon instance variables.
To call instance methods we have to create object. We call instance methods by using
objectname.method name( )
import java.util.*;
class Rect1{
int l,b; //Instance Variables
Rect1(int x, int y){ l=x; b=y; }
void display(){ //Instance Method
System.out.println("Area of Rectangle"+l*b);
}
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
Rect1 r2 = new Rect1(20,30);
r2.display();
}
}
Output: Area of Rectangle600
Passing Primitive Data Types to Methods: To a method argument we can pass primitive
types like int, float as parameters. When we pass a primitive type to a method, it is call by value.
The following program explain how to pass Primitive types as parameters to a method.
class PassingParameters{
// Passing Primitive types as arguments
void add(int a, int b){
System.out.println("Sum"+(a+b));
}
}
class Passing{
public static void main(String ar[]){
PassingParameters p = new PassingParameters();
p.add(10,20);
}
}
Output: Sum30
Passing Arrays to Methods: To a method argument we can pass array as parameters. When
we pass a primitive type to a method, it is call by value. The following program explain how to pass
Array as parameter to a method.
class PassingArray{
class ObjectPassDemo
{
int a, b;
ObjectPassDemo(int i, int j)
{ a = i; b = j; }
boolean equalTo(ObjectPassDemo o)
{
return (o.a == a && o.b == b);
}
}
public class Test
{
public static void main(String args[])
{
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}
Output:
ob1 == ob2: true
ob1 == ob3: false
As we call the method equalTo, the reference ‘o’ will be assigned to the object which is passed as an
argument, i.e. ‘o’ will refer to ‘ob2’ as following statement execute.
System.out.println("ob1 = ob2” +ob1.equalTo(ob2));
Recursion: A function calling itself repeatedly till it satisfy a specified condition.
import java.util.*;
public class Factorial {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to find its factorial");
n = sc.nextInt();
System.out.println("Factorial of 5 is: "+factorial(n));
}
}
Output: Enter a number to find its factorial
5
Factorial of 5 is: 120
Factory Methods: A Factory method is a static method which is used to create and return an
object of a class it belong to. A single Factory method can replace several constructors in the
class by accepting different options from the user while creating the object.
Ex:
Inheritance: Inheritance is the concept of deriving a new class from the existing class. The new
class is sub class whereas the existing class is the super class. Inheritance is a reusability concept
in which one class acquires the properties (methods and fields) of another. The Derived class(Sub
class/Child class) extracts the methods and variables of the Base class(Super class/Parent class).
Syntax for declaring derived class:
Inheritance represents IS-A relationship which is also called as Parent-Child relationship. A Parent class
can have any number of Child class whereas a Child class can have only one Parent class. Child class
inherits the Parent class using extends keyword.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Types of Inheritance in Java : The following are different types of Inheritance in Java, some are
directly supported and some are indirectly supported through Java Interfaces.
Single Inheritance : A sub class with only one super class is called single inheritance .
The below diagram represents the single inheritance in java where ClassB extends only one
class ClassA. Here Class B will be the Sub class and Class A will be one and only one Super class.
class A
{ //fields
//methods }
class B extends A
{ //fields
//methods
}
Ex:
class Parent {
void display(){ System.out.println("Parent class");}
}
class Child extends Parent{
void display(){System.out.println("Child Class"); }
}
class Display{
public static void main(String[] args) {
Child c = new Child();
c.display(); } }
Output: Child Class
Multilevel Inheritance: In Multilevel inheritances there exists single base class, single derived
class and multiple intermediate base classes.
As seen in the below diagram. ClassB inherits the property of ClassA and again ClassB act as
a parent for Class C
class A
{
//fields
//methods
}
class B extends A
{
//fields
//methods
}
class C extends B
{
//fields
//methods
}
Ex:
class GrandParent{
void displayg(){ System.out.println("Grand Parent");}
}
class Parent extends GrandParent {
void displayp(){ System.out.println("Parent class");}
}
class Child extends Parent{
void displayc(){System.out.println("Child Class"); }
}
class Display{
public static void main(String[] args) {
Child c = new Child();
c.displayg();
c.displayp();
c.displayc();
}
}
Output:
Grand Parent
Parent class
Child Class
Hierarchical Inheritance: When more than one classes are derived from a single base class,
such inheritance is known as Hierarchical Inheritance.
As seen in the below example base ClassA will be inherited by ClassB, ClassC and ClassD.
class A
{
//fields
//methods
}
class B extends A
{
//fields
//methods
}
class C extends A
{
//fields
//methods
}
class D extends A
{
//fields
//methods
}
Ex:
class College {
void display(){System.out.println("College i the best place to emerge");}
}
class Ug extends College{
void show(){System.out.println("Graduate");}
}
class Pg extends College{
void view(){System.out.println("Post Graduate");}
}
class Diplay{
public static void main(String[] args) {
Ug ug = new Ug();
ug.show();
Pg pg = new Pg();
pg.view();
}
}
Output:
Graduate
Post Graduate
Multiple Inheritance: Multiple Inheritance is nothing but one class extending more than one
base class. Multiple Inheritance is basically not supported by many languages such as Java,
Small Talk, C# etc.. (C++ Supports Multiple Inheritance).
As the Child class has to manage the dependency of more than one Parent class. But
we can achieve multiple inheritance in Java using Interfaces.