0% found this document useful (0 votes)
7 views35 pages

Unit II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views35 pages

Unit II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Unit-II Core Java

Class & Object:

Class is a user-define data type to define its properties.


A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created. It
is a logical entity. It can't be physical.
A class is collection of objects also .
Syntax of class:

class class_name

// fields

// method

// body of class

Example :

//Refer class example in a book already noted in class room

Object :
An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc.

An object is an instance of a class. A class is a template or blueprint from


which objects are created. So, an object is the instance(result) of a class.
Unit-II Core Java

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

Syntax of object:

Class_name object_name =new class_name();

Example:

Refer class example in a book already noted in class room


Unit-II Core Java

Method:
In general, a method is a way to perform some task. Similarly,
the method in Java is a collection of instructions that performs
a specific task. It provides the reusability of code. We can also
easily modify code using methods.

A method is a block of code or collection of statements or a


set of code grouped together to perform a certain task or
operation. It is used to achieve the reusability of code. We write
a method once and use it many times. We do not require to
write code again and again. It also provides the easy
modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when
we call or invoke it.

The most important method in Java is the main() method.

The method declaration provides information about method


attributes, such as visibility, return-type, name, and arguments.
It has six components that are known as method header, as we
have shown in the following figure.
Unit-II Core Java

Method Signature: Every method has a method signature. It is


a part of the method declaration. It includes the method
name and parameter list.

Access Specifier: Access specifier or modifier is the access


type of the method. It specifies the visibility of the method.
Java provides four types of access specifier:

Public: The method is accessible by all classes when we use


public specifier in our application.

Private: When we use a private access specifier, the method is


accessible only in the classes in which it is defined.

Protected: When we use protected access specifier, the


method is accessible within the same package or subclasses
in a different package.

Default: When we do not use any access specifier in the


Unit-II Core Java

method declaration, Java uses default access specifier by


default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns.
It may have a primitive data type, object, collection, void, etc. If
the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the


name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a


comma and enclosed in the pair of parentheses. It contains the
data type and variable name. If the method has no parameter,
left the parentheses blank.

Method Body: It is a part of the method declaration. It contains


all the actions to be performed. It is enclosed within the pair of
curly braces.

Naming a Method

While defining a method, remember that the method name


must be a verb and start with a lowercase letter. If the method
name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name,
the first letter of each word must be in uppercase except the
first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()


Unit-II Core Java

It is also possible that a method has the same name as


another method name in the same class, it is known as method
overloading.

Types of Method

There are two types of methods in Java:

Predefined Method

User-defined Method

Predefined Method
In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods. It is also known as the standard library
method or built-in method. We can directly use these methods
just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding
method runs in the background that is already stored in the
library.

Each and every predefined method is defined inside a class.


Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we
write inside the method. For example, print("Java"), it prints
Java on the console.

Advantage of Method
o Code Reusability
o Code Optimization
Unit-II Core Java

Example of the predefined method.

Demo.java

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));

}
}
Output:
The maximum number is: 9

In the above example, we have used three predefined


methods main(), print(), and max(). We have used these
methods directly without declaration because they are
predefined. The print() method is a method
of PrintStream class that prints the result on the console. The
max() method is a method of the Math class that returns the
greater of two numbers.

User-defined Method
The method written by the user or programmer is known as a
user-defined method. These methods are modified according
Unit-II Core Java

to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is


even or odd. First, we will define the method.

//user defined method


public static void display()
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

We have defined the above method named findevenodd(). It


has a parameter num of type int. The method does not return
any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the
number is even, it prints the number is even, else prints the
number is odd.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be called. The calling


of a method in a program is simple. When we call or invoke a
user-defined method, the program control transfer to the called
method.

import java.util.Scanner;
Unit-II Core Java

public class Dog


