0% found this document useful (0 votes)
6 views29 pages

javanotes_unit2

The document covers fundamental concepts of Java programming, including arrays, inheritance, special keywords, abstract classes, interfaces, and exception handling. It provides definitions, syntax, and examples for each topic, emphasizing the structure and functionality of Java code. Key concepts such as method overriding, the use of 'this' and 'super' keywords, and the distinction between classes and interfaces are also explained.

Uploaded by

Mi Groot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

javanotes_unit2

The document covers fundamental concepts of Java programming, including arrays, inheritance, special keywords, abstract classes, interfaces, and exception handling. It provides definitions, syntax, and examples for each topic, emphasizing the structure and functionality of Java code. Key concepts such as method overriding, the use of 'this' and 'super' keywords, and the distinction between classes and interfaces are also explained.

Uploaded by

Mi Groot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit-2

1) Define arrays ? how to declare arrays in java ?


2) Define inheritance ? what are the types of inheritance?

3) explain about the following keyword and methods


a) this keyword b) super keyword c) abstract class d) final keyword
e) static keyword
4) define method overridden and explain with example?
5) Define interface ? explain with example ?
6) Explain about abstract classes in java?

7) Define packages ? how to import packages ? what are the categories of


packages?

8) Define string ?how to declare it? What are String methods in java
9) Define exception ? what are the types of exceptions ?

1)Define arrays ? how to declare arrays in java ?

Java Arrays
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at
a time.
In java, arrays are objects and they are created dynamically using new operator. Every
array in java is organized using index values. The index value of an array starts with '0'
and ends with 'size-1'. We use the index value to access individual elements of an
array.
In java, there are two types of arrays and they are as follows.

 One Dimensional Array


 Multi Dimensional Array

Creating an array
In the java programming language, an array must be created using new operator and
with a specific size. The size must be an integer value

S.Rajeshwari , Lecturer in Computers 1


Syntax

data_type array_name[ ] = new data_type[size];

class arrayex
{
public static void main(String args[])
{

int a[ ]=new int[10];


int i;

a[0]=10;
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

System.out.println("array elements are");


for(i=0;i<5;i++)
System.out.print(a[i]+ " ");
}
}

Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional,
3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional
array variable, specify each additional index using another set of square brackets. We
use the following syntax to create two-dimensional array.
Syntax

data_type array_name[ ][ ] = new data_type[rows][columns];

ex: int x[][]=new int[3][3];

here x is create 3 rows and 3 cols as:

x[0][0] x[0][1] x[0][2]

S.Rajeshwari , Lecturer in Computers 2


x[1][0] x[1][1] x[1][2]

x[2][0] x[2][1] x[2][2]

When we create a two-dimensional array, it created with a separate index for rows and
columns. The individual element is accessed using the respective row index followed by
the column index.
//matrix ex
class arrayex
{
public static void main(String args[])
{

int a[ ][]=new int[2][2];


int i,j;

a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;

System.out.println("matrix is \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.print(a[i][j]+ " ");
}
System.out.println();

}
}
}
o/p
10 20
30 40

Java Classes

S.Rajeshwari , Lecturer in Computers 3


2)Define inheritance ? what are the types of inheritance?
inheritance :

The inheritance is the process of acquiring the properties of one class to another class.
(or)
The inheritance is the process of creating new class from an existing class.

Here existing class is called parent class or super class or base class.

The Parent class is the class which provides features to another class. The parent class
is also known as Base class or Superclass.

New class is called child class or sub class or derived class.

The Child class is the class which receives features from another class. The child class
is also known as the Derived Class or Subclass.

In the inheritance, the child class acquires the features from its parent class. But
the parent class never acquires the features from its child class.

Advantages of inheritance:
1. Reusability of code
2. To increase the features to the base class
3. To increase the reliability of the base class.

Creating super Class


It is same as normal class definition

Syntax

Syntax:

class <ParentClassName>

S.Rajeshwari , Lecturer in Computers 4


{ ...
//Implementation of parent class
...
}

Creating Child Class in java

In java, we use the keyword extends to create a child class. The following syntax used
to create a child class in java.

Syntax:

class <ChildClassName> extends <ParentClassName>


{
//Implementation of child class
}

In a java programming language, a class extends only one class. Extending multiple
classes is not allowed in java.

There are five types of inheritances, and they are as follows.

 Simple Inheritance (or) Single Inheritance

 Multiple Inheritance

 Multi-Level Inheritance

 Hierarchical Inheritance
 Hybrid Inheritance

S.Rajeshwari , Lecturer in Computers 5


