0% found this document useful (0 votes)
20 views48 pages

Unit 2

Uploaded by

shahmeet644
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)
20 views48 pages

Unit 2

Uploaded by

shahmeet644
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/ 48

Java Programming Notes CO5G

Chapter-
Chapter-2

1. Defining a Class, Creating a class and Accessing class Members:


A class is a user-defined type which groups data members and its associated functions together. Data is
encapsulated in a class by placing data fields and methods inside body of class definition.

An object is a variable of class. The primary purpose to create an object of a class is to access the
members (data and methods) of class.

Syntax to define a class:


class class_name
{
data_type member1_name;
data_type member2_name;
:
return_type method1(parameter list)
{
//statements;
}
return_type method2(parameter list)
{
//statements;
}
}

Syntax to create an object


Class_name obj_name=new class_name()

Syntax to access class members


Obj_name.membername
Object_name.methodname(argument list)

Example 1:

public class Student


{
String name ="abc";
int age = 20;
void display()
{

Prepared by: Meenakshi A.Thalor Page 1


Java Programming Notes CO5G
System.out.println("My name is "+name);
System.out.println("I am "+ age+ " years old");
}
public static void main(String args[])
{
Student s=new Student ();
s.display(); // accessing methods using object
}
}
Output:

My name is abc
I am 20 years old

Example2:

class Student
{
String name;
int age;
void display()
{
System.out.println("My name is "+name);
System.out.println("I am "+ age+ " years old");
}
public static void main(String args[])
{
Student s=new Student();
s.name="xyz"; //accessing data using object
s.age=20;
s.display(); // accessing methods using object
}
}

Output:
My name is xyz
I am 20 years old

Example 3:
class Student
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;

Prepared by: Meenakshi A.Thalor Page 2


Java Programming Notes CO5G
}
void display()
{
System.out.println("My name is "+name);
System.out.println("I am "+ age+ " years old");
}
public static void main(String args[])
{
Student s=new Student();
s.accept("xyz",20);
s.display();
}
}

Output:
My name is xyz
I am 20 years old

2. Constructor
A constructor initializes an object immediately upon the creation. This process is known as automatic
initialization of an object. Constructor is a special method that enables an object to initialize itself when it
is created

Properties of constructors:

• Its name is same as class name.


• It does not have any return type.
• It is used to initialization of objects during its creation.

Types of Constructor

1. Default constructor: A constructor without any argument is called default constructor. When user
does not write any constructor in program then all the objects are initialed by the data type with
default values.
2. Parameterized Constructor: A constructor with argument is called parameterized constructor.

Example: Calculate area of rectangle by using default constructor

class Rectangle
{
int length, width;
Rectangle() // default constructor
{

Prepared by: Meenakshi A.Thalor Page 3


Java Programming Notes CO5G
length=10;
width=20;
}
int rectArea() //simple method
{
return(length*width);
}
public static void main (String args[])
{
Rectangle r1=new Rectangle(); //calling default constructor
System.out.println(“Area of Rectangle=”+ r1.rectArea());
}
}

Output:

Area of Rectangle=200

Example: Calculate area of rectangle by using parameterized constructor method

class Rectangle
{
int length, width;
Rectangle(int a, int b) // parameterized constructor
{
length=a;
width=b;
}
int RectArea()
{
return(length*width);
}
public static void main (String args[])
{
Rectangle r1=new Rectangle(15,11); //calling parameterized constructor
int area1=R1.RectArea();
System.out.println(“Area1=”+area1);
}
}

Output:

Area of Rectangle=200

Prepared by: Meenakshi A.Thalor Page 4


Java Programming Notes CO5G

3. Nesting of methods:
Calling a method from another method is called as nesting of method. In following example max(int ,int)
is nested method as it is calling from display method.

class NestedDemo
{
int a=10;
int b=20;

void display()
{
System.out.println("Maximum is "+max(a,b));
}
int max( int a1,int b1)
{
if(a1>b1)
return(a1);
else
return(b1);
}
public static void main(String args[])
{
NestedDemo n=new NestedDemo ();
n.display();
}
}
Output:

Maximum is 20

4. This Keyword:
“this” keyword in Java is a special keyword which can be used to represent current object or instance of
any class in Java. “this” keyword can also call constructor of same class in Java and used to call
overloaded constructor. Here are few important points related to using this keyword in Java.

1) “this” keyword represent current instance of class: If member variable and local variable name
conflict than this can be used to refer member variable.

For example, the Point class was written like this

class Point
{

Prepared by: Meenakshi A.Thalor Page 5


Java Programming Notes CO5G
int x = 0;
int y = 0;

Point(int a, int b) //constructor


{
x = a;
y = b;
}
}

Here x,y are shadowed by a method or constructor parameter.But it could have been written like this:

class Point
{
int x = 0;
int y = 0;

Point(int x, int y) //constructor using this keyword


{
this.x = x;
this.y = y;
}
}

Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local
copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

2) “this” keyword can be used to call overloaded constructor in java. If used than it must be first statement
in constructor. Here is an example of using this() for constructor chaining:

class ThisDemo
{
int a;
int b;
ThisDemo()
{
this(10,20);
}
ThisDemo( int a,int b)
{
this.a=a;
this.b=b;
}
void display()
{
System.out.println("a=" +a+" "+"b="+b);
}

Prepared by: Meenakshi A.Thalor Page 6


Java Programming Notes CO5G

public static void main(String args[])


{
ThisDemo n1=new ThisDemo();
n1.display();
ThisDemo n2=new ThisDemo(30,40);
n2.display();
}
}
Output:

a=10 b=20
a=30 b=40

5. Using Command-Line Arguments


Sometimes you will want to pass information into a program when you run it. This is accomplished by
passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program's name on the command
line when it is executed. Accessing the command-line arguments inside a Java program is quite easy.They
are stored as strings in the String array passed to main( ).

Example:

The following program displays all of the command-line arguments that it is called with:

public class CommandLine


{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
{
System.out.println("args[" + i + "]: " + args[i]);
}
}
}

