What is Method Overloading?

Method Overloading:

One or more methods  in a class having same name, but different number or type of arguments, is called method overloading.

When a overloaded method is called, the method with matching number and type of arguments gets executed.

If there is no exact match of argument types, type promotion is applied, before invoking the method.

For eg

class Abc{

void add(int i, int j){  //body of method }

void add(float i, float j, float k){ //body of method }

void add(int i,int j, int k){ //body of method }

}

NOTE:

1.Method overloading cannot be done, based only on return type of the method

2.Method overloading is compile time polymorphism, as the method which need to get called is decided/binded during compile time itself.

Question:

Can below methods be overloaded??

class Abc{

void add(int i, int j){  //body of method }

int add(int a, int b){ //body of method }

}

Array as parameters

Hope you already gone thru basic of arrays.
An array can be sent as parameter to a constructor or a method. Also an array can be returned by a method.
Below example shows the same.


class Student{
	int marks[];
	
	Student(int m[])
	{
		marks = m;
	}
	
	private int getTotal(){
		int sum = 0;
		for(int i=0;i

Below is an example showing a method returning an array.

public class StudentProgram {
	public static void main(String arg[])
	{
		int gmp[] = getArray();
		
		for(int item:gmp)
		{
			System.out.println(item);
		}
	}
	
	
	private static int[] getArray()
	{
		int smp[] = {45,64,53,26};
		
		return smp;
	}
}

You may also like to read:
array example
how to sort an array in java

Package and interface example

Assignment Problem:
Create a class named Circle which can take radius as constructor parameter, and has methods which calculates and returns diameter, circumference and surface area. Write another class named MainCircle, which has main method, and creates an object of Circle, and invokes all methods of Circle class, and print the return values?

Solution:

package p2;

public interface ICircle {
public final float pi=3.14f;
   public float getDiameter();
   public float getcircumference();
   public  float getarea();    
}
package p1;
import p2.ICircle;
public class CircleImpl implements ICircle{
        float radius;
    public CircleImpl(float radius){
        this.radius=radius;
    }
    public float getDiameter(){
        float diameter=2*radius;
        System.out.println("The diameter is: "+diameter);
        return diameter;
    }
    public float getcircumference(){
        float circumference=2*pi*radius;
        System.out.println("The circumference is: "+circumference);
        return circumference;
    }
    public float getarea(){
        float area=pi*radius*radius;
        System.out.println("The area is: "+area);
        return area;
    }
}

Below is main method, which creates object of CircleImpl class, and invokes its methods

package p3;
import p1.CircleImpl;
public class MainCircle {
    public static void main(String[]args){
CircleImpl obj=new CircleImpl(3f);
obj.getDiameter();
obj.getcircumference();
obj.getarea();
    }
}

Click here to download this code, on Eclipse
You may also like to read:
What is a package
What are access specifiers

Object oriented Assignments

1. Create a class named Circle which can take radius as constructor parameter, and has methods which calculates and returns diameter, circumference and surface area. Write another class named MainCircle, which has main method, and creates an object of Circle, and invokes all methods of Circle class, and print the return values.

2. Create a class named Rectangle, which can take width and height as constructor parameters, and has methods which calculates and returns perimeter, area, diagonal length od rectangle. Also expose a method which returns false if square, else true. Write another class MainRectangle, which creates object of Rectangle, and invokes methods, and prints return values.

3. Repeat above problem 2, with Rectangle in package com.p1, and MainRectangle class in package com.p2. Explore by making constructor and methods of Rectangle, as default and public Access Specifier, and observe.

4. Create an interface ICircle, which declares a constant PI with 3.14 value, and declares methods which returns diameter, circumference and surface area. Write a class CircleImpl which implements ICircle, and defines all methods of ICircle. Write another class named MainCircle, which has main method, and creates an object of CircleImpl, and invokes all methods of Circle class, and print the return values.

5. Repeat problem 4, with ICircle interface in com.p1, CircleImpl in com.p2 and MainCircle in com.p3.

6. Write a program in Java that inputs a long sentence or paragraph from user into a String and then displays how many times each alphabet appears in that string. How many spaces, full stops and commas are there in the string? Assume upper and lower case letters as same like A and a are considered to be as same character. In the end calculate and display the percentages of occurrence of each character. Also display the total number of characters in the string.

7.Write a class RectCoor, which has constructor taking width and height of a rectangle as parameters. Expose a set method, to receive starting x and y coordinates of the rectangle.Expose three more get methods, which prints each of the three rest of the co ordinates.

8.Repeat above problem by having a different class to represent a single coordinate. set method need to take parmeter, and get emthods need to return object of coordinate class.

9.For a given number(say i), find the multiple of 5, which is just less than i, and which is just greater than i. For example, if the number is 23, then output should be 20 and 25

10.A student class, which has an array that stores, marks in 5 subjects. A student class also has student name, age, etc…Create 10 objects of such student class, with sample data. Store these 10 objects in an array. Provide methods to print student names in alphabetical ascending order. Compute avg marks of each student and print in ascending order of avg marks. Print the least mark scored by student. Display ranking order and student name, based on total marks.

11.Print two dimensional arrays, in column major order i..e print first column numbers, then second column,etc…
12.print two dimensional array elements diagonal wise, starting from left(consider no. of rows are same as number of columns)
13.print two dimensional array elements diagonal wise, starting from left
14.print maximum element of elements stored diagonally, in an array
15.Write a class, which has a constructor accepting int array as parameter, also declare an array as data member. Write methods to find total, avg, max, min of array, also method to return the array. From main method create an obejct of the class, and invoke the methods.
16.Write a program, to print total of each row elements, of a two dimensional arrays.
17.Program to find max and min element in a two dimensional array.
18.Write a program to find how many times each word occurs, in a sentence. At end of program print each word along with number of times it appears in the sentence.
19.Write a program, with a class, with a method which can take two arrays(say arr1 and arr2) as parameters, and creates and returns third array(say arr3) with the elements of two arrays, such that all even elements are from arr1, and odd elements from arr2. In case arr1 and arr2 are of different lengths, then remaining elements of any array need to be put in arr3.
For eg. arr1 is {23,21,45,38}, and arr2 is {49,93,96,66,53,86,54}. Then arr3 need to be {23,49,21,93,45,96,38,66,53,86,54}

20.Write program to convert String to a InputStream

21.Write a program with two threads, initialize a String. Each thread need to display exactly one character in the String, and then goes to wait() after notifying second thread by invoking notify(). After second thread prints one character, it goes to wait(), after notifying First thread. This is done until all characters in the String are printed.

22.(a) Write a program to extend an interface.
(b) Can Generics be used with an interface? Can you give examples of in built interfaces using Generics, like Comparator,etc…

23.Create a jar file, which has a class exposing add, sub, mul, div methods. Create a project, to which add the above jar file. Create a class with the main method, load the class, which is in jar file. Now invoke the methods add, sub, mul and div classes.

24.Combine 4 input streams, into a single input stream, read data from combined input stream, and write to a file, while writing to a file ignore the words mango.

25.Develop a command line zip tool, which compresses all the files and folders in a specific path.
usage: myzip -p path -e .txt
path can be absolute or relative path
.txt is the extension of files which need to be zipped, remaining files with other extensions will not be included in zip file. Also assume that there is no possibility, to specify multiple extensions

if -e is not provided, then all files and folders in the specified path are zipped

26.Implement Download manager, to download a file.
mydm -d url_of_file -p dest_path
-d: url of file which need to be downloaded
-p: specify local path to where file need to be downloaded
Display error, if no network, or if url provided is not valid

It should be to Pause or Resume download.

27.Create Shape class, which exposes draw() method. Create the sub classes Rect, Square, Circle, which are sub classes of Shape. From the main method, create objects of different sub classes, which are referred by Shape class reference. Observe overriding of methods.

28. Write a program to print a String “abcdef” in below format
(i) fedcba

(ii) a
ab
abc
abcd
abcde
abcdef

(iii)a
b
c
d
e
f

(iV) a
b
c
d
e
f

(V)a f

b e

cd

29.Please create a Message Queue, and Four Threads, A, B, C and D. Thread A puts a string into Message Queue, and invokes Threads B,C and D. Thread B reads from Message Queue and displays to console, Thread C reads from Message Queue and displays reverse of actual String, Thread D reads from Message Queue, sorts each character of String, and displays. Hint: use wait() and notifyAll() methods.

30.Develop a Program, for a singleton, which is synchronized.

31.Write a Program, which computes an expression like 2+3*8/56-12
Hint: use Stack in Collection, to compute expressions

32.Display a swing window, and display a String, by blinking periodically, and display String in Random color, each time.

33.Develop MySequenceInputStream which extends from java.io.SequenceInputStream. MySequenceInputStream need to provide below functionality, should allow to combine multiple InpuStreams into a single InputStream, and it should be possible to specify a String which should occur between each InputStreams, which are being combined into a single InputStream.

34.Write program to find if a given year is leap year?

35.A rectangular iron sheet with width 20, and height 15, need to be cut into small rectangular sheets of width 6 and height 7.5. How many pieces can be made, and what is the wastage. Write a program, which can take different dimensions, and prints the number of small rectangle sheets, which can be cut from big rectangular sheet?

Core java assignments
Core Java Assignments 2
Applets and Swings Assignments

What is static import? What are advantages and disadvantages of static import?

By static importing a class, all static members in that class can be directly used. This avoids using class name for each and every static member. Also, note that even pre defined classes like System,etc… can be static imported.

static import was introduced in Java 1.5 version
Below is an example of static import. As shown in below example, Test is a class in com.p1 package, and Test class has few static members.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
		return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
		return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
		return PI*Math.pow(radius, 2);
	}
	
}

In below code snippet, since com.p1.Test.* is imported using static, it is possible to use static members of com.p1.Test class directly, without using class name.

package com.p2;

import static com.p1.Test.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
	}
}

Can we use multiple static import

Yes, we can use multiple static import statement in a java file. How ever, ensure that there is no ambiguity in the static members of static imported classes.

package com.p1;

public class Test {
	public static float PI = 3.14f;
	
	public static double getDiameter(double radius)
	{
	return radius/2;
	}
	
	public static double getCircumference(double radius)
	{
	return 2*PI*radius;
	}
	
	public static double getSurfaceArea(double radius)
	{
	return PI*Math.pow(radius, 2);
	}
	
	public static void display()
	{
	System.out.println("display() in com.p1.Test");
	}
}

package com.p3;

public class Abc {
	public static void display()
	{
	System.out.println("display() in com.p3.Abc");
	}
}

package com.p2;

import static com.p1.Test.*;
import static com.p3.Abc.*;

public class SIDemo {
	public static void main(String args[])
	{
	double diameter = getDiameter(5.68);
		
	System.out.println("Diameter is: "+diameter);
		
	double s_area = getSurfaceArea(3.86);
		
	System.out.println("Surface Area is: "+s_area);
		
	System.out.println("PI value considered is:"+PI);
		
	//below method call causes compiler error, as display() method
	//is available in both the classes, com.p1.Test and com.p3.Abc
	//display();
	}
}

Disadvantages of static import

Below are disadvantages of static import
1.This may arise readability issues.
2.It may also cause ambiguity, when same member is declared in more than one static imported classes.

You may also like to read:
What is use of static members
Can we have more than one static block
Role of static method in abstract class
how to use packages in Java

Can a method parameter be final?

Hope you had already gone below usages of final keyword
1. final keyword with a class
2. final keyword with a method

As shown in below example it is possible to use final keyword for a parameter passed to a method.
Purpose of final keyword to a parameter is, the final object or primitive data type cannot be directly assigned to any other value, in the method body.

However, instance members of the class can be indirectly as shown in below example.

class MyTest{
	int i;
        public void setI(int x)
        {
        i = x;
        }
}

public class FinalParameter {
public static void main(String args[])
{
MyTest obj1 = new MyTest();
obj1.i = 10;
System.out.println("before invoking check():"+obj1.i);
check(obj1);
System.out.println("after invoking check():"+obj1.i);
}
	
static void check(final MyTest obj)
{
//Below line produces Compile error, as obj is final
//obj = new MyTest();

//But below line is valid, as we are not changing the object
//rather we are just changing value of a instance variable
obj.i = 20;

//above value can also be changed by invoking the setI(int x) method
}
}
Output:
before invoking check():10
after invoking check():20

You may also like to read:

Can a constructor be final?
constants in Java
How to inherit from String class

Difference between a Reference and an object, in Java

class Tuv{
	int a, b;
}

public class ReferenceDemo {
	public static void main(String args[])
	{
	Tuv obj/*name of reference*/ = new Tuv()/*creating object*/;
	//obj is the reference to Tuv object
		
	Tuv a_obj = obj;
	//creating another reference, and assigning to an existing object
		
	Tuv b_obj;//created reference, and not the object
		
	new Tuv().a = 50;//anonymous object, can be used only once
	//anonymous object does not have reference
		
	obj.a = 10;
	obj.b = 20;
		
	System.out.println("Before invoking check():"+obj.a+" "+obj.b);
		
	check(obj);
		
	System.out.println("After invoking check():"+obj.a+" "+obj.b);
	}
	
	static void check(Tuv tmp)
	{
	System.out.println("in check(), b4 changing:"+tmp.a+" "+tmp.b);
		
	tmp.a = 40;
	tmp.b = 50;
		
	System.out.println("in check(), after changing:"+tmp.a+" "+tmp.b);
	}
}

purpose of static members

A member of a class may be delcared as static.

A static member, is associated with the class(in which it is delcared), and not with the indidvidual objects.
Since static members are associated with class, they can be directly accessed with class name.
static members can be accessed, even before creation of object of the class.

A data members declared as static has common storage and value for the class, i..e for all objects of the class.

From a non static method both static and non static data members and member methods can be used or invoked.
Where as from static method only static members can be used or invoked. So, to invoke non static methods, from a static method, we need to create object of class, whose method need to be invoked.

this keyword cannot be used in static methods, as both of them contradict. static is unrelated to object, where as this refers to current object.

static example

//Example of static keyword
class Abcd
{
	static public int i;
	//i value is common to all object of Abcd
	//static members are associated with class, and not with object

	int j;
	//each object of Abcd, can have different value of j


	public int getI()
	{
	return i;
	}

	public int getJ()
	{
	stTest();
	return j;
	}

	//static data members/methods can be used in non static methods
	//but a static method can refer only static methods or data members
	public static void stTest()
	{

	System.out.println("This is static method");
	//j = 10; //error, only static variables can be referenced
	}
}

public class StaticExample {

	float met1()
	{
	return 0.0f;
	}

	public static void main(String args[])
	{
	Abcd.i = 50;

	//Abcd.j = 20;
	//Compile error, j cannot be accessed directly with class name
	//because j is non static

	StaticExample se = new StaticExample();
	se.met1();

	Abcd.stTest();

	Abcd obj = new Abcd();
	//obj.j = 34;
	//obj.i = 20;

	System.out.println("Abcd.i is "+Abcd.i);
	System.out.println("obj.j is "+obj.j);
	}
}

You may also like to read:
this keyword
How to declare static block
Are static constructors possible?
purpose of static method in abstract class

Access Specifier and Scope

Below are Access Specifiers supported in Java.
1. private
2. public
3. protected
4. default or none

private, public, protected are Access specifiers, which can be used only for members(data members and member methods) of a class.

private members can be accessed only within the class.

public members can be accessed with the class, other classes in current package, classes in other package.

protected members can be accessed within the class, and in the immediate derived class.

members with no access specifiers can be accessed within the class, and other classes only within current package.

Lifetime of variables

Lifetime of a variable, depends on the place where it has been declared.

Life time of Data members or instance variables is same as the object, in which they exist. An object is destroyed by garbage collector Java when there are no more reference to that object.

Local Variables:
Local variables are the variables declared in the method body. Local variable are available within method body until method returns.

Arguments or Parameters:
Arguments or Parameters are passed to constructor or methods, and are available until the constructor or method returns.

Also variables can be declared in a block(Eg. if, else block,etc…), within a method. Such variables are available only within the block where they have been declared.

Below is an example code snippet:

class Test1
{
	int i,j; //data members or member variables or instance variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j; //l is local variable
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
//obj is local object
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
purpose of static block
what is for each loop, in java

What is a class, in Java?

Basics of Object Oriented Concepts.
A class is basic unit of Object Oriented Languages, and hence in Java.
A class can have or a class encapsulates
1.Data Members or properties or fields
2.Constructors
3.Member Methods or Methods

What are properties, of a class

Data members or Properties is the data required by the member methods, to operate. Data members is one of the way, in which constructors and methods of a class, can share data. A class can have zero or more properties. A property can be of primitive type or user defined type.

What are methods, of a class

Methods is the behavior exposed by this class to external world, using which objects or other classes can interact with this class. A class can have zero or more methods.

What is object, in Java?

An object is an instance of a class. And the process of creating an object, from a class, is called instantiation.

Difference between class and object

To compare, class and object with real world scenarios, a class is just like a bottle moulder, which moulds bottles into a shape. And an object is just like a bottle, which got moulded from moulder.

Just like a moulder can mould any number of bottles, a class can generally have any number of objects, except in special cases, like singleton

What is Constructor, in Java?

A Constructor is a special method, of a class, used to initialize an object.

Below is an example of a class, creating object of a class, and invoking methods of class.

class Test1
{
	int i,j; //data members or member variables

	Test1()//constructor
	{
	i = 20;
	j = 11;

	System.out.println("Test1() Constructor");
	}

	void add() //member methods
	{
	int k; //local variable i..e not a member variable of Test1 class
	//NOTE: k cannot be accessed from object of Test1 class
	k = i+j;
	System.out.println("Add Result is:"+k);
	}

	void sub()
	{
	int l = i-j;
	System.out.println("Sub Result is:"+l);
	}
}

public class ClassDemo {
//execution starts from here
public static void main(String args[])
{
	Test1 obj; //declaring object reference
	obj=new Test1(); //creating object of Test1 class
	obj.add(); //invoking add() method of Test1 class, using object obj

	obj.sub();
}
}

You may also like to read:
invoke constructor from another constructor
what is abstract keyword