0% found this document useful (0 votes)
20 views

unit-II (Java) Padma

Irfjd

Uploaded by

Anurag Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

unit-II (Java) Padma

Irfjd

Uploaded by

Anurag Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Bhavan’s Vivekananda College,

Sainikpuri, Secunderabad.
BSC V SEM
Programming in Java(CS525)

UNIT- II

K. Padma Priya
Lecturer,
Department of Computer Science,
Bhavan’s Vivekananda College,
Sainikpuri, Secunderabad.
Programming in Java
UNIT-II
Programming in Java

Unit II Syllabus:
Class Methods: Constructors--- Method Overloading --- Static
Members --- Nesting of Methods --- Inheritance --- Overriding Methods
–- Final Variables and Methods --- Final Classes --- Abstract Methods
and Abstract Classes – Visibility Control.
Arrays and Strings: One-Dimensional Array --- Two-Dimensional
Array ---String Class.
Interfaces (Multiple Inheritance): Defining Interfaces --- Extending
Interfaces -- Implementing Interfaces.
Learning Outcomes:

Students will develop Java Programs relating to the Class, Arrays,


Strings and Interfaces.
Syntax of default
constructor:
<class_name>()
{}
// Second Example program for Default Constructor
import java.lang.*;

class Student
{
int rno;
String name;
Student() // Default Constructor
{
rno=1111;
name=“Ram”;
System.out.println(“rno=“+rno+”name=“+name);
}
} // class Student is closed

class Ma
{
public static void main(String arg[])
{
Student s1=new Student();
Student s2=new Student();
}
} // class Ma is closed
// Second Example program for Parameterized Constructor
import java.lang.*;

class Student
{
int rno;
String name;
Student(int r, String n) // Parameterized constructor
{
rno=r;
name=n;
System.out.println(“rno=“+rno+”name=“+name);
}
} // class Student is closed

class Ma
{
public static void main(String arg[])
{
Student s1=new Student(11, ” Ram”);
Student s2=new Student(22, ” Laxman”);
}
} // class Ma is closed
Method Overloading in Java

If a class has multiple methods having same name but different in

parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the

methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there

can be any number of arguments, if you write the method such as

a(int,int) for two parameters, and b(int,int,int) for three parameters then

it may be difficult for you as well as other programmers to understand

the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly


Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type.

The first add method receives two integer arguments and second add

method receives two double arguments.


int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
Java static keyword
The static keyword in java is used for memory management
mainly. We can apply java static keyword with variables, methods,
blocks and nested class. The static keyword belongs to the class
than instance of the class.
The static can be:

variable (also known as class variable)


method (also known as class method)
block
nested class
Java static variable

If you declare any variable as static, it is known static variable.


The static variable can be used to refer the common
property of all objects (that is not unique for each object)
e.g. company name of employees, college name of
students etc.
The static variable gets memory only once in class area at
the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Example of static variable
//Program of static variable

class Student{
int rollno;
String name;
static String college;

Student(int r,String n){


rollno = r;
name = n;
college ="Bhavans";
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");

s1.display();
s2.display();
}
}

Output:111 Karan ITS


222 Aryan ITS
Java static method
If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an