Try executing this program as shown here:

Javac CommandLine.java
java CommandLine Hello how are you?

This would produce the following result:

args[0]: Hello

Prepared by: Meenakshi A.Thalor Page 7


Java Programming Notes CO5G

args[1]: How
args[2]: are
args[3]: you?

6. Passing value at Run time


Rather than using command line arguments another way to pass information into a program at runtime is-
use BufferedReader class. BufferedReader class is defined in java.io package.

import java.io.*;
public class Person
{

public static void main(String [] args)


{
int a;
float b;
double c;
String s;
try
{
BufferedReader in=new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter integer number");
a=Integer.parseInt(in.readLine());
System.out.println("Enter float number");
b=Float.parseFloat(in.readLine());
System.out.println("Enter double number");
c=Double.parseDouble(in.readLine());
System.out.println("Enter string");
s=in.readLine();
System.out.println("Integer number: "+a);
System.out.println("Float number: "+b);
System.out.println("Double number: "+c);
System.out.println("String : "+s);
}
catch(Exception e)
{}
}
}
Output:

Enter integer number


10
Enter float number
12.5
Enter double number
23.56

Prepared by: Meenakshi A.Thalor Page 8


Java Programming Notes CO5G
Enter string
madam
Integer number:10
Float number:12.5
Double number:23.56
String :madam

7. Variable length Arguments (Vargs)


The feature of variable argument has been added in Java 5. This will enable you to write
methods/functions which takes variable length of arguments. For example the popular printf() method in
C. We can call printf() method with multiple arguments.

printf("%s", 50);
printf("%d %s %s", 250, "Hello", "World");

Varargs was added in Java 5 and the syntax includes three dots … (also called ellipses). Following is the
syntax of vararg method.

public void test(int count, String... args)


{
// code
}

Notice the dots … in above code. That mark the last argument of the method as variable argument. Also
the vararg must be the last argument in the method.
Now let us check simple hello world varargs code.

public class VarargsDemo


{
public static void main(String args[])
{
test(215, "India", "Delhi");
test(147, "United States", "New York", "California");
}
public static void test(int some, String... args)
{
System.out.print("\n" + some);
for(String a: args)
{
System.out.print(” “+a);
}
}
}
In above code, the test() method is taking variable arguments and is being called from main method with
number of arguments. Test is declared as static method as we cannot invoke a nonstatic method from
main method.

Prepared by: Meenakshi A.Thalor Page 9


Java Programming Notes CO5G

Output:

215 India Delhi


147 United States New York California

Example2:

class VargsDemo
{
void display( String... args)
{
for(String a: args)
{
System.out.print( a + " ");
}
}
public static void main(String args[])
{
VargsDemo n1=new VargsDemo();
n1.display("hello","how","are","you?");
}
}

Output:

Hello how are you?

8. Finalize method
In java when class objects are created, the appropriate constructor is called but Java does not require a
destructor, because memory is not directly allocatable. However, class objects may still create conditions
that must be manually undone, such as closing files opened for I/O. In Java, classes may define a
method called finalize() . If finalize() exists for a class, it is called just before an instance of that class is
destroyed. The compiler generates a default finalize() method if a class does not provide one. Note that
the exact time that finalize() is called can never be predicted, simply because the exact time of garbage
collection (i.e., actual destruction of objects) cannot be predicted. Under some circumstances, such as
when the interpreter exits at the end of a program, it is possible that finalize() might never be called. Thus,
the programmer of a class should never rely on finalize()to do critical tasks. finalize() is only useful to
free system resources, such as open files and network connections. A finalizer method is declared by
naming it finalize() with no parameters and a void return value.

The java.lang.Object.finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object. A subclass overrides the finalize method to
dispose of system resources or to perform other cleanup.
Syntax:
Following is the declaration for java.lang.Object.finalize() method

Prepared by: Meenakshi A.Thalor Page 10


Java Programming Notes CO5G

protected void finalize()

Example
The following example shows the usage of lang.Object.finalize() method.

public class Person


{
void display()
{
System.out.println("Just want to say hello!!!");
}
public static void main(String [] args)
{
try
{
Person p=new Person();
p.display();
System.out.println("finalizing...");
p.finalize();
System.out.println("finalized");
}
catch(Throwable e)
{}
}
}

Let us compile and run the above program, this will produce the following result:

Just want to say hello!!!


Finalizing...
Finalized.

9. Object Class
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a
descendant of the Object class. Every class you use or write inherits the instance methods of Object.
Following table is showing the methods of Object class. You need not use any of these methods, but, if
you choose to do so, you may need to override them with code that is specific to your class.

S.N. Method Description

1 protected Object clone() This method creates and returns a copy of this object.

2 boolean equals(Object obj) This method indicates whether some other object is "equal to" this one.

3 protected void finalize() This method is called by the garbage collector on an object when

Prepared by: Meenakshi A.Thalor Page 11


Java Programming Notes CO5G

garbage collection determines that there are no more references to the


object.
4 Class<?> getClass() This method returns the runtime class of this Object.

5 int hashCode() This method returns a hash code value for the object.

void notify() This method wakes up a single thread that is waiting on this object's
6
monitor.
void notifyAll() This method wakes up all threads that are waiting on this object's
7
monitor.
8 String toString() This method returns a string representation of the object.

void wait() This method causes the current thread to wait until another thread
9
invokes the notify() method or the notifyAll() method for this object.
This method causes the current thread to wait until either another
void wait(long timeout)
10 thread invokes the notify() method or the notifyAll() method for this
object, or a specified amount of time has elapsed.
This method causes the current thread to wait until another thread
void wait(long timeout, int
invokes the notify() method or the notifyAll() method for this object, or
11 nanos)
some other thread interrupts the current thread, or a certain amount of
real time has elapsed.

10. Visibility controls/Access Specifiers:


Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are:
• Visible to the package. The default. No modifiers are needed.(Friendly)
• Visible to the class only (private).
• Visible to the world (public).
• Visible to the package and all subclasses (protected).
Default Access Modifier – friendly:
Default access modifier means we do not explicitly declare an access modifier for a class, field, method,
etc. A variable or method declared without any access control modifier is available to any other class in
the same package.

