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 System.exit and assert, in Java

System.exit(int) is a method in java.lang package, where as assert is a keyword.

assert is used for debugging purpose, and assert to work, explicit enabling is required by providing -ea JVM argument. When assert expression gets evaluated to false, AssertionError exception is thrown.

For System.exit() to execute, no such explicit enabling is required. When System.exit() is executed, program terminates by providing exit code to Operating System.

Below is declaration of System.exit() method

public static void exit(int status_code);

System.exit() is generally used with below arguments
System.exit(0) – indicates that java program terminated normally
System.exit(1) – indicates that java program terminated abnormally
System.exit(-1)- indicates that java program terminated abnormally

Below is an example for System.exit()

public class SystemExitDemo {
public static void main(String args[])
{
try{
	String str="2sdjhfgsdjhfgsdjh3";

	int i = Integer.parseInt(str);

	}catch(Exception e)
	{
	e.printStackTrace();
	System.exit(1);//abnormal termination
	}
	System.exit(0);//normal termination
	}
}

You may also like to read:
What are data Wrapper classes in Java?
What is non static block, when to use it?
How to use assert
Purpose of System.getProperty() method

Purpose of a package, in Java

What is a package?

A Package is set of Classes, interfaces or sub packages.

Advantage of package

Below are advantages of packages
1. To avoid name collisions between classes or interfaces. Using different packages it is possible to have Classes or interfaces with same name.
2. Improves Modularity of Applications. As application development, is done across various Teams spread across various organizations, it is advantage to have each software module or layer in a package, and each sub module may further have sub package.
3. Another advantage of packages is, packages provides one more level of accessibility. Class members or classes with default or no access specifier, are accessible only within, current package.

All public classes and interfaces can be accessed by other packages also.
All classes and interfaces with default or none access specifier, can be accessed only within current package.

Below is diagram showing two packages com.java652 and com.p1. The package com.java652 has two classes WeatherDetails and CityDetails. The package com.p1 has one class StateDetails and an interface. objects of classes in different packages interact with each other, to perform required functionality.

What is Java Package
Java Package

Keywords used for packages





Below are keywords used in packages
1. package
package keyword is used to specify to which package, current java source file belongs to. There can be only package statement in a file. package statement need to be first statement in the file.
2. import
import keyword is used to specify that classes or interfaces of other packages need to be used in current java file. There can be multiple import statements, in a single file.

Also note that a separate folder is created with package name as folder name. And all class and interface files belonging to this package, are in this folder.

Download Package example(Eclipse Project)

For each sub package, one sub folder is created, under the main folder.

How to create package

how to create package, manually

When you develop java project using command line, and simple text editor, you need to manually create the package.
That means you need to manually create folders, and sub folders, for packages and sub packages, accordingly. Place java source file in corresponding folders or sub folders.

How to create package on Eclipse

As shown in below picture,
Right click on project, for which you want to create a package.
Now select New, then select package, then fill the package name like com.java652
To create class in this package, right click on package, select New, then select Class, then fill the class name.

how to create package in eclipse
how to create package in eclipse

How to create package on Netbeans

As shown in below picture,
Right click on project, for which you want to create a package.
Now select New, then select Java Package, then fill package name
To create class in this package, right click on package, select New, then select class.

how to create package in netbeans
how to create package in netbeans

you may also like to read:
How many Access specifiers in Java?
Can a abstract class have static method

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

operators in Java

Below are Operators supported, in Java

Arithmetic operators

+(addition), -(subtraction), *(multiplication), /(dividedby), %(Modulo – reminder of division)
++(increment) x++; means x = x+1;
–(decrement)

Difference between Pre increment and Post increment

Post increment
x++;
For eg, consider System.out.println(x++);
In above statement, first x is printed, and after that x is incremented

Pre increment
++x;
For eg, consider System.out.println(++x);
In above statement, first x is incremented, and after that x is printed

Similarly, pre and post increment can be used in other arithmetic expressions.

Difference between Pre decrement and Post decrement

Pre decrement and post decrement operator as well, can be used in arithmetic expressions.

Relational Operators or Comparison Operators

Relational or Comparison operators are used to perform comparison check between two variables or constants
x<3 (less than) > (greater than)
<= (less than or equal to) >= (greater than or equal to)
==( checking equal to),
!=(not equal to)

Generally Relational or Comparison expression evaluates to true or false.
Relational or Comparison operators are used with if, loops

Logical Operators

Logical operators are used two combine two or more Relational or Comparison expressions.
&&(Logical and): evaluates to true only if both operands are true
Eg.(y==3)&&(z>20)

||(Logical or): evaluates to true, when either of the operand is true

!(Logical not): Negates logical expression, converts true to false, and vice versa

logical or and not takes two operands, where as logical not takes one operand

Assignment Operators

=, +=(short hand assignment)
-=, *=, /=, %=
x op= y means x=x op y;
For eg. x+=y means x=x+y;
X*=y; means x =x*y;

Conditional Operator or Ternary Operator

?:

Conditional operator takes three arguments
usage:
relational_expression? expression_1 : expression_2;

If relational expression gets evaluated to true, expression_1 is returned, else expression_2 is returned.

Eg. b = (a == 15) ? 21 : 52;
As shown in above example, if value of a is 15, 21 is assigned to b, else 52 is assigned to b

Bitwise Operator

Bitwise operators perform operations on each binary representation
& – bitwise AND
| – bitwise OR
^ – bitwise XOR
<< - bit wise left shift >> – bit wise right shift

16 & 8
0010000(binary representation of 16)
0001000(binary representation of 8)
Result: 00000000

instanceof operator

instanceof example

We cannot overload operators in Java.How ever few operators like + has builtin overloading.