1. Simple Inheritance (or) Single Inheritance: in this type only one
super class and only one sub class.

//example of single inheritance


class student
{
int rno;
String name;
void getdata1()
{
rno=101;

S.Rajeshwari , Lecturer in Computers 6


name="ram";
}
void display1()
{
System.out.println("rno= "+rno);
System.out.println("name :"+name);
}
}
class test extends student
{
int m1,m2;
void getdata2()
{
m1=80;
m2=70;
}
void display2()
{
System.out.println("m1="+m1);
System.out.println("m2="+m2);
}
}

class single
{
public static void main(String args[])
{
test k=new test();
k.getdata1();
k.getdata2();
k.display1();
k.display2();
}
}

o/p: rno=101
name=ram
m1=80
m2=70

1) Multiple inheritance:

S.Rajeshwari , Lecturer in Computers 7


In this type, a class is derived several super classes . that is there
is only one sub class and several super classes.

Java does not support multiple inheritance. This problem is solved


through the interface.

2) Multilevel inheritance:
One class is derived from using another derived class is called multi
level inheritance ,

class student
{
int rno;
String name;
void getdata1()
{
rno=101;
name="ram";
}
void display1()
{
System.out.println("rno= "+rno);
System.out.println("name :"+name);
}
}
class test extends student

S.Rajeshwari , Lecturer in Computers 8


{
int m1,m2;
void getdata2()
{
m1=80;
m2=70;
}
void display2()
{
System.out.println("m1="+m1);
System.out.println("m2="+m2);
}
}
class result extends test
{
int tot;
void display3()
{
tot=m1+m2;
System.out.println("tot= "+tot);
}
}

class multilevel
{
public static void main(String args[])
{
result k=new result();
k.getdata1();
k.getdata2();
k.display1();
k.display2();
k.display3();
}
}

o/p
rn0=101
name=ram
m1=80
m2=70
tot= 150

3) Hybrid inheritance:
Combination of multiple and multilevel is called hybrid inheritance.
It is also solved with interface .

S.Rajeshwari , Lecturer in Computers 9


Special keywords and methods in java

3)explain about the following keyword and methods


a) this keyword b) super keyword c) abstract class d) final keyword
e) static keyword

1) this :
this is one type of special keyword in java . it can be used for two
purposes.
a) this keyword for variable
b) this() constructor

a) this keyword for variable :


when a local variable and instance variables (class members) have the
same name using this keyword we can call the instance variable.

Example:
class add
{
int x,y,s;
add(int x,int y)
{
this.x=x;
this.y=y;
}
void display()
{
s=x+y;
System.out.println("sum= "+s);
}
}

class thiskey
{
public static void main(String args[])
{
add k=new add(10,20);
k.display();

}
}

S.Rajeshwari , Lecturer in Computers 10


b) this () constructor:
this() constructor is used to call one constructor function to another
constructor function with in the same class. Depending on the parameters
the appropriate constructor is executed.

Rules for this() constructor:

1. this statement is the first statement in the constructor


2. we cannot use more than one this() constructor in same constructor

// this() constructor example

class overload
{

overload(int x)
{
System.out.println("integer value x="+x);

}
overload(double y)
{
this(10);
System.out.println("double value y="+y);
}
overload(char z)

{
this(20.5);
System.out.println("character value z="+z);
}
}

class thiscon
{
public static void main(String args[])
{

overload k1 = new overload('A');

}
}

o/p: integer value x : 10

S.Rajeshwari , Lecturer in Computers 11


double value y : 20.5
character value z= A
2) super keyword

super is also one of the special keyword in java. It can be used in 3 ways:

a) super keyword for variable


b) super keyword for method
c) super() constructor

a) super keyword for variable:

when super class variable name and sub class variables are same using
the super keyword we can access super class variables.

// super keyword for variable

class base
{
int x=10;
}
class derived extends base
{
int x=20;
void display()
{
System.out.println("super class x value ="+super.x);

System.out.println("derived class x value ="+x);


}
}
class superkeyword
{
public static void main(String args[])
{
derived k=new derived();
k.display();
}
}
o/p:
super class x value = 10
derived class x value = 20

b) super keyword for method

S.Rajeshwari , Lecturer in Computers 12


4) define method overridden and explain with example?

The super class and sub class have the same method name , same
arguments and same return type , then when we call super class method
,in that case the sub class method is executed instead of super class
method. . this type of concept is called method overridden .
To overcome overridden concept we can use super keyword to call the
super class method.

Syntax: super.methodname();

// super keyword for method