Private Access Modifier - private:


Methods, Variables and Constructors that are declared private can only be accessed within the declared
class itself.Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.Variables that are declared private can be accessed outside the class if public getter methods are
present in the class.Using the private modifier is the main way that an object encapsulates itself and hide
data from the outside world.

Prepared by: Meenakshi A.Thalor Page 12


Java Programming Notes CO5G

Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed from any other class. However
if the public class we are trying to access is in a different package, then the public class still need to be
imported.Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.

Protected Access Modifier - protected:


Variables, methods and constructors which are declared protected in a superclass can be accessed only by
the subclasses in other package or any class within the package of the protected members' class.

Private protected Access:


A field can be declared with two keywords private and protected together. This gives a visibility level in
between the "protected" access and "private" access. This modifier makes the fields visible in all
subclasses regardless of what package they are in. Remember, these fields are not accessible by other
classes in the same package.

• The following table summarizes the visibility provided by various access modifiers.

Access modifier public protected friendly private private


protected
Own class √ √ √ √ √
Sub class in same package √ √ √ √ ˟
Other classes in same package √ √ √ ˟ ˟
Sub class in other package √ √ ˟ √ ˟
Other classes in other package √ ˟ ˟ ˟ ˟

11.Array
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables.

The following code declares an array variable and initializes it to null:


char data[] = null;
or
char[] data = null;

To declare an array variable and initialize it to refer to a new instance, use the following syntax:
int[] data = new int [10];
or

Prepared by: Meenakshi A.Thalor Page 13


Java Programming Notes CO5G
int data[]=new int[10]

The declaration of an array must include its type, but not its size. Arrays may be initialized with
conventional initialization syntax.

int[] int_array = {1, 3, 4, 15, 0};

Example 1 :Accept and display data for array


import java.io.*;
public class Person
{

public static void main(String [] args)


{
int arr[]=new int[5];
try
{
BufferedReader br=new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter elements of array");
for(int i=0;i<5;i++)
arr[i]=Integer.parseInt(br.readLine());
System.out.println("Elements are:");
for(int j=0;j<5;j++)
System.out.println(arr[j]);

}
catch(Exception e)
{}

}
}
Output:

Enter elements of array


10
20
30
40
50
Elements are:
10
20
30
40
50

Example 2 : Accept and display data for array and display sum of array.

Prepared by: Meenakshi A.Thalor Page 14


Java Programming Notes CO5G

import java.io.*;
public class Person
{

public static void main(String [] args)


{
int arr[]=new int[5];
int sum=0;
try
{
BufferedReader br=new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter elements of array");
for(int i=0;i<5;i++)
{
arr[i]=Integer.parseInt(br.readLine());
sum=sum+arr[i];
}
System.out.println("Elements are:");
for(int j=0;j<5;j++)
System.out.println(arr[j]);
System.out.println("Sum:" +sum);
}
catch(Exception e)
{}

}
}

Output:

Enter elements of array


10
20
30
40
50
Elements are:
10
20
30
40
50
Sum: 150

Example 3: Search an element in an array

Prepared by: Meenakshi A.Thalor Page 15