{
public static void main (String args[])
{
System.out.print("Enter the number: ");
}

In the above code snippet, as soon as the compiler reaches at


line findEvenOdd(num), the control transfer to the method and
gives the output accordingly.

Example :

Method overloading : (Refer the class notes ).


Constructor :

In Java, a constructor is a block of codes similar to the method. It is called


when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one
constructor is called.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


Unit-II Core Java

2. A Constructor must have no explicit return type


3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any


parameter.

Syntax of default constructor:

<class_name>(){}
Example of default constructor :

//Java Program to create and call a default constructor


class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
Unit-II Core Java

public static void main(String args[])


{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output :
Bike is created

What is the purpose of a default constructor?

The default constructor is used to provide the default values to


the object like 0, null, etc., depending on the type.

Java Parameterized Constructor


A constructor which has a specific number of parameters is
called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values


to distinct objects. However, you can provide the same values
also.

Example of parameterized constructor

In this example, we have created the constructor of Student class


that have two parameters. We can have any number of
parameters in the constructor.
Unit-II Core Java

Constructor overloading :( Refer the class notes ).

In Java, a constructor is just like a method but without return type.


It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more


than one constructor with different parameter lists. They are
arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of
parameters in the list and their types.

Example:

Difference between constructor and method in Java


There are many differences between constructors and methods. They
are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the
you don't have any constructor in a class. compiler in any case.
Unit-II Core Java

The constructor name must be same as the class The method name may or may not
name. be same as the class name.

Java control statements (Decision making & looping):


Java compiler executes the code from top to bottom. The
statements in the code are executed according to the order in
which they appear. However, Java provides statements that can
be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements

o switch statement

2. Loop statements
o do while loop

o while loop

o for loop

3. Jump statements
o break statement

o continue statement

Decision making:

Decision-making statements decide which statement to execute


and when. Decision-making statements evaluate the Boolean
Unit-II Core Java

expression and control the program flow depending upon the


result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch
statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The


control of the program is diverted depending upon the specific
condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements
given below.

OR
The "if statement" will ensure the given condition, and if the
condition becomes true, then the block of statements enclosed
within curly braces will get executed; otherwise, not.
OR
if statement to specify a block of java code to be executed if a
condition is True.
Syntax
if (condition)
{
// block of code to be executed if the condition is True
}
Example :
Unit-II Core Java

if (20 > 18)


{
System.out.println ("20 is greater than 18");
}

We can also test variables:

int x = 20;
int y = 18;
if (x > y)
{
System.out.println ("x is greater than y");
}
Output: x is greater than y

Example explained

In the example above we use two variables, x and y, to test


whether x is greater than y (using the > operator). As x is 20, and y
is 18, and we know that 20 is greater than 18, we print to the
screen that "x is greater than y".
Unit-II Core Java

if….else statement
The “if statement” will ensure the given condition and if the
condition becomes true, then the block of statement enclosed
within curly braces will get executed; otherwise , the block of code
associated with the else will get executed .
Syntax :
if (condition)
{
True condition ;
}
Else
{
False condition;
}
Example:
Int x=20;
Int y=15;
if(x<y)
{
System.out.println (“x is greater than y”);
Unit-II Core Java

}
Else
{
System.out.println(“condition is false ”);
}
Output : condition is false

Switch Statement:
In Java, Switch statements are similar to if-else-if statements.
The switch statement contains multiple blocks of code called
cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead
of if-else-if statements. It also enhances the readability of the
program.

Some important point about switch statement :

o The case variables can be int, short, byte, char, or


enumeration. String type is also supported since version 7 of
Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't
match the value of expression. It is optional.
o Break statement terminates the switch block when the
condition is satisfied.
Unit-II Core Java

It is optional, if not used, next case is executed.


o While using switch statements, we must notice that the case
expression will be of the same type as the variable. However,
it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Consider the following example to understand the flow of the


switch statement.

class switchstat
{
Public static void main (String args[])
Unit-II Core Java

{
int day=2;
Switch(day)
{
Case 1:
System.out.println (“monday”);
Break;
Case 2:
System.out.println (“Tuesday”);
Break;
Case 3:
System.out.println (“Wednesday”);
Break;
Case 4:
System.out.println (“Thursday”);
Break;
Case 5:
System.out.println(“monday”);
Break;
}
Unit-II Core Java

}
}
Output : Tuesday

While using switch statements, we must notice that the case


expression will be of the same type as the variable. However, it
will also be a constant value. The switch permits only int, string,
and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code
repeatedly while some condition evaluates to true. However, loop
statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly. However,


there are differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize
the loop variable, check the condition, and increment/decrement
in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.

In for loop, if the given condition is true body of the program will
executed until the condition becomes false and terminate the
Unit-II Core Java

loop and program.

Syntax:

for(initialization, condition, increment/decrement)


{
//block of statements
}
Example of for loop:
public class Calculation
{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);

}
}