You may also like to read:
Basic data types in Java

static method in Abstract class

Can a static method be a member of Abstract Class?

Read here for What is a abstract method? and what is abstract class?

static method is associated with class and not with individual objects of the class.

Yes, an abstract class can have static methods. But a static method cannot be abstract.

Also remember that, static methods take part in inheritance.
But static methods do not take part in polymorphism.

Below example shows that an abstract class, can have static method.


abstract class Abs1{
	int i,j;
	Abs1(){
		super();
		System.out.println("Abs1() Constructor");
	}

	Abs1(int i, int j)
	{
		this();
		this.i = i;
		this.j = j;
		System.out.println("Abs1(int i, int j) Constructor");
	}

	public static void met1()
	{
		System.out.println("met1() method in Abs1 class");
	}
}

public class AbstractDemo extends Abs1{

	AbstractDemo(){
		System.out.println("AbstractDemo() Constructor");
	}
	public static void main(String args[])
	{
		AbstractDemo obj = new AbstractDemo();
		System.out.println("in main() method");

		Abs1.met1();
	}
}

You may also like to read:
Difference between static and non static block
how many keywords or reserved words in java
purpose of static inner class

What are loops in Java

A loop is required to run set of statement(s) repeatedly, for certain number of times.

There are three loops in Java. They are
1. for loop
2. while loop
3. do while loop

How to use for loop in Java

Below is syntax of for loop

for(initialization;condition;expression)
{
	//program statements
}

In initialization single or multiple variables(separated by comma) can be declared or initialized.
Initialization part gets executed only once when execution of for loop starts.
Condition can be simple condition(using relational operators) or complex condition(having relational and logical operators),
Condition part executes once, before starting execution of each iteration.Iteration is continued only if the condition part evaluates to true, else execution comes out of the for loop.
Expression part executes once, after each iteration. Expression part can have multiple statements separated by comma.

Below are few valid for statements

for(int i=0;i<10;i++)
{
//statements(s)
}

for(int i=0,j=10;(i<10)&&(j>0);i++,j--)
{
//statement(s)
}

//infinite for loop
for(;;)
{
//statement(s)
}

There may be other logic problems which may end up with infinite for loop, as shown below
for(int i=0;i>0;i++)//infinite for loop
{
//statement(s)
}

Below for loop is syntactically right, but logically may not produce expected output

int i;
for(i=0;i<20;i++);//here ; does not give compile error
{
//statement(s)
}

Nested for loops Examples

Program to print Fibonacci numbers
sorting example
How to calculate factorial in Java?
print a pattern using for loop

what is for-each loop in Java

for-each has been added in Java version 5. It provides better readable syntax to iterate through individual elements in Array or in any Collection. Below is an example of for-each

class TestForEach{
  public static void main(String args[]){
   float arr[] = {14.5f,61.23f,43.5f,34.4f,12.23f};

   for(int item:arr){
     System.out.println(item);
   }
 }
}

Difference between while and for loop

Both for and while loops are used to run set of statements repeatedly.
But they are different, in syntax.

for loop syntax is much cleaner, compared to while loop. initialization, condition and change of values in expression, appear at one place, hence code using for loop is better readable and maintainable.

Another difference is for loop lets to declare variables, which can be used only within for block. But its not possible to declare variables in while statement.

Difference between while and do while loops

Basic difference between while and do while is
1.while loop iterates zero or more times, based on the condition
2.But do while loop iterates one or more times, based on the condition

You may also like to read:
How many keywords in Java?
Basic data types in Java

Different Types of Inheritance in Java

Inheritance is one of the powerful Object Oriented Concept, and improves re usability of the code.

Below are different types of inheritance
1. Single Inheritance or Simple Inheritance
This is simplest form of Inheritance, in which one class inherits members of another class. In Single Inheritance there exists one Base class and one Derived class.

Single Inheritance in Java
Single Inheritance

2. Multilevel Inheritance
In Multilevel inheritance, a Derived class is a Base class for some other class. As shown in below example class B is Derived from class A. And further class C is derived from class B. And class C can further be Base class of some other class, and there can be few more levels. Multilevel Inheritance example
multi level inheritance
multi level inheritance

Having too many Levels may adversely affect performance during run time.

Refer Inheritance in Generic class.

3. Hierarchical Inheritance
In Multilevel Inheritance, there is common Base class for more than one Derived class.
As shown in below picture class A is common Base class to classes B and C. Hierarchical Inheritance example

4. Hybrid Inheritance
Hybrid Inheritance has more than one inheritance. Actually this is combination of Multilevel, Single and Hierarchical Inheritance. Below is Hybrid Inheritance Example

Hybrid Inheritance in Java
Hybrid Inheritance in Java

You may also like to read:
Why multiple inheritance is not supported in Java?

How to declare constants in Java?

final keyword is used to declare constants.

final can be used to declare constants
1. which is a data member in a class.
2. in an interface
3. local within a method.

Declared constant can be primitive or non primitive data type


Below is an example

class Abc{
    public void show()
    {
        System.out.println("show() method in Abc class");
    }
}

interface Test{
    final int VAL = 45;
}

public class FinalKeywordDemo {
    final static float XYZ = 3.5f;
    final static Abc obj = new Abc();
    public static void main(String args[])
    {
        final int MAX_VALUE = 10;
        //final keyword is used to define constant values

        //obj = new Abc();//error, b'coz obj is final
        //MAX_VALUE = 20; //error, b'coz ABC is final
        //XYZ = 5.8f; //error

        System.out.println(MAX_VALUE+" "+XYZ+" "+Test.VAL);
    }
}


You may also like to read:
Purpose of final method
What is final class