Java Programming Notes CO5G
class Search
{
public static void main(String[] args)
{
int a[]= { 32, 87, 3, 589, 12, 1076, 2000,8, 622, 127 };
int num = 12;
int i;
boolean flag = false;
for (i = 0; i < a.length; i++)
{
if (a[i] == num)
{
flag = true;
break;
}
}
if (flag)
System.out.println("Found " + num + " at index " + i);
else
System.out.println(num + " not in the array");
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface, terminates
the for loop when that value is found. Control flow then transfers to the statement after the for loop. This
program's output is:
Found 12 at index 4

Example 4: Accept and display data for 2 D array.

import java.io.*;
public class Person
{
public static void main(String [] args)
{
int arr[][]=new int[2][2];
try
{
BufferedReader in=new BufferedReader( new InputStreamReader(System.in));
System.out.println("Enter elements of array");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
arr[i][j]=Integer.parseInt(in.readLine());
}
System.out.println("Elements are:");
for(int i=0;i<2;i++)

Prepared by: Meenakshi A.Thalor Page 16


Java Programming Notes CO5G
{
for(int j=0;j<2;j++)
System.out.println(arr[i][j]);
}
}
catch(Exception e)
{}
}

Output:
Enter elements of array
1
2
3
4

Elements are:
1
2
3
4
The Array Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing
arrays, and filling array elements. These methods are overloaded for all primitive types.

SN Methods Description

Searches the specified array of Object ( Byte, Int , double, etc.) for the
public static int
specified value using the binary search algorithm. The array must be
1 binarySearch(Object[] a,
sorted prior to making this call. This returns index of the search key, if
Object key)
it is contained in the list; otherwise, (-(insertion point + 1).

Returns true if the two specified arrays of longs are equal to one
another. Two arrays are considered equal if both arrays contain the
public static boolean same number of elements, and all corresponding pairs of elements in
2
equals(long[] a, long[] a2) the two arrays are equal. This returns true if the two arrays are equal.
Same method could be used by all other primitive data types (Byte,
short, Int, etc.)

3 public static void fill(int[] a, Assigns the specified int value to each element of the specified array of
int val) ints. Same method could be used by all other primitive data types

Prepared by: Meenakshi A.Thalor Page 17


Java Programming Notes CO5G

(Byte, short, Int etc.)

public static void Sorts the specified array of objects into ascending order, according to
4 sort(Object[] a) the natural ordering of its elements. Same method could be used by all
other primitive data types ( Byte, short, Int, etc.)

Example:

import java.util.Arrays;

class ArrayDemo
{
public static void main(String[] args)
{
int Arr[] = {2, 1, 9, 6, 4};
Arrays.sort(Arr);

System.out.println("The sorted int array is:");


for (int number : Arr)
{
System.out.println("Number = " + number);
}

int num = 4;

int index = Arrays.binarySearch(Arr,num);

System.out.println("The index of element 4 is : " + index);


}
}
Output:

The sorted int array is:


1
2
4
6
9
The index of element 4 is: 2
12. String class

The String class represents character strings. All string literals in Java programs, such as "abc", are
implemented as instances of this class.

Prepared by: Meenakshi A.Thalor Page 18


Java Programming Notes CO5G
Strings are constant; their values cannot be changed after they are created. String buffers support mutable
strings. Because String objects are immutable they can be shared. For example:

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};


String str = new String(data);
Constructor of String class:

Constructor Description
String() Initializes a newly created String object so that it represents an empty
character sequence.
String(char[] value) Allocates a new String so that it represents the sequence of characters
currently contained in the character array argument.
String(String original) Initializes a newly created String object so that it represents the same
sequence of characters as the argument; in other words, the newly created
string is a copy of the argument string.

Methods of String class:

Following tables shows the methods of string class.Here s1 is object of sting class which is invoking the
built in methods of string class.

Sr. Method Description Syntax


No.
1 S1.toUpperCase() convert a string into uppercase String toUpperCase()
letter

2 S1.toLowerCase() convert a string into Lower case String toLowerCase()


letter

3 S1.replace(‘x’,’y’) Replace all appearance of ‘x’ by String replace(char ‘x’,char ‘y’)


‘y’
4 S1.trim() Remove whitespaces at beginning String trim()
and end of string str
5 S1.equals(s2) Returns true if invoking sting is boolean equals(String s2)
equal to string s2.
6 S1.equalsIgnoreCase Returns true if invoking sting is boolean equalsIgnoreCase(String s2)
(s2) equal to string s2,ignoring the
case of characters
7 S1.length() Return length of string int length()
8 S1.charAt(n) Return character at index n char charAt(int n)
9 S1.compareTo(s2) Return –ve if s1<s2, Int compareTo(String s2)
+ve if s1>s2

Prepared by: Meenakshi A.Thalor Page 19


Java Programming Notes CO5G
0 of s1=s2
10 S1.concat(s2) Give concatenation of string s1 String concat(String s2)
and s2
11 S1.substring(n) Gives substring starting from nth String substring(int n)
index
12 S1.substring(n,m) Gives substring starting from nth String substring(int n,int m)
index upto mth-1
13 S1.indexOf(‘x’) Gives the position of first int indexOf(char ‘x’)
occurence of ‘x’ in string s1
14 S1.indexOf(‘x’,n) Gives the position of ‘x’ that int indexOf(char ‘x’,int n)
occur after nth position in string
s1

Example of toUpperCase()
class Example_UpperCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Uppercase :"+str.toUpperCase());
}
}
Output:
Uppercase :HELLO

Example of toLowerCase()

class Example_LowerCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("LowerCase: "+str.toLowerCase());
}
}
Output:
Lowercase :hello

Example of trim()
class Example_Trim
{
public static void main(String args[])
{
String str=new String(" Hello Java");
System.out.println("Trimed String :"+str.trim());
}

Prepared by: Meenakshi A.Thalor Page 20


Java Programming Notes CO5G
}
Output:
Trimed String: Hello Java

Example of charAt)

class Example_CharAt
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Char At 3:"+str.charAt(3));
}
}

Output:

Char At 3:l

Example of equals()
class Example_Equal
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Are Hello & hello equal :"+str.equals("hello"));
}
}
Output:
Are Hello & hello equal :false

Example of equalsIgnoreCase()

class Example_EqualIgnoreCase
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Are Hello & hello equal :"+str.equalsIgnoreCase("hello"));
}
}
Output:
Are Hello & hello equal : true

Example of Length()

class Example_Length

Prepared by: Meenakshi A.Thalor Page 21


Java Programming Notes CO5G
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Length : "+str.length());
}
}
Output:
Length:5

Example of replace()

class Example_Replace
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.prinitln("Replaced String:"+str.replace('H','C');
}
}
Output:
Replaced String:Cello

Example of compareTo()

class Example_CompareTo
{
public static void main(String args[])
{
String str=new String("Hello");
if(str.compareTo("hello")>0)
System.out.println("Hello is greater than hello");
else if(str.compareTo("hello")<0)
System.out.println("hello is greater than Hello");
else
System.out.println("Both are equal");
}
}

Output:
hello is greater than Hello

Example of concat()

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

Prepared by: Meenakshi A.Thalor Page 22


Java Programming Notes CO5G
{
String str=new String("Hello");
System.out.println("Concatenated String :"+str.concat(" Java"));
}
}

Output:

Concatenated String : Hello Java

Example of IndexOf()

class Example_IndexOf
{
public static void main(String args[])
{
String str=new String("Attitude");
System.out.println("Index Of 't' with 1 parameter: "+str.indexOf('t'));
System.out.println("Index Of 't' With 2 parameter :"+str.indexOf('t',3));
}
}

output:
Index Of 't' with 1 parameter:1
Index Of 't' With 2 parameter :4

Example of substring()

class Example_Substring
{
public static void main(String args[])
{
String str=new String("Hello");
System.out.println("Substring with 1 parameter :"+str.substring(2));
System.out.println("Substring with 2 parameter :"+str.substring(2,4));

}
}

output:

Substring with 1 parameter :llo


Substring with 2 parameter :ll

13. StringBuffer Class

Prepared by: Meenakshi A.Thalor Page 23


Java Programming Notes CO5G
Java provides the StringBuffer and String classes, and the String class is used to manipulate character
strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The
StringBuffer class is used to represent characters that can be modified.Following table shows the
difference between string and stringBufferClass

Sr. String class StringBuffer Class


No.
1 String class creates string of fixed length Stringbuffer class creates strings of variable
length
2 We can’t insert substring in middle of string We can insert substring in middle of string
using string methods using stringbuffer methods
3 Methods of String class: Methods of StringBufferClass:
toLowerCase() setcharAt()
toUppercase() append()
equals() insert()
equalsIgnoreCase() setLength()
substring() reverse()
indexOf()
concat()
4 Syntax: Sytax:
String str= new string(); StringBuffer str= new stringBuffer()