class base
{
void display()
{
System.out.println("this is super class display function");
}
}
class derived extends base
{

void display()
{
super.display();
System.out.println("this is derived class display function");

}
}
class supermethod
{
public static void main(String args[])
{
derived k=new derived();
k.display();
}
}

o/p: this is super class display function


this is derived class display function

S.Rajeshwari , Lecturer in Computers 13


5) super() constructor:

super() constructor is used to call super class constructor from sub class
constructor dependind on the passing parameters , the appropriate constructor
is executed.

// super constructor

class base
{
base()
{
System.out.println("this is base class funtion");
}

}
class derived extends base
{
derived()
{
super();
System.out.println("this is derived class function");
}
}
class supercon
{
public static void main(String args[])
{
derived k=new derived();
}
}
o/p: this base class function
this is derived class function

abstract class:
5) Explain about abstract classes in java?

S.Rajeshwari , Lecturer in Computers 14


Abstract class in Java

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have


abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated that is it does not have definition part. Definition part
can be done in sub class.
o Abstract methods must be overridden in sub class.

// abstract class

abstract class base


{

void display1()
{
System.out.println("this is non abstarct method");
}

abstract void display2();


}
class derived extends base

{
void display2()
{
System.out.println("this is abstract methdo ");
}
}
class abstractex
{

public static void main(String args[])


S.Rajeshwari , Lecturer in Computers 15
{
derived k = new derived();
k.display1();
k.display2();
}
}

Interface in Java

6) Define interface ? explain with example ?

An interface is basically a kind of class. Like classes interface is also contains variables
and methods.

But the difference between class and interface is :

class contains mixed data (variables and final constants) and mixed methods (normal
methods and abstract methods).

Interface contains only final methods and abstract methods.

Syntax:

interface interface-name

// final variables

// abstract methods

When ever we want to add interface features in class we must use implements
keyword.

Ex:

Class class-name implements interface-name

-----------

S.Rajeshwari , Lecturer in Computers 16


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.

//interface example

class student
{
int rno;
String name;
void getdata1()
{
rno=101;
name="ram";
}
void display1()
{
System.out.println("rno= "+rno);
System.out.println("name :"+name);
}
}
class test extends student
{
int m1,m2;
void getdata2()
{
m1=80;
m2=70;
}
void display2()
{
System.out.println("m1="+m1);
System.out.println("m2="+m2);
}
}
interface sports
{
final int spwt=5;
abstract public void display3();

S.Rajeshwari , Lecturer in Computers 17


}
class result extends test implements sports
{
int tot;
public void display3()
{
tot=m1+m2+spwt;
System.out.println("tot= "+tot);
}
}

class interfaceex
{
public static void main(String args[])
{
result k=new result();
k.getdata1();
k.getdata2();
k.display1();
k.display2();
k.display3();
}
}

7)Define packages ? how to import packages ? what are the categories of


packages?

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two types . they are :

1. built-in package or API packages

2. user-defined package.

Types of packages:

S.Rajeshwari , Lecturer in Computers 18


1. Built-in Packages

These packages consist of a large number of classes which are a part of


Java API(application programming interface) .

Some of the commonly used built-in packages are:

1) java.lang:

Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.

2) java.io:

Contains classed for supporting input / output operations.

3) java.util:

Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.

4) java.applet:

Contains classes for creating Applets.

5) java.awt:

Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).

6) java.net:

Contain classes for supporting networking operations.

S.Rajeshwari , Lecturer in Computers 19


Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

2)User-defined packages
These are the packages that are defined by the user. That‟s why it is called
user defined package. Whenever we want access classes we must use import
statement as:

import packagename.classname;

Or

import package-name.*;

For creating user defined package the following steps are required :
S.Rajeshwari , Lecturer in Computers 20
Step1 : create a directory, which has the same name as package.

C:\> jdk1.7>bin> md pack

C:\>jdk1.7>bin>cd pack

C:>jdk1.7>bi>pack>

Step 2: open a new file and create a new package. Directory name and
package name must be same..and class and methods must be public.

1)first.java

package pack;
public class first
{
public void display()
{
System.out.println("this is first class display function");
}
}
Save file as first.java
2)second.java

package pack;
public class second
{
public void display()
{
System.out.println("this is second class display function");
}
}
Save file as second.java

Whwnevr we want to add these classes in another program , we must import classes
using the import statement.

3)imp.java

Import pack.*;

S.Rajeshwari , Lecturer in Computers 21


class imp

public static void main(String args[])

first k1=new first();

second k2=new second();

k1.display();

k2.display();

Access Modifiers in Java


There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside

S.Rajeshwari , Lecturer in Computers 22


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

