Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Problem Description:
How to overload methods ?
Solution:
This example displays the way of overloading a method depending on type and number of
parameters.
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is "
+ i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height
+ " feet tall");
}
void info(String s) {
System.out.println(s + ": House is "
+ height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");
//Overloaded constructor:
new MyClass();
}
}
Result:
The above code sample will produce the following result.
Building new House that is 0 feet tall.
House is 0 feet tall.
Overloaded method: House is 0 feet tall.
bricks
Problem Description:
How to use method overloading for printing different types of array ?
Solution:
This example displays the way of using overloaded method for printing types of array (integer,
double and character).
public class MainClass {
public static void printArray(Integer[] inputArray) {
for (Integer element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Double[] inputArray) {
for (Double element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void printArray(Character[] inputArray) {
for (Character element : inputArray){
System.out.printf("%s ", element);
System.out.println();
}
}
public static void main(String args[]) {
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4,
5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println("Array integerArray contains:");
printArray(integerArray);
System.out.println("\nArray doubleArray contains:");
printArray(doubleArray);
System.out.println("\nArray characterArray contains:");
printArray(characterArray);
}
}
Result:
The above code sample will produce the following result.
Array integerArray contains:
1
2
3
4
5
6
Array doubleArray contains:
1.1
2.2
3.3
4.4
5.5
6.6
7.7
Array characterArray contains:
H
E
L
L
O
Problem Description:
How to use method for solving Tower of Hanoi problem?
Solution:
This example displays the way of using method for solving Tower of Hanoi problem( for 3
disks).
public class MainClass {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from,
char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from "
+ from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk "
+ topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
Result:
The above code sample will produce the following result.
Disk
Disk
Disk
Disk
Disk
Disk
Disk
1
2
1
3
1
2
1
from
from
from
from
from
from
from
A
A
C
A
B
B
A
to
to
to
to
to
to
to
C
B
B
C
A
C
C
Problem Description:
How to use method for calculating Fibonacci series?
Solution:
This example shows the way of using method for calculating Fibonacci Series upto n numbers.
public class MainClass {
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n",
counter, fibonacci(counter));
}
}
}
Result:
The above code sample will produce the following result.
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
Fibonacci
of
of
of
of
of
of
of
of
of
of
0
1
2
3
4
5
6
7
8
9
is:
is:
is:
is:
is:
is:
is:
is:
is:
is:
0
1
1
2
3
5
8
13
21
34
Fibonacci of 10 is: 55
Problem Description:
How to use method for calculating Factorial of a number?
Solution:
This example shows the way of using method for calculating Factorial of 9(nine) numbers.
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
Result:
The above code sample will produce the following result.
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
Problem Description:
How to use method overriding in Inheritance for subclasses ?
Solution:
This example demonstrates the way of method overriding by subclasses with different number
and type of parameters.
public class Findareas{
public static void main (String []agrs){
Figure f= new Figure(10 , 10);
Rectangle r= new Rectangle(9 , 5);
Figure figref;
figref=f;
System.out.println("Area is :"+figref.area());
figref=r;
System.out.println("Area is :"+figref.area());
}
}
class Figure{
double dim1;
double dim2;
Figure(double a , double b) {
dim1=a;
dim2=b;
}
Double area() {
System.out.println("Inside area for figure.");
return(dim1*dim2);
}
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a ,b);
}
Double area() {
System.out.println("Inside area for rectangle.");
return(dim1*dim2);
}
}
Result:
The above code sample will produce the following result.
Inside area for figure.
Area is :100.0
Inside area for rectangle.
Area is :45.0
Problem Description:
How to display Object class using instanceOf keyword?
Solution:
This example makes displayObjectClass() method to display the Class of the Object that is
passed in this method as an argument.
import java.util.ArrayList;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Object testObject = new ArrayList();
displayObjectClass(testObject);
}
public static void displayObjectClass(Object o) {
if (o instanceof Vector)
System.out.println("Object was an instance
of the class java.util.Vector");
else if (o instanceof ArrayList)
System.out.println("Object was an instance of
the class java.util.ArrayList");
else
System.out.println("Object was an instance of the "
+ o.getClass());
}
}
Result:
The above code sample will produce the following result.
Object was an instance of the class java.util.ArrayList
Problem Description:
How to use break to jump out of a loop in a method?
Solution:
This example uses the 'break' to jump out of the loop.
public class Main {
public static void main(String[] args) {
int[] intary = { 99,12,22,34,45,67,5678,8990 };
int no = 5678;
int i = 0;
boolean found = false;
for ( ; i < intary.length; i++) {
if (intary[i] == no) {
found = true;
break;
}
}
if (found) {
System.out.println("Found the no: " + no
+ " at index: " + i);
}
else {
System.out.println(no + "not found in the array");
}
}
}
Result:
The above code sample will produce the following result.
Found the no: 5678 at
index: 6
Problem Description:
How to use continue in a method?
Solution:
This example uses continue statement to jump out of a loop in a method.
public class Main {
public static void main(String[] args) {
StringBuffer searchstr = new StringBuffer(
"hello how are you. ");
int length = searchstr.length();
int count = 0;
for (int i = 0; i < length; i++) {
if (searchstr.charAt(i) != 'h')
continue;
count++;
searchstr.setCharAt(i, 'h');
}
System.out.println("Found " + count
+ " h's in the string.");
System.out.println(searchstr);
}
}
Result:
The above code sample will produce the following result.
Found 2 h's in the string.
hello how are you.
Problem Description:
How to use method overloading for printing different types of array ?
Solution:
This example shows how to jump to a particular label when break or continue statements occour
in a loop.
public class Main {
public static void main(String[] args) {
String strSearch = "This is the string in which you
have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl:
for (int i = 0; i < = max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("Found the substring .");
}
else {
System.out.println("did not find the
substing in the string.");
}
}
}
Result:
The above code sample will produce the following result.
Found the substring .
Problem Description:
How to use enum & switch statement ?
Solution:
This example displays how to check which enum member is selected using Switch statements.
enum Car {
lamborghini,tata,audi,fiat,honda
}
public class Main {
public static void main(String args[]){
Car c;
c = Car.tata;
switch(c) {
case lamborghini:
System.out.println("You choose lamborghini!");
break;
case tata:
System.out.println("You choose tata!");
break;
case audi:
System.out.println("You choose audi!");
break;
case fiat:
System.out.println("You choose fiat!");
break;
case honda:
System.out.println("You choose honda!");
break;
default:
System.out.println("I don't know your car.");
break;
}
}
}
Result:
The above code sample will produce the following result.
You choose tata!
Problem Description:
How to use enum constructor, instance variable & method?
Solution:
This example initializes enum using a costructor & getPrice() method & display values of
enums.
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println(c + " costs "
+ c.getPrice() + " thousand dollars.");
}
}
Result:
The above code sample will produce the following result.
All car prices:
lamborghini costs 900 thousand dollars.
tata costs 2 thousand dollars.
audi costs 50 thousand dollars.
fiat costs 15 thousand dollars.
honda costs 12 thousand dollars.
Problem Description:
How to use for and foreach loops to display elements of an array.
Solution:
This example displays an integer array using for loop & foreach loops.
public class Main {
public static void main(String[] args) {
int[] intary = { 1,2,3,4};
forDisplay(intary);
foreachDisplay(intary);
}
public static void forDisplay(int[] a){
System.out.println("Display an array using for loop");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void foreachDisplay(int[] data){
System.out.println("Display an array using for
each loop");
for (int a : data) {
System.out.print(a+ " ");
}
}
}
Result:
The above code sample will produce the following result.
Display an array using for loop
1 2 3 4
Display an array using for each loop
1 2 3 4
Problem Description:
How to make a method take variable lentgth argument as an input?
Solution:
This example creates sumvarargs() method which takes variable no of int numbers as an
argument and returns the sum of these arguments as an output.
public class Main {
static int sumvarargs(int... intArrays){
int sum, i;
sum=0;
for(i=0; i< intArrays.length; i++) {
sum += intArrays[i];
}
return(sum);
}
public static void main(String args[]){
int sum=0;
sum = sumvarargs(new int[]{10,12,33});
System.out.println("The sum of the numbers is: " + sum);
}
}
Result:
The above code sample will produce the following result.
The sum of the numbers is: 55
Problem Description:
How to use variable arguments as an input when dealing with method overloading?
Solution:
This example displays how to overload methods which have variable arguments as an input.
public class Main {
static void vaTest(int ... no) {
System.out.print("vaTest(int ...): "
+ "Number of args: " + no.length +" Contents: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
static void vaTest(boolean ... bl) {
System.out.print("vaTest(boolean ...) " +
"Number of args: " + bl.length + " Contents: ");
for(boolean b : bl)
System.out.print(b + " ");
System.out.println();
}
static void vaTest(String msg, int ... no) {
System.out.print("vaTest(String, int ...): " +
msg +"no. of arguments: "+ no.length +" Contents: ");
for(int n : no)
System.out.print(n + " ");
System.out.println();
}
public static void main(String args[]){
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}
Result:
The above code sample will produce the following result.
vaTest(int ...): Number of args: 3 Contents: 1 2 3
vaTest(String, int ...): Testing: no. of arguments: 2
Contents: 10 20
vaTest(boolean ...) Number of args: 3 Contents:
true false false