StringBuffer Constructors:

StringBuffer objects can be created using following StringBuffer constructors.

Constructor Description Example


StringBuffer() Creates empty StringBuffer object having StringBuffer stringBuffer = new
initial capacity of 16. StringBuffer();

StringBuffer(int Creates empty StringBuffer object having StringBuffer stringBuffer = new


capacity)
initial capacity specified. StringBuffer(50);
Here capacity is 50.
StringBuffer(String Creates new StringBuffer object having String str = “Hello”;
content) contents same as the argument string StringBuffer stringBuffer = new
object. The initial capacity of the StringBuffer(str);
newly created StringBuffer object will be Here, capacity of stringBuffer
the length of the argument string object + object would be 5 + 16 = 21.
16.

Prepared by: Meenakshi A.Thalor Page 24


Java Programming Notes CO5G
Methods of StringBuffer Class

Following tables shows the methods of StringBuffer class. Here s1 is object of sting class which is
invoking the built in methods of String class.

Sr. Method Description Syntax


No.
1 s1.setCharAt(n,’x’) Modify the nth character to x void setCharAt(int n,char ‘x’)
2 s1.append(s2) Append the sting s2 to s1 at the String append(String s2)
end
3 s1.insert(n,s2) Insert the string s2 at the position String insert(int n,String s2)
n of the string s1
4 s1.setLength(n) Set the length of string s1 to n.if void setLength(int n)
n<s1.length() s1 is truncated. If
n>s1.length zero are added to s1
5 s1.reverse() Reverse the string s1 String reverse()
6 s1.replace(n,m,s2) Replace the substring starting String replace(int n,int m,String s2)
from nth index upto mth-1 with
string s2

Example of setCharAt()

class Example_setCharAt
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object_Language");
str.setCharAt(6,' ');
System.out.println("String="+str);
}
}

Output:
String=Object Language

Example of append()
class Example_Append
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object Language");
System.out.println("AppendedString="+str.append(" is secure"));
}
}
Output: AppendedString= Object Language is secure

Example of Insert()

Prepared by: Meenakshi A.Thalor Page 25


Java Programming Notes CO5G
class Example_Insert
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object Language");
System.out.println("New String="+str.insert(7,"Oriented "));
}
}

Output:
New String=Object Oriented Language

Example of setLength()

class Example_setlength
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object");
System.out.println("Length="+str.length());
str.setLength(10);
System.out.println("Length="+str.length());
}
}
Output:
Length=6
Length=10

Example of Reverse()
class Example_reverse
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Hello");
System.out.println("String after reverse="+str.reverse());
}
}
Output:
String after reverse =olleH

Example of Replace()
class Example_replace
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Hello!!!");
System.out.println("String after replace="+str.replace(5,8,”***”));
}

Prepared by: Meenakshi A.Thalor Page 26


Java Programming Notes CO5G
}
Output:
String after replace=Hello***

14. Vector Class


The Vector class implements a growable array of objects. Like an array, it contains components that can
be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to
accommodate adding and removing items after the Vector has been created.

Vectors are implemented with an array, and when that array is full and an additional element is added,
a new array must be allocated. Because it takes time to create a bigger array and copy the elements from
the old array to the new array, it is a little faster to create a Vector with a size that it will commonly be
when full. Of course, if you knew the final size, you could simply use an array. However, for non-critical
sections of code programmers typically don't specify an initial size. You must import either import
java.util.Vector; or import java.util.*;Following table shows the difference between array and vector.

Sr. Array Vector


No.
1 Arrays can accommodate only fixed number of Vectors can accommodate unknown number of
elements. elements.
2 Arrays can hold primitive data types &objects. Vectors can hold only objects.
3 All the elements of the arrays are ofsame data The objects in the vectors may not be
type. Ie. Homogeneous elements. homogeneous, ie. They can be of different types.
4 Array is an ordered collection of elements. Vector is a class contained in java.util package.
5 Array does not provide any methods to add or Vector class provides elements to add or remove
remove elements. elements.
6 Datatype arrayname[] = new Vector objectname = new Vector();
datatype[size]; Or
Vector objectname=new Vector(size);

Constructors of Vector Class

Constructor Description Example


Vector() Creates a new empty vector with size Vector v = new Vector();
10 and capacity Increment 0.
Vector (int Creates a new empty vector with the Vector v = new Vector(100);
initialCapacity) specified initial capacity and with
capacity increment equal to 0.

Vector (Collection c) Creates a new vector containing Vector v = new


elements of the specified collection in Vector(myCollection);
the order returned by the Collection’s
Iterator.

Prepared by: Meenakshi A.Thalor Page 27


Java Programming Notes CO5G
Vector (int Creates a new empty vector with the Vector v = new Vector(100,20);
initialCapacity, int specified initial capacity and with
capacityIncrement) specified capacity increment.

Methods of Vector class

Sr. Method Description Syntax


No.
1 List.addElement(item) Add the item into the list at Vector addElement (Object item)
the end
2 List.elementAt(n) Gives the name of the nth String elementAt(int n)
(index)object
3 List.size() Gives the number of objects int size()
in vector
4 List.removeElement(item) Removes the specified item Vector removeElement(Object item)
from list
5 List.removeElementAt(n) Remove the item stored at nth Vector removeElementAt(Object item)
index of the vector
6 List.removeAllElements() Removes all elements of Vector removeAllElement(Object
vector item)
7 List.copyInto(array) Copies all items from vector Void copyInto(String array[])
to array of string type
8 List.insertElementAt(item,n) Insert item in to vector at nth Vector insertElementAt(object item,int
index. n)

Example1

import java.util.*;
class VectorDemo1
{
public static void main(String args[])
{
Vector v=new Vector();
int length=args.length;
for(int i=0;i<length;i++)
{
v.addElement(args[i]); //adding command line arguments
}
v.insertElementAt("COBOL",2);
Enumeration venum=v.elements();
System.out.println("Elements are");
while(venum.hasMoreElements())
System.out.println(venum.nextElement()+" ");

}
}