Output:

The sum of first 10 natural numbers is 55.

While loop:
Unit-II Core Java

While is an entry-controlled loop statements. The test condition is


evaluated and if the condition is true , then the body of the loop is
executed. After the execution of body, the test condition is once
again evaluated and if it is true, the body is executed once again.
While loop is used to iterate a part of the program several times.
If the number of iteration is not fixed. It is recommended to use
while loop than for loop.
If you don’t know how many times loop are repeated so use while
loop.
Syntax:
While(condition)
{
// code to be executed
(increment);
}
Example of while loop:
int i=0;
while(i<5)
{
System.out.println(i);
i++;
}
Unit-II Core Java

The code in the loop will run, over & over again as long as a
variable (i) is less than 5.
Note: Do not forget to increase the variable used in the condition,
otherwise the loop will never end.

Do while loop:
The do while loop is a variant of the while loop. The loop will
execute the code block once. Before checking if the condition is
true, then, it will repeat the loop as long as the condition is true.
Do while loop is executed at least once because condition is
checked after loop body.
Do while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use do-while
loop.
Syntax:
do
{
// block of code to be executed at least once.
// Increment of variable;
Unit-II Core Java

} while(condition);

Example of do-while loop:


Int i=0;
do
{
System.out.println (i);
i++;
}while(i<5);
The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the
condition is tested.

Array:
Normally, an array is a collection of similar type of elements
which has contiguous memory location.

Java 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
Unit-II Core Java

on.

Advantages

o Code Optimization: It makes the code optimized, we can


retrieve or sort the data efficiently.
o Random access: We can get any data located at an index
position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in


the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in Java which grows
automatically.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr;
OR
dataType []arr;
Unit-II Core Java

OR
dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Example of Java Array


//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.

class Testarray
{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}

OURPUT :
Unit-II Core Java

10

20

30

40

50

You can initialize and declare array in this way also :


int a[]={33,3,4,5};//declaration and initialization

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[][];
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

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


Unit-II Core Java

Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and
print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array


class Multidi
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
Unit-II Core Java

System.out.println();
}
}
}
Test it Now

Output:

123
245
445

STRING : (Refer class notes )

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.

The syntax of Java Inheritance


Unit-II Core Java

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to
increase the functionality.

Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance ()
4. Hierarchical inheritance
5. Hybrid inheritance

Single Inheritance :
When a class inherits another class, it is known as a single inheritance.
In the example given below, Dog class inherits the Animal class, so
there is the single inheritance.

(Refer the class example)

Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog
class inherits the Dog class which again inherits the Animal class, so
Unit-II Core Java

there is a multilevel inheritance.

(Refer the class example)


Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java.

Consider a scenario where A, B, and C are three classes. The C class


inherits A and B classes. If A and B classes have the same method and you
call it from child class object, there will be ambiguity to call the method of
A or B class.

Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.

class A
{
void msg()
{
System.out.println("Hello");
}
}
class B
{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B
{ //suppose if it were

public static void main(String args[])


{
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
Unit-II Core Java

}
}
Output:

Compile Time Error

So, to overcome this problem invents new technology that is


Interface.

Interface :

An interface in Java is a blueprint of a class. It has static


constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction.


There can be only abstract methods in the Java interface, not
method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given
below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple
inheritance.
Unit-II Core Java

o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It


provides total abstraction; means all the methods in an
interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements
an interface must implement all the methods declared in the
interface.

Syntax:

interface <interface_name>

// declare constant fields

// declare methods that abstract by default

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class,
an interface extends another interface, but a class implements an
interface.
Unit-II Core Java

Example of Interface :

interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
Unit-II Core Java

public void draw()


{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by met
hod e.g. getDrawable()
d.draw();
}
}
Output :drawing circle
drawing circle

You might also like