instance of a class.
static method can access static data member and can change the value of it.
//Program to get cube of a given number by static method
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
Nesting of Methods
When a method in java calls another method in the same class, it is called
Nesting of methods.
Here is the source code of the Java Program to Show the
Nesting of Methods.
public class NestingMethods
{
int l,b;
NestingMethods(int i, int j)
{
l=i;
b=j;
}
int area()
{
int a1=l*b;
return a1;
}
int diplay()
{
int result=area();
return result;
}
Example for single inheritance
Example Program for super() keyword and subclass Constructor
Class Super
{
int x;
Super(int xx)
{
x=xx;
}
}

S
// Example program for Method Overriding
class Parent class Over
{ {
int x; public static void main(String arg[])
void display() {
{ Child oo=new Child();
x=200; oo.display();
} }
} // class Parent is closed } // class Over is closed
class Child extends Parent
{
int y;
void display()
{
y=400;
System.out.println(“x=“+x+”y=“+y);
}
} // class Child is closed
Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.

•Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )

•But, if a class has at least one abstract method, then the class must be declared abstract.
•If a class is declared abstract, it cannot be instantiated.
•To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
•If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

A Java abstract class is a class which cannot be instantiated, meaning you cannot create new instances of an
abstract class. The purpose of an abstract class is to function as a base for subclasses. This Java abstract class
tutorial explains how abstract classes are created in Java, what rules apply to them. This tutorial gets into the
purpose of abstract classes in Java in more detail towards the end of this text.

Declaring an Abstract Class in Java


In Java you declare that a class is abstract by adding the abstract keyword to the class declaration. Here is a
Java abstract class example:
abstract class MyAbstractClass {}
Abstract Methods
An abstract class can have abstract methods. You
declare a method abstract by adding the abstract
keyword in front of the method definition.
Here is a Java abstract method example:
public abstract class MyAbstractClass
{
abstract void abstractMethod();
}
An abstract method has no implementation. It just has a method
signature. Just like methods in a Java interface.
If a class has an abstract method, the whole class must be
declared abstract. Not all methods in an abstract class have to be
abstract methods. An abstract class can have a mixture of abstract
and non-abstract methods.
Eg program:
abstract class Parent
{
void display()
{
System.out.println("hello");
}
abstract void area();
}
class Rectangle extends Parent
{
void area()
{
int l=5,b=4;
System.out.println(l*b);
}
}
class Square extends Parent
{
void area()
{
int s=5;
System.out.println(s*s);
}
}
class Abstract1
{
public static void main(String a[])
{
Rectangle r1=new Rectangle();
Square s1=new Square();
r1.area();
r1.area();
s1.area();
r1.display();
s1.display();

}}
final keyword
1) final variable
final variables are nothing but constants. We cannot change the value
of a final variable once it is initialized. Lets have a look at the below
code:

class Demo
{
final int MAX_VALUE;
void myMethod()
{
MAX_VALUE=101;
}
public static void main(String args[])
{ Demo obj=new Demo();
obj.myMethod();
}
}
final class

We cannot extend a final class.

A constructor cannot be declared as final.

Local final variable must be initializing during declaration.

All variables declared in an interface are by default final.

We cannot change the value of a final variable.

A final method cannot be overridden.

A final class not be inherited. If method parameters are declared final then the

value of these parameters cannot be changed. It is a good practice to name final

variable in all CAPS.) final, finally and finalize are three different terms. finally is

used in exception handling


Java Array
Array is a collection of similar type of elements that have contiguous memory location.

J ava array is an object that contains elements of similar data type. I t is a data structure
where we store similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index.

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
1. dataType[] arr; (or)
2. dataType arr[];
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional 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;

//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]); }}
Multidimensional array in java
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Two dimensional Array in java
dataType[][] aa; (or)
dataType aa[][]; (or)

Example to instantiate Two dimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column
initialize Two dimensional Array in java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
program: two dimensional arrays(Addition of two
matrices)
class Test{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}
Strings:

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters.


In java, string is an immutable object which means it is constant and can
cannot be changed once it has been created.

Creating a String
There are two ways to create a String in Java

1. String literal
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String
instance:

String str1 = "Welcome";


String str2 = "Welcome";

Using New Keyword


Interfaces
 Interface is similar to class. It is a collection of abstract methods. A

class implements an interface, thereby inheriting the abstract

methods of the interface.

 Along with abstract methods, an interface may also contain

constants, default methods, static methods, and nested types.

Method bodies exist only for default methods and static methods.

 Writing an interface is similar to writing a class. But a class

describes the attributes and behaviors of an object. And an

interface contains behaviors that a class implements.


Declaring Interfaces
The interface keyword is used to declare an interface
Interfaces have the following properties −
 An interface is implicitly abstract. You do not need to use
the abstractkeyword while declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed.
 Methods in an interface are implicitly public.
// Example program for multiple Inheritance using interfaces
interface A1
{
abstract void area();
}
interface B1
{
void perimeter();
}
class Multiple implements A1,B1
{
public void area()
{
int a,l,b;
l=5;
b=4;
a=l*b;
System.out.println(a+"\n");
}
public void perimeter()
{
int l,b,p;
l=5;
b=4;
p=2*(l+b);
System.out.println(p);
}
}
class Inheritance
{
public static void main(String args[])
{
Multiple m1=new Multiple();
m1.area();
m1.perimeter();
}
}

You might also like