Prepared by: Meenakshi A.Thalor Page 28


Java Programming Notes CO5G
Execution steps:
C:\jdk\bin>Javac VectorDemo1.java
C:\jdk\bin>Java VectorDemo1 C C++ PASCAL
Elements are:
C
C++
COBOL
PASCAL

Example2:
import java.util.*;
class VectorDemo2
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Integer (10)); //Adding elements at the end of vector
v.addElement(new Float (10.75));
v.addElement(new Character('a'));
v.addElement(new String("Hello"));
v.addElement(new String("Welcome"));
v.removeElementAt(1); //removing 2nd object
if(v.contains(new Integer(10))); //searching for an object
System.out.println("Found the object");
System.out.println("First and Last element of vector are:");
System.out.println(v.firstElement()); //showing first object
System.out.println(v.lastElement()); //showing last object
System.out.println("Elements of vector are:");
Enumeration venum=v.elements(); //showing all objects
while(venum.hasMoreElements())
System.out.println(venum.nextElement()+" ");
}
}
Output:
Found the object
First and Last element of Vector are:
10
Welcome
Elements of vector are:
10
a
Hello
Welcome

Example3: Demonstrate capacity operations.


import java.util.*;
class VectorDemo
{

Prepared by: Meenakshi A.Thalor Page 29


Java Programming Notes CO5G
public static void main(String args[])
{
Vector v = new Vector(3, 5); // initial size is 3, increment is 2
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +v.capacity());
v.addElement(new Double(5.45));
System.out.println("Capacity after one additions: " +v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Capacity after two additions: " +v.capacity());
v.addElement(new Float(9.4));
System.out.println("Capacity after one additions: " +v.capacity());
v.addElement(new Integer(10));
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("Capacity after three additions: " +v.capacity());
// use an iterator to display contents
Iterator vItr = v.iterator();
System.out.println("Elements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next()+" ");
}
}
Output:

Initial size:0
Initial capacity:3
Capacity after four additions: 8
Capacity after one additions:8
Capacity after two additions:8
Capacity after one additions:8
Capacity after three additions:13
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12

Example 4: using copyInto method

import java.util.*;

Prepared by: Meenakshi A.Thalor Page 30


Java Programming Notes CO5G
class VectorDemo
{
public static void main(String args[])
{
Vector v = new Vector();
String s[]= new String[4];
v.addElement("1");
v.addElement("2");
v.addElement("3");
v.addElement("4");
v.copyInto(s);
for(int i=0;i<s.length;i++)
System.out.println(s[i]);

}
}

Output:
1
2
3
4

15. Wrapper Classes


The primitive data types are not objects; they do not belong to any class; they are defined in the language
itself. Sometimes, it is required to convert data types into objects in Java language. A data type is to be
converted into an object and then added to a Stack or Vector etc. For this conversion, the designers
introduced wrapper classes.
As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance.
Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods
to unwrap the object and give back the data type.

List of Wrapper classes

In the above code, Integer class is known as a wrapper class (because it wraps around int data type to
give it an impression of object). To wrap (or to convert) each primitive data type, there comes a wrapper
class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.

Data Types Wrapper classes


byte Byte
short Short
int Integer
long Long
float Float
double Double

Prepared by: Meenakshi A.Thalor Page 31


Java Programming Notes CO5G
char Character
boolean Boolean

Following is the hierarchy of the above classes.

The image part with relationship ID rId14 was not found in the file.

All the 8 wrapper classes are placed in java.lang package so that they are implicitly imported and made
available to the programmer. As you can observe in the above hierarchy, the super class of all numeric
wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper
classes are defined as final and thus designers prevented them from inheritance.

Importance of Wrapper classes


There are mainly four uses of wrapper classes.

1.Converting primitive numbers to objects

Integer iobj=new Integer(i) //conversion of primitive int(i) to integer object (iobj)


Float fobj=new float(f) //conversion of primitive float(f) to float object (fobj)
Double dobj=new Double(d) //conversion of primitive double(d) to double object (dobj)

2. Converting objects to primitive numbers

int i=iobj.intValue() //conversion of integer object (iobj) to primitive int(i)


float f=fobj.floatValue()//conversion of float object (fobj) to primitive float(f)
double d=dobj.doubleValue()//conversion of double object (dobj) to primitive double(d)

3.Converting Numbers to Strings

String s3 = Integer.toString(i); //conversion of primitive int(i) to String object


String s4 = Double.toString(d); //conversion of primitive double(i) to String object

Prepared by: Meenakshi A.Thalor Page 32


Java Programming Notes CO5G
String s4 = Float.toString(d); //conversion of primitive float(i) to String object

4.Converting Strings to Numbers

int i=Integer.parseInt(str)
double d=Double.parseDouble(str)

16. Enum Types


An enum type is a special data type that enables for a variable to be a set of predefined constants. The
variable must be equal to one of the values that have been predefined for it. Common examples include
compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because
they are constants, the names of an enum type's fields are in uppercase letters.In the Java programming
language, you define an enum type by using the enum keyword. Here is some code that shows you how to
define and use the enum.

public class Example


{
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY
}
Day day;

Example(Day day)
{
this.day = day;
}

public void test()


{
switch (day)
{
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;

Prepared by: Meenakshi A.Thalor Page 33


Java Programming Notes CO5G
}
}
public static void main(String[] args)
{
Example d1 = new Example(Day.MONDAY);
d1.test();
Example d2 = new Example(Day.WEDNESDAY);
d2.test();
Example d3 = new Example(Day.FRIDAY);
d3.test();
Example d4 = new Example(Day.SATURDAY);
d4.test();
}
}
The output is:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.