8)Define string ?how to declare it? What are String methods in java

String is a sequence of characters. But in Java, string is an object that represents a


sequence of characters. The java.lang.String class is used to create a string object.

in java strings are created using 3 ways:

1. Using char data type


2. Using String class
3. Using StringBuffer class keyword

1. Using char data type

String can be created using char data type as:

char name[ ]=new char[4];

name[0]=‟j‟;

name[1]=‟a‟;

name[2]=‟v‟;

name[3]=‟a‟;

(or) char name[ ]={„j‟,‟a‟,‟v‟,‟a‟};

for(i=0;i<name.length;i++)

S.Rajeshwari , Lecturer in Computers 23


System.out.println(name[i]);

2) using String class :

Java String literal is created by using String class and it is enclosed with in double
quotes. For Example:

String s=new Sting("java");

System.out.println(s);
3) using StringBuffer class:

StringBuffer is also same as Sting class. But the difference between String and
StringBuffer is :
String class contains fixed size, but StringBuffer class contains flexible size .
Ex: StringBuffer s=new StringBuffer(“java”);

String methods in java

The java.lang.String class provides many useful methods to perform operations on


sequence of char values.

No. Method Description

1 charAt() returns char value for the


particular index
2 length() returns string length

3 substring() returns substring for given


begin index.
4 substring(int returns substring for given
beginIndex, int endIndex) begin index and end index.
5 join() returns a joined string.

6 equals() checks the equality of


string with the given object.
7 isEmpty() checks if string is empty.

8 concat() concatenates the specified


string.
9 replace(char old, replaces all occurrences of
char new) the specified char value.

S.Rajeshwari , Lecturer in Computers 24


10 replace( old, new) replaces all occurrences of
the specified CharSequence.
11 equalsIgnoreCase() compares another string. It
doesn't check case.
12 split() returns a split string
matching regex.
13 indexOf(int ch) returns the specified char
value index.
14 toLowerCase() returns a string in
lowercase.
15 toUpperCase() returns a string in
uppercase.
16 trim() removes beginning and
ending spaces of this string.

Example:

//string example
class stringexample
{
public static void main(String args[])
{
String s1=new String("Java Programming");
String s2=new String ("Language");
String s3=new String("JAVA PROGRAMMING");
System.out.println("no. of characters in s1 string is "+s1.length());
System.out.println("upper string is "+s1.toUpperCase());
System.out.println("upper string is "+s1.toLowerCase());

System.out.println("compare s1 and s3 "+s1.equals(s3));


System.out.println("compare s1 and s3 "+s1.equalsIgnoreCase(s3));
System.out.println("substring of s1 "+s1.substring(5));
System.out.println("substring of s1 "+s1.substring(5,12));
System.out.println("substring of s1 "+s1.concat(s2));
}
}

S.Rajeshwari , Lecturer in Computers 25


9.Define exception ? what are the types of exceptions ?

Exception Handling in Java

The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.

An exception is an unwanted or unexpected errors , which occurs during the execution


of a program i.e at run time, that errors disrupts the normal flow of the program‟s
execution.

Types of Java Exceptions

There are mainly two types of exceptions:

1. Checked exception or compile time errors


2. Unchecked Exception or run time errors

1) Checked Exception

These type of errors are occurred at the time of compile program. Ex: data
type mismatch error, syntax errors, semicolon missing etc.

2) Unchecked Exception or runtime errors

These type of errors are occurs at the time of running the program. e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.

In java language exception handling mechanism can be used to handle run time errors.

S.Rajeshwari , Lecturer in Computers 26


Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we
can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.

finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.

//exception handling example


class exceptionex
{
public static void main(String args[])
{
int a=20,b=10,c=10,x,y;

try
{
x=a/(b-c);

S.Rajeshwari , Lecturer in Computers 27


System.out.println("x= "+x);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

catch(ArithmeticException e)
{
System.out.println(e);
}

finally
{

y=a/(b+c);
System.out.println("y= "+y);
}

}
}

Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has
occurred in an arithmetic operation.

2. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an


array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.

3. ClassNotFoundException : This Exception is raised when we try to


access a class whose definition is not found.

4. FileNotFoundException : This Exception is raised when a file is not


accessible or does not open

5. NoSuchMethodException : t is thrown when accessing a method which


is not found

S.Rajeshwari , Lecturer in Computers 28


6. NullPointerException : This exception is raised when referring to the
members of a null object. Null represents nothing

7. StringIndexOutOfBoundsException : It is thrown by String class


methods to indicate that an index is either negative than the size of the
string.

S.Rajeshwari , Lecturer in Computers 29

You might also like