Professional Documents
Culture Documents
Javappt 2
Javappt 2
Javappt 2
Method Overloading
I/O
String
Overloading Methods
• Constructors all have the same name.
• Methods are distinguished by their
• signature
• name
• number of arguments
• type of arguments
• position of arguments
• method overloading means, a class can also have multiple usual
methods with the same name.
Polymorphism
• Allows a single method or operator associated with different meaning
depending on the type of data passed to it.
• It can be realised through:
• Method Overloading
• Operator Overloading (Supported in C++, but not in Java)
• Defining the same method with different argument types (method
overloading) – polymorphism.
• The method body can have different logic depending on the data
type of arguments.
Demonstrate method overloading
class OverloadDemo { class Overload {
void test() { public static void main(String args[]) {
System.out.println("No parameters");} OverloadDemo ob = new OverloadDemo();
void test(int a) { double result;
System.out.println("a: " + a);} // call all versions of test()
void test(int a, int b) { ob.test();
System.out.println("a and b: " + a + " " + b);} ob.test(10);
double test(double a){ ob.test(10, 20);
System.out.println("double a: " + a); result = ob.test(123.25);
return a*a; System.out.println("Result of
} ob.test(123.25): " + result);
} }}
Demonstrate method overloading
class peri{
class Perimeter{
public static void main(String args[]){
int p;
int perimeter(int l,int b) { int res;
p=(l+b)*2; Perimeter pr=new Perimeter();
return p; res=pr.perimeter(10,20);
} System.out.println("Perimeter of Rectangle"+res);
int perimeter(int s) { res=pr.perimeter(10);
p=4*s;
return p; System.out.println("Perimeter of Square"+res);
res=pr.perimeter(10,20,30);
} System.out.println("Perimeter of Triangle"+res);
int perimeter(int s1,int s2,int s3) {
p=s1+s2+s3; }
return p; }
}
}
Overloading Constructors
class Box { Box(double len) {
double width; width = height = depth = len;}
double height; double volume() {
double depth; return width * height * depth;
Box(double w, double h, double d) { }}
width = w; class OverloadCons {
height = h; public static void main(String args[]) {
depth = d; Box mybox1 = new Box(10, 20, 15);
} Box mybox2 = new Box();
Box() { Box mycube = new Box(7);
width = -1; // use -1 to indicate double vol;
height = -1; // an uninitialized vol = mybox1.volume();
depth = -1; // box System.out.println("Volume of mybox1 is " +
} vol);
Overloading Constructors
vol = mybox2.volume(); The output produced by this program
System.out.println("Volume of is :
mybox2 is " + vol); Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
vol = mycube.volume(); Volume of mycube is 343.0
System.out.println("Volume of
cube is " + vol);
}
}
Using Objects as Parameters
class Test { class PassOb {
int a, b; public static void main(String args[]) {
Test(int i, int j) {a = I;b = j;} Test ob1 = new Test(100, 22);
// return true if o is equal to the invoking Test ob2 = new Test(100, 22);
object Test ob3 = new Test(-1, -1);
boolean equals(Test o) { System.out.println("ob1 == ob2: " +
if(o.a == a && o.b == b) return true; ob1.equals(ob2));
else return false; System.out.println("ob1 == ob3: " +
} ob1.equals(ob3));
} }}
Output
ob1 == ob2: true
ob1 == ob3: false
pass object to constructor Objects are passed by reference.
Box(Box ob) { class CallByRef {
width = ob.width;
height = ob.height; public static void main(String args[]) {
depth = ob.depth; Test ob = new Test(15, 20);
}
In main method you can write
System.out.println("ob.a and ob.b
Box mybox1 = new Box(10, 20, 15);
before call: “ +ob.a + " " + ob.b);
Box myclone = new Box(mybox1); ob.meth(ob);
System.out.println("ob.a and ob.b
Objects are passed by reference.
class Test {
after call: " +
int a, b; ob.a + " " + ob.b);
Test(int i, int j) {a = i;b = j;} }
void meth(Test o) {
o.a *= 2;o.b /= 2;}
}
Returning Objects
class Test { Test ob2;
int a; ob2 = ob1.incrByTen();
Test(int i) {a = i;} System.out.println("ob1.a: " + ob1.a);
Test incrByTen() { System.out.println("ob2.a: " + ob2.a);
Test temp = new Test(a+10); ob2 = ob2.incrByTen();
return temp; System.out.println("ob2.a after
}} second increase: "+ ob2.a);
class RetOb { }}
public static void main(String args[]) { //output
Test ob1 = new Test(2); ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Introducing Access Control
class Test { class AccessTest {
int a; // default access public static void main(String args[]) {
public int b; // public access Test ob = new Test();
private int c; // private access ob.a = 10;
void setc(int i) { c =i;} ob.b = 20;
int getc() { return c;} // ob.c = 100; // Error!
} ob.setc(100); // OK
System.out.println("a, b, and c: " +
ob.a + " " + ob.b + " " + ob.getc());}
}
Static members
• Java supports definition of global methods and variables that can be
accessed without creating objects of a class.
• Such members are called Static members.
• Define a variable by marking with the static methods.
• This feature is useful when we want to create a variable common to all
instances of a class.
• One of the most common example is to have a variable that could keep a
count of how many objects of a class have been created.
• Note: Java creates only one copy for a static variable which can be used
even if the class is never instantiated
Static members
class GetInput {
System.out.println("Enter a string");
s = in.nextLine();
}}
Scannerdemo1.java
import java.util.*;
public class scannerdemo1{
public static void main (String []args ) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter name");
String name = sc.nextLine();
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("enter gender");
char gender = sc.next().charAt(0);
System.out.println("name is"+name);
System.out.println("age ="+age);
System.out.println("gender ="+gender);
}
}
student.java
import java.util.*;
class student{
int rno,age,m1,m2,m3;
float max,average;
void accept() {
Scanner sc= new Scanner(System.in);
System.out.println("enter roll no.");
rno=sc.nextInt();
System.out.println("enter age");
age=sc.nextInt();
System.out.println("enter marks in 3 subjects");
m1=sc.nextInt();
m2=sc.nextInt();
m3=sc.nextInt();
}
student.java
void compute() {
average=(m1+m2+m3)/3;
int a=Math.max(m1,m2);
max=Math.max(a,m3);
}
void display() {
System.out.println("roll no."+rno);
System.out.println("age"+age);
System.out.println("m1"+m1);
System.out.println("m2"+m2);
System.out.println("m3"+m3);
System.out.println("average"+average);
System.out.println("maximum marks"+max);
}
student.java
public static void main(String args[]) {
int i
student obj[]=new student[3];
//student [] obj=new student[3];
for(i=0;i<3;i++)
{
obj[i]=new student();
}
for(i=0;i<3;i++)
{
obj[i].accept();
obj[i].compute();
obj[i].display();
}
}
String in Java
• String manipulation is the most common operation performed in Java programs.
• The easiest way to represent a String (a sequence of characters) is by using an array of
characters.
• Example:
char place[] = new char[4];
place[0] = ‘J’;
place[1] = ‘a‘;
place[2] = ‘v‘;
place[3] = ‘a‘;
• Although character arrays have the advantage of being able to query their length, they
themselves are too primitive and don‘t support a range of common string operations.
• For example, copying a string, searching for specific pattern etc.
• Recognizing the importance and common usage of String manipulation in large
software projects, Java supports String as one of the fundamental data type at the
language level. Strings related book keeping operations (e.g., end of string) are
handled automatically.
String Operations in Java
• Following are some useful classes that Java provides for String
operations.
• String Class
• StringBuffer Class
• StringTokenizer Class
String Class
• equals(s1)
• Returns true if this string is equal to string s1.
• equalsIgnoreCase(s1)
• Returns true if this string is equal to string s1; it is case insensitive.
• String replace(char oldChar, char newChar)
• Returns a new string with all instances of the oldChar replaced with newChar.
• public trim()
• Trims leading and trailing white spaces.
• public String toLowerCase()
• public String toUpperCase()
• Changes as specified.
String Class - example
class StringDemo {
public static void main(String[] args) {
String s = new String("Have a nice Day");
System.out.println("String Length = " + s.length() );
System.out.println("Modified String = " + s.replace('n', 'N'));
System.out.println("Converted to Uppercase = " + s.toUpperCase());
System.out.println("Converted to Lowercase = " + s.toLowerCase()); }}
String Length = 15
Modified String = Have a Nice Day
Converted to Uppercase = HAVE A NICE DAY
Converted to Lowercase = have a nice day
StringBuffer class
• Java StringBuffer class is used to created mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable
i.e. it can be changed.
• Constructors
• StringBuffer(): creates an empty string buffer with the initial capacity of 16.
• StringBuffer(String str): creates a string buffer with the specified string.
• StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
Important methods
• append(String s): is used to append the specified string with this
string.
• insert(int offset, String s): is used to insert the specified string with
this string at the specified position.
• replace(int startIndex, int endIndex, String str): is used to replace the
string from specified startIndex and endIndex.
• delete(int startIndex, int endIndex): is used to delete the string from
specified startIndex and endIndex.
• reverse(): is used to reverse the string.
methods of StringBuffer class
}
}