17. Inheritance
It is process of deriving a new class from derived class. A class that is derived from another class is called
a subclass (also a derived class, extended class, or child class). The class from which the subclass is
derived is called a superclass (also a base class or a parent class). When you want to create a new class
and there is already a class that includes some of the code that you want, you can derive your new class
from the existing class. In doing this, you can reuse the fields and methods of the existing class without
having to write them yourself.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors
are not members, so they are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
Single Level Inheritance

When there is one base class and one derived class the inheritance is called single level inheritance.
Following is the example of single level inheritance.

Person

name,age

Employee

designation,salary

Prepared by: Meenakshi A.Thalor Page 34


Java Programming Notes CO5G

class Person
{
String name;
int age;
Person(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
}
}
class Employee extends Person
{
String emp_designation;
float emp_salary;
Employee(String p,int q,String r,float s)
{
super(p,q);
emp_designation=r;
emp_salary=s;
}
void display1()
{
display();
System.out.println("Employee Designation="+emp_designation);
System.out.println("Employee Salary="+emp_salary);
}
public static void main(String args[])
{
Employee e=new Employee("Akshay",18,"Manager",25000);
e.display1();
}
}

Output:
Name= Akshay
Age=18
Employee Designation= Manager
Employee Salary=25000

18. Multilevel Inheritance

Prepared by: Meenakshi A.Thalor Page 35


Java Programming Notes CO5G
When a subclass is derived from a derived class then this mechanism is known as the multilevel
inheritance. In multilevel inheritance there are super class, intermediate super classes and
subclass as shown below Multilevel inheritance can go up to any number of level.

Account

cust_name,acc_no

Saving_acc

saving_bal,min_bal

Account_detail

Withdrawal,deposit

import java.io.*;

class Account
{
String cust_name;
int acc_no;
Account(String n,int no)
{
acc_no=no;
cust_name=n;
}
void display()
{
System.out.println(" Customer name = "+cust_name);
System.out.println(" Account number = "+acc_no);
}
}
class Saving_acc extends Account
{
int saving_bal;
int min_bal;
Saving_acc(String n,int no,int sbal,int mbal)
{
super(n,no);
saving_bal=sbal;
min_bal=mbal;

Prepared by: Meenakshi A.Thalor Page 36


Java Programming Notes CO5G
}
void output()
{
display();
System.out.println(" Saving balance ="+saving_bal);
System.out.println(" Minimum balance = "+ min_bal);
}
}
class Acc_detail extends Saving_acc
{
int deposit,withdrawal;
Acc_detail(String n,int no,int sbal,int mbal,int dep,int wd)
{
super(n,no,sbal,mbal);
deposit=dep;
withdrawal=wd;
}
void final_result()
{
output();
System.out.println(" Deposit amount= "+deposit);
System.out.println(" Withdrawal amount = "+ withdrawal);
}
}
class sample
{
public static void main(String args[])
{
Acc_detail a=new Acc_detail("ABC",1803,10000,500,1000,2000);
a.final_result();
}
}
Output:

Customer name = ABC


Account number = 1803
Saving balance =10000
Minimum balance =500
Deposit amount= 1000
Withdrawal amount=2000

19. Hierarchical Inheritance:

In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D.

Prepared by: Meenakshi A.Thalor Page 37


Java Programming Notes CO5G
The image part with relationship ID rId14 was not found in the file.

Examples:
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA()
obj1.methodB();
obj2.methodA()
obj2.methodC();

Prepared by: Meenakshi A.Thalor Page 38


Java Programming Notes CO5G
obj3.methodA()
obj3.methodD();
}
}
Output:
method of Class A
method of Class B
method of Class A
method of Class C
method of Class A
method of Class D

20. Method Overloading


When more methods are created having same name, but different declaration of parameter list with
different definition then the methods are said to be overloaded and the process is called method
overloading. Java supports polymorphism through method overloading-"one interface, multiple methods".

To create an overloaded method, provide different method definitions in a class, all with the same name,
but with the different parameter list. The difference may either be in the number or type of arguments,
that is each parameter list must be unique. The method's return type is not so much important as it does
not play any role in this.

when an overloaded method is called, Java first looks for a match between the arguments used to call the
method and the method's parameters.

Example

class person
{
String name;
int age;
void accept()
{
name="abc";
age=20;
}
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);

Prepared by: Meenakshi A.Thalor Page 39


Java Programming Notes CO5G
}
public static void main(String array[])
{
person p=new person();
p.accept();
p.display();
person p1=new person();
p1.accept("xyz",18);
p1.display();
}
}
Output:
Name: abc
Age=20
Name=xyz
Age=18

21. Constructor Overloading


Constructors can be overloaded. Constructors in a class have the same name as the class, but their
signatures are differentiated by their parameter lists.

Example: Contains two constructors which are overloaded.


Class Room
{
float length;
float breadth;
Room(float x,float y)
{
length=x;
breadth=y;
}
Room(float x)
{
length=breadth=x;
}
int area()
{
return(length*breadth);
}
public static void main(String array[])
{
Room r1=new Room(10,20);
System.out.println(“Area=” +R1.area());
Room r2=new Room(12)
System.out.println(“Area=” +R2.area());
}

Prepared by: Meenakshi A.Thalor Page 40


Java Programming Notes CO5G
}

Output:
Area=200
Area=144

22. Method Overridding


• In a class hierarchy, when a method in subclass has the same name and type signature as a
method in its superclass, then the method in subclass is said to override the method in the
superclass.
• The version of the method defined by the superclass will be hidden.
• A method defined in the superclass is inherited by its subclass and is used by the objects created
by subclass.
• Method inheritance enables to define and used methods repeatedly in subclasses without having
to define the method again in the subclass.
• Sometimes we wish an object to respond to the same method but have different behavior when
that method is called meaning that overrides the method defined is the superclass.
• The method defined in the subclass is invoked and executed instead of superclass method. This is
known as method overriding.

For eg: Demonstrates the concept of method overriding,the display() method is overridden.

