2 Overloading Methods and Constructors
2 Overloading Methods and Constructors
Constructors
Method Overloading
• Hint:
• Primitive types are passed by value
• Objects are passed as reference
Pass by value
// Primitive types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
Pass by reference
// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
String class
• Every string you create is actually an object of type
String. Even string constants are actually String
objects.
• The second thing to understand about strings is
that objects of type String are immutable; once a
String object is created, its contents cannot be
altered.
– If you need to change a string, you can always create a
new one that contains the modifications.
– Java defines a peer class of String, called StringBuffer,
which allows strings to be altered, so all of the normal
string manipulations are still available in Java.
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
Input from user
import java.util.Scanner;
public class userInput {
public static void main(String args[]) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}