class base
{
int a;
base(int a)
{
this.a=a;
}
void display() //method defined
{
System.out.println(“Base a=”+a);
}
}
class derived extends base
{
int y;
derived(int x,int y)
{
super(x);
this.y=y;

Prepared by: Meenakshi A.Thalor Page 41


Java Programming Notes CO5G
}
void display() //method defined again
{
super.display();
System.out.println(“Derived y=”+y);
}
public static void main(String args[])
{
derived s1=new derived(100,200);
s1.display();
}
}
Output:
Base a=100
Derived y=200

23. Dynamic Method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run
time, rather than compile time. Dynamic Method Dispatch is related to a principle that states that an super
class reference can store the reference of subclass object. However, it can't call any of the newly added
methods by the subclass but a call to an overridden methods results in calling a method of that object
whose reference is stored in the super class reference.It simply means that which method would be
executed, simply depends on the object reference stored in super class object.

import java.io.*;
class Demo
{
void display() //method defined
{
System.out.println("Printing from Demo class");
}
}
class Example extends Demo
{
void display() //method defined again
{

System.out.println("Printing from Example class");


}
public static void main(String args[])
{
Demo d=new Demo();
d.display();
Example e=new Example();
e.display();

Prepared by: Meenakshi A.Thalor Page 42


Java Programming Notes CO5G
d=e;
d.display();
}
}

Output:
Printing from Demo class
Printing from Example class
Printing from Example class

24. Final Keyword


In java final keyword can use for three purposes as given below:

1. Use final to declare symbolic constants

First, it can be used to create symbolic constants as shown below

final float PI=3.14f

2. Using final to Prevent Overriding

While method overriding is one of Java’s most powerful features, there will be times when you will want
to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at
the start of its declaration. Methods declared as final cannot be overridden. The following fragment
illustrates final:

class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() //Here error will occured
{
System.out.println("Illegal!");
}
}

Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time
error will result.

3. Using final to Prevent Inheritance

Prepared by: Meenakshi A.Thalor Page 43


Java Programming Notes CO5G
Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration
with final. Declaring a class as final implicitly declares all of its methods as final, too.

Here is an example of a final class:

final class A
{
// ...
}
class B extends A //this will create error
{
//….
}

As the comments imply, it is illegal for B to inherit A since A is declared as final.

25. Super Keyword:

In java super keyword is used for two purposes

• The first calls the superclass’ constructor or to pass values to base class constructor.
• The second is used to access a member of the superclass that has been hidden by a member of a
subclass.

A subclass can call a constructor method defined by its superclass by using following form of super:
super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must
always be the first statement executed inside a subclass’ constructor.

The second form of super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used. This usage has the following general form:

super.member

Here, member can be either a method or an instance variable.

This second form of super is most applicable to situations in which member names of a subclass hide
members by the same name in the superclass.

Following example is showing the use of super keyword for both purposes.

class base
{
int a;
base(int a)
{

Prepared by: Meenakshi A.Thalor Page 44


Java Programming Notes CO5G
this.a=a;
}
void display() //method defined
{
system.out.println(“super a=”+a);
}
}
class derived extends base
{
int y;
derived(int x,int y)
{
super(x); //call base class constructor
this.y=y;
}
void display()
{
super.display(); //accessing member of superclass
system.out.println(“super y=”+y);
}
public static void main(String args[])
{
derived s1=new derived(100,200);
s1.display();
}
}
26. Abstract Class and Methods
A final class prevents the extensions of class or restrict the inheritance while abstract class is opposite of
final class where it is necessary to create a sub class of abstract class.

Abstract class can have simple methods as well as abstract methods. Abstract methods are those methods
which are preceded by abstract keyword and user will declare them in abstract class the definition of
abstract method will be carried out in sub class.

Following table depicts the difference between class and abstract class

S.n. Class Abstract Class


1 Object of class can be created Object of abstract class cannot be created
2 It contains non abstract methods (methods with It can have abstract and non abstract methods.
their definitions )
3 Extension of class is not mandatory Extension of abstract class is compulsory
4 Declaration Declarion:
class classname abstract class classname
{ {

} }

Prepared by: Meenakshi A.Thalor Page 45


Java Programming Notes CO5G
Syntax:

abstract class classname


{
datatye variablename;
abstract returntype function_name(Parameter list);
returntype function_name(parameter list)
{
//body of function
}
}

Example:

abstract class Demo


{
int x;
void accept(int x1)
{
x=x1;
}
abstract void display();
}
class Sample extends Demo
{

public display()
{
System.out.println(“x=”+x);
}

public static void main(string args[])


{
Sample s=new Sample();
s.accept(10)
s.display();
}

}
Output:

x=10

27. Static data Member


Static data members are also called as class variables as it directly belongs to class rather than any object
or instance. A static member is common to all the objects and accessed without using any object. Single
copy of static data is exist in memory which is shared among object. Each and every object do the
updation on that single copy only.

Prepared by: Meenakshi A.Thalor Page 46


Java Programming Notes CO5G

Syntax:
static data_type variable_name;
Example:

class test
{
static int count;
void increase()
{
count++;
}
void display()
{
System.out.println("Count="+count);
}
public static void main(String array[])
{
test t1=new test();
t1.increase();
t1.display();
test t2=new test();
t2.increase();
t2.display();
}
}
Output:
Count=1
Count=2

28. Static Member function

One of commonly used static member function in java is main ().Static methods belong to entire class and
not a part of any objects of class. User can create a static function by precede the method definition with
static keyword. A static member function is invoked with class name rather than any object.

Synatx
static return_type function_name(argument list)

Example:

class Shape
{
static int length;
static int breath;
static double are;
static void area(int l)

Prepared by: Meenakshi A.Thalor Page 47


Java Programming Notes CO5G
{
length=breath=l;
are=length*breath;
System.out.println("Area of square:"+are);
}
static void area(int l1,int b1)
{
length=l1;
breath=b1;
are=length*breath;
System.out.println("Area of rectangle:"+are);
}
public static void main(String array[])
{
shape.area(9);
shape.area(9,5);
}
}

Output:
Area of square:81.0
Area of rectangle:45.0

Prepared by: Meenakshi A.Thalor Page 48

You might also like