You are on page 1of 76

# Primitive value vs Reference value

## Note 1: A variable is a sticky note.

Now, a sticky note is very small. You can only write a little bit of information on it. If you want to write
more information you need more sticky notes, but that's not a problem. Imagine you have an endless
supply of sticky notes.

Note 2: You have an endless supply of sticky notes, which store small amounts of information.
Great, what can you write on your sticky note? I can write:

1. Yes or no (a boolean).
2. My age (a number).
3. My name (a string).
4. Nothing at all (undefined).
5. A doodle or anything else which means nothing to me at all (null).
So we can write simple things (let's be condescending and call them primitive things) on our sticky
notes.
Note 3: You can write primitive things on your sticky notes.
So say I write 30 on a sticky note to remind myself to buy 30 slices of cheese for the little party I'm
throwing at my place tonight (I have very few friends).
When I go to put my sticky note on the fridge I see that my wife has put another sticky note on the
fridge which also says 30 (to remind me that her birthday is on the 30th of this month).
Q: Do both the sticky notes convey the same information?
A: Yes, they both say 30. We don't know if it's 30 slices of cheese or the 30th day of the month, and
frankly we don't care. For a person who didn't know any better it's all the same.
var slicesOfCheese = 30;
var wifesBirthdate = 30;

## alert(slicesOfCheese === wifesBirthdate); // true

Note 4: Two sticky notes which have the same thing written on them convey the same information,
even though they are two different sticky notes.
I'm really excited about tonight - hanging out with old friends, having a great time. Then some of my
friends call me and say that they won't be able to make it to the party.

So I go to my fridge and erase the 30 on my sticky note (not my wife's sticky note - that would make
her very angry) and make it a 20.
Note 5: You can erase what's written on a sticky note and write something else.
Q: That's all good and fine, but what if my wife wanted to make write a list of groceries for me to pick
up while I was out to get some cheese. Would she need to write a sticky note for every item?
A: No, she would take a longer list of paper and write the list of groceries on that paper. Then she
would write a sticky note telling me where to find the list of groceries.
So what's happening here?

## 1. A list of groceries is obviously not simple (erm... primitive) data.

2. My wife wrote it on a longer piece of paper.
3. She wrote where to find it in a sticky note.
Honey, the list of groceries is under your keyboard.
To recap:

## 1. The actual object (the list of groceries) is under my keyboard.

2. The sticky note tells me where to find it (the address of the object).
1

Note 6: Reference values are references to objects (addresses where they will be found).
Page
Q: How do we know when two sticky notes say the same thing? Say my wife made another grocery list
in case I misplaced the first, and wrote another sticky note for it. Both the lists say the same thing, but
do the sticky notes say the same thing?
A: No. The first sticky note tells us where to find the first list. The second one tells us where to find the
second list. It doesn't matter whether the two lists say the same thing. They are two different lists.
var groceryList1 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];
var groceryList2 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];

## alert(groceryList1 === groceryList2); // false

Note 7: Two sticky notes convey the same information only if they refer to the same object.
This means if my wife made two sticky notes reminding me where the grocery list is, then the two
sticky notes contain the same information. So this:

## Honey, the list of groceries is under your keyboard.

Contains the same information as:

## Don't forget that the list of groceries is under your keyboard.

In programming terms:

var groceryList1 = ["1 dozen apples", "2 loaves of bread", "3 bottles of milk"];
var groceryList2 = groceryList1;

## alert(groceryList1 === groceryList2); // true

So that's all that you need to know about primitives and references in JavaScript. No need to get into
things like heap and dynamic memory allocation. That's important if you're programming in C/C++.
Edit 1: Oh, and the important thing is that when you pass variables around you're essentially
passing primitive values by value and reference values by reference.
This is just an elaborate way of saying that you're copying everything written on one sticky note to
another (it doesn't matter whether you're copying a primitive value or a reference).
When copying references, the object being referenced doesn't move (e.g. my wife's grocery list will
always stay under my keyboard, but I can take the sticky note I copied anywhere I want - the original
sticky note will still be on the fridge).
2
Page
Primitive vs. Reference Data Types
Primitives vs. References
 primitive types are the basic types of data
o byte, short, int, long, float, double, boolean, char
o primitive variables store primitive values
 reference types are any instantiable class as well as arrays
o String, Scanner, Random, Die, int[], String[], etc.

Assignment
 copies the contents of RHS variable into LHS variable
o primitives: the primitive value is copied
o references: the address is copied
 implications: for references the object is not copied, it is shared (reference variables
are aliases)

## Comparisons (e.g. ==)

 compares the contents of the variables
o primitives: the primitive values are compared
o references: the addresses are compared
 implications: for references the contents of the objects are not compared

Passing Parameters
 terminology:
o formal parameter: the parameter variable that is listed (along with its type) in the
method declaration
o actual parameter: the parameter that is given when the method is called
 copies the contents of actual parameter into the formal parameter (i.e., pass-by-value)
o primitives: the primitive value is copied
o references: the address is copied
 implications: for references the object is not copied, it is shared (i.e., actual parameter
and formal parameter are aliases)
 primitives: changing the formal parameter's value doesn't affect the actual parameter's
value
 references: changing the formal parameter's address doesn't affect the actual
parameter's address but changing the formal parameter's object does change the actual
parameter's object since they refer to the same object
3
Page
Returning Values
 returns a result to where the method was called
o primitives: the primitive value is returned
o references: the address is returned
 recall: local variables and parameters are destroyed when the method finishes execution
 implications: a locally created object can survive if it is returned or if it is stored in a data
member

## assigning a value to long data type in java

up long val = 5000000000;
vote4do The error during this assignment is "The literal 5000000000 of type int is out of range". Why does the
wn votefavorite
compiler by default assumes the literal to be int??

ANS

There is aspecific suffixes for long i.e L. If there is no suffix, then 5000000000 assumed to be
an int type. And 5000000000 is out of int range, causing the erro. So you need to add L at
the end of 5000000000 for it to be treated as a long value. Change your declaration from
long val = 5000000000L;

4
Page

String x = null;

## 1. What exactly does this statement do?

Recall what is a variable and what is a value. A common metaphor is that a variable is
similar to a box. Just as you can use a box to store something, you can use a variable to
store a value. When declaring a variable, we need to set its type.

There are two major categories of types in Java: primitive and reference. Variables
declared of a primitive type store values; variables declared of a reference type store
references. In this case, the initialization statement declares a variables “x”. “x” stores
String reference. It is null here.

## 2. What exactly is null in memory?

What exactly is null in memory? Or What is the null value in Java?

First of all, null is not a valid object instance, so there is no memory allocated for it. It is
simply a value that indicates that the object reference is not currently referring to an object.

## What is Null in Java

As I said, null is very very important concept in Java. It was originally invented to denote
absence of something e.g. absence of user, a resource or anything, but over the year it has
troubled Java programmer a lot with nasty null pointer exception. In this tutorial, we will learn
basic facts about null keyword in Java and explore some techniques to minimize null checks
and how to avoid nasty null pointer exceptions.

1) First thing, first, null is a keyword in Java, much like public, static or final. It's
case sensitive, you cannot write null as Null or NULL, compiler will not recognize them and
give error.
5
Page
Object obj = NULL; // Not Ok
Object obj1 = null //Ok

2) Just like every primitive has default value e.g. int has 0, boolean has false, null is
the default value of any reference type, loosely spoken to all object as well. Just like if you
create a boolean variable, it got default value as false, any reference variable in Java has
default value null. This is true for all kind of variables e.g. member variable or local variable,
instance variable or static variable, except that compiler will warn you if you use a local
variable without initializing them. In order to verify this fact, you can see value of reference
variable by creating a variable and them printing it's value, as shown in following code snippet :

## private static Object myObj;

public static void main(String args[]){
System.out.println("What is value of myObjc : " + myObj);
}

## What is value of myObjc : null

This is true for both static and non-static object, as you can see here that I made myObj a
static reference so that I can use it directly inside main method, which is static method and
doesn't allow non-static variable inside.

4) null can only be assigned to reference type, you cannot assign null to primitive variables
e.g. int, double, float or boolean. Compiler will complain if you do so, as shown below.

## short s = null; // type mismatch : cannot convert from null to short

byte b = null: // type mismatch : cannot convert from null to byte
double d = null; //type mismatch : cannot convert from null to double

## Integer itr = null; // this is ok

int j = itr; // this is also ok, but NullPointerException at runtime

As you can see, when you directly assign null to primitive error it's compile time error, but if
you assign null to a wrapper class object and then assign that object to respective primitive
type, compiler doesn't complain, but you would be greeted by null pointer exception at
runtime. This happens because of autoboxing in Java, and we will see it in next point.

7) You may know that you cannot call a non-static method on a reference variable
with null value, it will throw NullPointerException, but you might not know that,
you can call static method with reference variables with null values. Since static methods are
bonded using static binding, they won't throw NPE. Here is an example :

## public class Testing {

public static void main(String args[]){
6

## Testing myObject = null;

Page

myObject.iAmStaticMethod();
myObject.iAmNonStaticMethod();
}

## private static void iAmStaticMethod(){

System.out.println("I am static method, can be called by null
reference");
}

## private void iAmNonStaticMethod(){

System.out.println("I am NON static method, don't date to call me by null");
}

Output:
I am static method, can be called by null reference
at Testing.main(Testing.java:11)

9) You can compare null value using == (equal to ) operator and != (not equal to) operator,
but cannot use it with other arithmetic or logical operator e.g. less than or greater than. Unlike
in SQL, in Java null == null will return true, as shown below :

## String abc = null;

String cde = null;

if(abc == cde){
System.out.println("null == null is true in Java");
}

if(null != null){
System.out.println("null != null is false in Java");
}

if(abc == null){
// do something
}

## // not ok, compile time error

if(abc > null){

}
}
}

Output:
null == null is true in Java
7
Page
APPENDIX A: OPERATOR PRECEDENCE IN JAVA

Java has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence order.
When two operators share an operand the operator with the higher precedence goes first.
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3
since multiplication has a higher precedence than addition.

Associativity.
When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y
= (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-
left associativity (and an assignment statement evaluates to the value on the right hand side).
On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-
right associativity.

## Precedence and associativity of Java operators.

The table below shows all Java operators from highest to lowest precedence, along with
their associativity. Most programmers do not memorize them all, and even those that do still
use parentheses for clarity.

## [] access array element

. access object member
() invoke a method 1 left to right
++ post-increment
-- post-decrement

++ pre-increment
-- pre-decrement
+ unary plus
2 right to left
- unary minus
! logical NOT
~ bitwise NOT

() cast
3 right to left
new object creation
8
Page
*
/ multiplicative 4 left to right
%

5 left to right
+ string concatenation

<< >>
shift 6 left to right
>>>

< <=
> >= relational
instanceof 7 left to right
type comparison

==
equality 8 left to right
!=

## ?: conditional 14 right to left

= += -=
*= /= %=
&= ^= |= assignment 15 right to left
<<= >>= >>>=

There is no explicit operator precedence table in the Java Language Specification and
different tables on the web and in textbooks disagree in some minor ways.
Order of evaluation of subexpressions.
Associativity and precedence determine in which order Java applies operators to
subexpressions but they do not determine in which order the subexpressions are evaluated.
9

In Java, subexpressions are evaluated from left to right (when there is a choice). So, for
Page

example in the expression A() + B() * C(D(), E()), the subexpressions are evaluated in
the order A(), B(), D(), E(), and C(). Although, C() appears to the left of both D() and E(),
we need the results of both D() and E() to evaluate C(). It is considered poor style to write
code that relies upon this behavior (and different programming languages may use different
rules).

Short circuiting. When using the conditional and and or operators (&& and ||), Java does
not evaluate the second operand unless it is necessary to resolve the result. This allows
statements like if (s != null && s.length() < 10) to work reliably. Programmers rarely
use the non short-circuiting versions (& and |) with boolean expressions.

## Precedence order gone awry.

Sometimes the precedence order defined in a language do not conform with mathematical
norms. For example, in Microsoft Excel, -a^b is interpreted as (-a)^b instead of -(a^b). So -
1^2 is equal to 1 instead of -1, which is the values most mathematicians would expect.
Microsoft acknowledges this quirk as a "design choice". One wonders whether the
programmer was relying on the C precedence order in which unary operators have higher
precedence than binary operators. This rule agrees with mathematical conventions for all C
operators, but fails with the addition of the exponentiation operator. Once the order was
established in Microsoft Excel 2.0, it could not easily be changed without breaking backward
compatibility.

Exercises.
1. What is the result of the following code fragment?

int x = 5;
int y = 10;
int z = ++x * y--;

## System.out.println("1 + 2 = " + 1 + 2);

System.out.println("1 + 2 = " + (1 + 2));

## Answer: 1 + 2 = 12 and 1 + 2 = 3, respectively. If either (or both) of the operands

of the + operator is a string, the other is automatically cast to a string. String
concatenation and addition have the same precedence. Since they are left-
associative, the operators are evaluated left-to-right. The parentheses in the second
statement ensures that the second + operator performs addition instead of string
concatenation.

3. Add parentheses to the following expression to make the order of evaluation more
clear.

## Answer: LeapYear.java shows a variety of equivalent expressions, including the

following reasonable alternative.

## 4. What does the following code fragment print?

System.out.println(1 + 2 + "abc");
10

System.out.println("abc" + 1 + 2);
Page

Answer: 3abc and abc12, respectively. The + operator is left associative, whether it is
string concatenation or arithmetic plus.
Problem while printing characters Difference between
System.out.println('A') and System.out.println(+'A') [closed]

1 Why is it that :

## System.out.println('A') //gives output as A

Also

System.out.println(8+4+'A'+"PRIME"+4+4+'A');
gives output as 77PRIME44A
Why is it that 8+4 before the String "Prime" are being added, while 4+4 after "Prime"
are being printed as it is ?
I also have a doubt why 8+4+'A' results in 65(ascii of A)+12=77 whereas
4+4+'A' doesn't include A's ascii getting added up ?
Is there any specific rule or convention regarding the above ?

## up System.out.println(+'A') //gives output as 65

vote1down In the expression +'A' the unary plus operator (indicating a positive integer) gets applied
to 'A' and the expression only makes sense if the char is converted to an int. The
vote acce pted

character 'A' has the int value of 65 (see the ASCII table), which is why the whole
expression evaluates to 65, which then gets printed.
System.out.println(8+4+'A'+"PRIME"+4+4+'A');

## gives output as 77PRIME44A

Why is it that 8+4 before the String "Prime" are being added, while 4+4 after "Prime"
are being printed as it is ?
Because the associativity of + (both for integer addition and for string concatenation) is
left-to-right. So first you do 8+4, which is integer addition, then 12+'A' (which
requires 'A' to be interpreted as its integer value 65), and then you have +"PRIME". But
this only makes sense as string concatenation, which is why it results in "77PRIME";
afterwards every call to + is a string concatenation; the integers get converted to their
string equivalents (4 -> "4") and the result of a string + char operation shouldn't surprise
you.
So it's

8+4+'A'+"PRIME"+4+4+'A'
--> ((((((8+4)+'A')+"PRIME")+4)+4)+'A') // placed explicit parenthesis
--> (((((12+'A')+"PRIME")+4)+4)+'A') // int addition 8+4
--> ((((77+"PRIME")+4)+4)+'A') // int addition, 'A' cast to
int 65
--> ((("77PRIME")+4)+4)+'A') // string concat, 77 converted
to "77"
--> (("77PRIME4"+4)+'A') // string concat, 4 --> "4"
--> ("77PRIME44"+'A') // ditto
--> "77PRIME44A" // string + char concat

KEYWORDS
11
Page
1. abstract: - Java provides abstract keyword to signify something empty. By empty we mean that it has no
definition or implementation. Keyword abstract is used before the classes and methods. At the time of declaring
a class we mark it as abstract. An abstract class cannot be instantiated. It means an abstract class cannot have
Objects. Generally when we place keyword abstract before a class, we make sure that this class is basically an
abstract implementation or generic class and the functional characteristics can only be added by extending the
class. We cannot create objects of abstract class but we can make their sub-class and create objects of that. By
abstract method, we mean that method doesn't have any body. An abstract method doesn't have any statements
to execute. Classes that contain abstract method must also be assigned as abstract class and implementation to
their abstract method must be provided by extending those classes. If subclasses fail to provide implementation
to super-class abstract methods, than they are also marked as abstract.

2. assert: - Java provides us with a debugging keyword called as assert. In Java, assert is a normal Java
statement which a programmer puts in the code, that he/she thinks will always be true. Generally, assert
statements are being used by the programmer for the debugging purpose. Assertion statements can be turned
on or off. While running a program if we enable assertion than wherever our assert statement gets failed
Assertion Error is thrown by the program and whole program gets terminated. Generally, assertions are placed
by programmer in the code where he believes that statement will be true. After enabling assertion if there is a
failure, programmer gets an idea that in code there is some bug. The code fails with an Assertion Error.

3. boolean: - A boolean keyword in Java is a data type for a variable which can store two values, true or false.
Generally, boolean keyword is a data type which has size of 1 bit. In Java I am not sure about the size that
whether it store 1 bit or not.

4. break: - In Java, 'break' keyword is of quite high importance. As the name suggest, break statement breaks
code from one point and transfer flow to other part of program to execute. Generally let say in if block you have
placed a break statement. If your code enters if statement an encounters break statement it will stop executing
further if block and come out of if block and continue to execute. That is when you encounter break statement
execution breaks that block of code and control gets transfer to next statement just after the block. Generally
break statement are mostly used with switch statement. If break is used within a labeled block, than as soon as
break gets encountered, the program starts executing just after labeled block.

5. byte :- In Java, byte keyword is used as a data type for storing 8 bits of information for an integer. If it’s used
before a method definition than that method, when called will always return a byte value.

6. case :- In Java, case keyword is used within switch statements. A condition in switch statement is compared
with the cases in switch statement. Whatever case matches with the switch expression that case is executed.

7. catch :- In Java, catch keyword has a group of statements that catches exception, if there is any exception in
try block proceeding to it. The statements have a way to deal with the exception or have a way to let
programmer know that something is needed to be correct.

8. char :- In Java, char keyword is used as a data type which can store 16 bit Unicode character. If the keyword
is placed before method declaration than the method upon execution returns a value which is a char.

9. class :- In Java, class keyword is used to define a class. Generally a class acts as a blue print for an object. It
defines implementation for the object. It has statements defining variables, methods, inner classes etc. An
Object when instantiated for a particular class has all the physical implementation of what is defined in the class.

10. const :- It is a reserved keyword in Java but it has no use in Java and Java has provided it no function to
perform.

11. continue :- In Java, the continue keyword is used when we want rest of the statement after continue
12

keyword to get skipped and want program to continue with the next iteration.
Page

12. default :- In Java, default keyword is used within switch statement. It is used their optionally, if no Java case
matches with the expression than the default case is executed by the program.

13. do :- In Java, do keyword is used to implement do-while loop. Generally, do keyword is used when we want
to loop a block of statement once. After that the boolean condition gets evaluated, if condition is yes the loop
execute again, but if condition comes out to be false the loop exits.

14. double :- In Java, double keyword is used as a data type for storing 64 bits of information for a float type. If
it’s used before a method definition than that method when called will always return a double value.

15. else :- In Java, else keyword is used along with if keyword to create an if-else statement. Generally, a
condition is evaluated in if block brackets. If the condition evaluates to true if block body gets executed. If the
condition is evaluated to false else block body gets executed.

16. enum :- It is used in Java language to declare a data type consisting of a set of named values. They are
constants.

17. extends :- In Java, extends keyword is used specify the super class of a subclass, also in interface
declaration to specify one or more super interfaces. If we take an example say let say class A extends class B,
here class A adds functionality to class B by adding fields or methods. It goes same with interfaces.

18. final :- Generally, final keyword is used to make elements constant. That is once assigned cannot be
changed. A final class cannot be sub-classed. A final variable cannot be assigned a new value after it has been
assigned to a value. A final method cannot be overridden.

19. finally :- In Java, finally keyword is used to define a block of statements after try to catch blocks. This block
executes after try block, or after catch block, or before any return statement.

20. float :- In Java, float keyword is used as a data type for storing 32 bits of information for a float type. If it’s
used before a method definition than that method when called will always return a float value.

21. for :- In Java, for keyword is used to create looping statement that is for loop. In this for loop a counter
variable is initialized, than a boolean condition is evaluated and compared with counter variable or any
expression which turns out to either true or false. If the condition comes out to be true a block of statements
following for keyword executes, if condition comes out to be false for loop terminates.

22. goto :- In Java, a goto keyword is a reserved keyword which is not used in the Java language and has no
function provided to it.

23. if :- In Java, if keyword is used (optionally) along with else keyword to create an if-else statement. Generally,
a condition is evaluated in if block brackets. If the condition evaluates to true if block body gets executed. If the
condition is evaluated to false else block body gets executed.

24. implements :- In Java, implements keywords is used in class declaration. Generally, implements keyword
implements functionality of interfaces. Interfaces are abstract in nature; their functionality is implemented in the
class which implements it.

25. import :- In Java, import statement is used at the start of a Java file, just after package declaration.
Generally, import statement gets those classes in a program whose functionality we want to use in the program.
It is also used in importing static members.

26. instanceof :- In Java, instanceof operator is a binary operator which is used to test an IS-A relationship
13

between a class and object. Object is first operand and Class or Interface is a second operand.
Page

27. int :- In Java, int keyword is used as a data type for storing 32 bits of information for an integer type. If it’s
used before a method definition than that method when called will always return an int value.

28. interface :- In Java, interface is a special type of structure which contains abstract methods, constant fields
which are generally static or final.

29. long :- In Java, long keyword is used as a data type for storing 64 bits of information for an integer type. If
it’s used before a method definition than that method when called will always return a long value.

30. native :- This keyword is generally used in declaring method signifying that method's implementation is not
in the same source file but in different source file and in different language too.

31. new :- Java has a keyword called as new, which has been used to create a new instance of a class on heap.
It is used is object creation and providing memory to it.

32. package :- Packages have been created by the package keyword. In the package classes are kept which
constitute a relation between each other.

33. private :- In Java, private keyword can be used in declaration of methods, fields, inner class. This makes the

34. protected :- In Java, protected keyword can be used in declaration of methods, fields, inner class. This
makes the methods, fields and inner class access to own class members, to sub class and classes of same
package.

35. public :- In Java, public keyword can be used before class, methods, fields. This makes the class , methods
and fields accessible from any other class.

36. return :- In Java, return keyword is used to pass a value from a method to caller method. It also signifies end
of execution of a method.

37. short :- In Java, short keyword is mainly used when we want to declare a field that can hold 16 bit of integer
data. It is also placed before method declaration which signifies that method will return only short integer.

38. static :- In Java, static keyword is used when you want to declare method, fields and inner class as class
members rather object members, generally static members belong to a class rather than instance of that class.
Therefore only one copy is made for them and used by the class as its own implementation.

39. strictfp :- To ensure portability of floating point we ensure that they are platform independent.

40. super :- In Java, super keywords is used to access overridden methods and hidden members of super class
by its subclass. It is also used in constructor of a subclass to pass control over super class constructor.

41. switch :- In Java switch keyword is used to have multi-decision making statements. Generally switch is
mostly used with keywords case, break and default. This decision making block evaluates an expression first.
After the expression is evaluated the value is compared with various case statements. Any value that matches
with the expression, case associated with it gets executed. If no expression matches the default case gets
executed.

42. synchronized :- In java, synchronized keyword is used before the method declaration and before block of
code to get mutual lock for an object. It means that the method or block of code gets locked by the object till it
gets fully unlocked or gets fully executed by that object. Generally classes, fields and interfaces cannot be
declared as synchronized. The static method gets code synchronization by class itself.
14

43. this :- In Java, this keyword is used as a reference to currently executable object. Generally if we want to
Page

access class members we can use this keyword to access them. If we want to refer to a current object we use
this keyword. We also use this keyword to transfer control from one constructor to another in the same class.

44. throw :- In Java, when we want to throw a declared exception, the execution points to the catch block which
has provided statements to overcome the exception. If no catch block is declared in the current method than the
exception is passed to the calling method. It continues till it found exception handler. If no exception handler is
found over the stack that exception is then transferred to the Uncaught Exception handler.

45. throws :- In Java, we use throws keyword in the method declarations. If we get an exception in a method
and method has no implementation for that exception, than method throws an exception. The exception thrown
has been handled by the method who has called to current method in execution.

46. transient :- Whenever we declare a variable as transient, that variable is not the part of Object serialization.
When an object gets saved through default serialization all the non-transient variable retain their value after
deserialization. If you want the variable should have default value after deserialization than make it transient.

47. try :- In Java, whenever we want to do exception handling we use try keyword. Generally try block is used
where we are sure that exception can occur. In try block statements are executed normally and as soon as
exception occur it is handled my catch keyword following try block. It must have at least one catch or finally
block.

48. void :- In Java, when we use void before any method declaration, we make sure that method doesn't return
any value.

49. volatile :- In Java, volatile keyword provides a lock free mechanism. If a variable is assigned as volatile than
all the threads accessing it can modify its current value without keeping a separate copy. A volatile keyword is
accessed by all threads simultaneously. They operate on current value of variable rather than cached value.

50. while :- In Java, while keyword is used to create looping statement that is while loop. In this while loop a
boolean condition is evaluated and compared with counter variable or any expression which turns out to either
true or false. If the condition comes out to be true a block of statements following while keyword executes, if
condition comes out to be false the while loop terminates.

51. false :- In Java, false keyword is the literal for the data type Boolean. Expressions are compared by this
literal value.

52. null :- In Java, null keyword is the literal for the reference variable. Expressions are compared by this literal
value. It is a reserved keyword.

53. true :- In Java, true keyword is the literal for the data type Boolean. Expressions are compared by this literal
value.
15
Page
Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP)
Procedure Oriented Programming Object Oriented Programming
Divided Into In POP, program is divided into small parts In OOP, program is divided into parts called objects.
called functions.
Importance In POP,Importance is not given to data but to functions In OOP, Importance is given to the data rather than
as well as sequence of actions to be done. procedures or functions because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected,
Specifiers etc.
Data Moving In POP, Data can move freely from function to function In OOP, objects can move and communicate with each othe
in the system. through member functions.
Expansion To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function.
Data Access In POP, Most function uses Global data for sharing that In OOP, data can not move easily from function to
can be accessed freely from function to function in the function,it can be kept public or private so we can control
system. the access of data.
Data Hiding POP does not have any proper way for hiding data so it OOP provides Data Hiding so provides more security.
is less secure.
Examples Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.NET.
16
Page
Java - Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.

## Encapsulation in Java is a mechanism of wrapping the data (variables) and code

acting on the data (methods) together as a single unit. In encapsulation, the
variables of a class will be hidden from other classes, and can be accessed only
through the methods of their current class. Therefore, it is also known as data
hiding.

##  Declare the variables of a class as private.

 Provide public setter and getter methods to modify and view the variables values.

Example
Following is an example that demonstrates how to achieve Encapsulation in Java −

## /* File name : EncapTest.java */

public class EncapTest {
private String name;
private String idNum;
private int age;

return age;
}

return name;
}

return idNum;
}

## public void setAge( int newAge) {

17

age = newAge;
}
Page
public void setName(String newName) {
name = newName;
}

## public void setIdNum( String newId) {

idNum = newId;
}
}

The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters
and setters. Therefore, any class that wants to access the variables should access
them through these getters and setters.

The variables of the EncapTest class can be accessed using the following program −

## /* File name : RunEncap.java */

public class RunEncap {

## public static void main(String args[]) {

EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

}
}

## This will produce the following result −

Output
Name : James Age : 20

Benefits of Encapsulation
 The fields of a class can be made read-only or write-only.

 A class can have total control over what is stored in its fields.

 The users of a class do not know how the class stores its data. A class can change the data
18

type of a field and users of the class do not need to change any of their code.
Page
Encapsulation is more than just defining accessor and mutator methods for a class. It is broader
concept of object-oriented programming that consists in minimizing the interdependence between
classes and it is typically implemented through information hiding.

The beauty of encapsulation is the power of changing things without affecting its users.
In a object-oriented programming language like Java, you achieve encapsulation by hiding details
using the accessibility modifiers (public, protected, private, plus no modifier which implies package
private). With these levels of accessibility you control the level of encapsulation, the less restrictive the
level, the more expensive change is when it happens and the more coupled the class is with other
dependent classes (i.e. user classes, subclasses).

Therefore, the goal is not to hide the data itself, but the implementation details on how this data is
manipulated.
The idea is to provide a public interface through which you gain access to this data. You can later
change the internal representation of the data without compromising the public interface of the class.
On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the
capacity of changing the way you manipulate the data without affecting its users. You create a
dependency with the data itself, and not with the public interface of the class. You would be creating a
perfect cocktail for trouble when "change" finally finds you.

There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in
his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions
several compelling reasons, which I quote here:

 You can limit the values that can be stored in a field (i.e. gender must be F or M).
 You can take actions when the field is modified (trigger event, validate, etc).
 You can provide thread safety by synchronizing the method.
 You can switch to a new data representation (i.e. calculated fields, different data type)
However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding
the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It
returns a List implementation, but you do no care which implementation, as long as it satisfies
the List interface, right?. The implementation can be changed in the future without affecting the users
of the method.
The Beauty of Encapsulation
Now, in my opinion, to really understand encapsulation, one must first understand abstraction.

Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal
implementation. They have several subsystem, like a transmission system, a break system, a fuel
system, etc.

However, we have simplified its abstraction, and we interact with all cars in the world through the
public interface of their abstraction. We know that all cars have a steering wheel through which we
control direction, they have a pedal that when you press it you accelerate the car and control speed,
and another one that when you press it you make it stop, and you have a gear stick that let you control
if you go forward or backwards. These features constitute the public interface of the car abstraction. In
the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was
the same thing.

However, few of us know the details of how all these features are implemented under the hood. Think
of the time when cars did not have a hydraulics directional system. One day, the car manufactures
invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which
users where interacting with them. At most, users experienced an improvement in the use of the
directional system. A change like this was possible because the internal implementation of a car is
19

encapsulated. Changes can be safely done without affecting its public interface.
Page
Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides.
You go and buy one of these new cars, and when you run out of gas you go to the gas station, and
you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas
pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks,
it falls apart because things are not working the way it was expected. A change like this would cost
millions. We would need to change all gas pumps in the world. When we break encapsulation we have
to pay a price.

So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change.
You maximize encapsulation by minimizing the exposure of implementation details. The state of a
class should only be accessed through its public interface.
20
Page
Java - Abstraction

Previous Page
Next Page

As per dictionary, abstraction is the quality of dealing with ideas rather than
events. For example, when you consider the case of e-mail, complex details such as
what happens as soon as you send an e-mail, the protocol your e-mail server uses
are hidden from the user. Therefore, to send an e-mail you just need to type the

## Likewise in Object-oriented programming, abstraction is a process of hiding the

implementation details from the user, only the functionality will be provided to the
user. In other words, the user will have the information on what the object does
instead of how it does it.

## In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract
class.

 Abstract classes may or may not contain abstract methods, i.e., methods without body (
public void get(); )

 But, if a class has at least one abstract method, then the class must be declared abstract.

##  If a class is declared abstract, it cannot be instantiated.

 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.

 If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.

Example
This section provides you an example of the abstract class. To create an abstract
class, just use the abstract keyword before the class keyword, in the class
declaration.
21
Page

## /* File name : Employee.java */

public abstract class Employee {
private String name;
private int number;

## public Employee(String name, String address, int number) {

System.out.println("Constructing an Employee");
this.name = name;
this.number = number;
}

## public double computePay() {

System.out.println("Inside Employee computePay");
return 0.0;
}

## public void mailCheck() {

System.out.println("Mailing a check to " + this.name + " " + this.address);
}

## public String toString() {

return name + " " + address + " " + number;
}

return name;
}

}

}
22

## public int getNumber() {

Page

return number;
}
}

You can observe that except abstract methods the Employee class is same as normal
class in Java. The class is now abstract, but it still has three fields, seven methods,
and one constructor.

Now you can try to instantiate the Employee class in the following way −

## /* File name : AbstractDemo.java */

public class AbstractDemo {

## public static void main(String [] args) {

/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

When you compile the above class, it gives you the following error −

## Employee.java:46: Employee is abstract; cannot be instantiated

Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error

## Inheriting the Abstract Class

We can inherit the properties of Employee class just like concrete class in the
following way −

Example
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary

## public Salary(String name, String address, int number, double salary) {

setSalary(salary);
}

23

Page

}

return salary;
}

## public void setSalary(double newSalary) {

if(newSalary >= 0.0) {
salary = newSalary;
}
}

## public double computePay() {

System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Here, you cannot instantiate the Employee class, but you can instantiate the Salary
Class, and using this instance you can access all the three fields and seven methods
of Employee class as shown below.

## /* File name : AbstractDemo.java */

public class AbstractDemo {

## public static void main(String [] args) {

Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

## This produces the following result −

Output
Constructing an Employee
Constructing an Employee
24

## Call mailCheck using Salary reference --

Within mailCheck of Salary class
Page

## Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
25
Page
Java Encapsulation Abstraction Data hiding
and Data binding

## Java Encapsulation : In an object-oriented programming

language, Encapsulation, Abstraction, Data hiding and Data binding are very
confusing words, everyone feels difficult to understand. Many Web sites discuss at
length and finally one site contradicts slightly with the other with many user comments
of what they feel.
Here I give in my own style of explanation on Java Encapsulation etc., first in a layman way (to
simplify the complexity) and then technically.
When a male and female get married they are known as husband and wife and they are binded (actual
English grammatical usage must be "bound") together (here I use binding word). The advantage of binding
is their secrets of life are not revealed to others, other way they are hidden (I use the word hidden). The
behaviour between them is hidden from outside world. They may donate some money to charities. Charities
are using the money but without knowing how they saved the money out of their salary. I say the saving
style is abstractedfrom charities (here I used the word abstraction). But charities are still using the money
without knowing the implementation details of saving. Like this pair of wife and husband, many pairs exist.
One pair’s behaviour is not known to the other pair, other way, one pair secrets of life are known to the other
pair. Each pair makes one unit. I say units are encapsulated (here, I use encapsulation). With encapsulation,
one unit (pair) salary and saving data cannot be known or changed or affected by the other. Encapsulation is
possible between the pairs residing in the same building or locality.
Similarly, in the house you are using a Television set (TV). You are able to see the pictures and able to
change the channels without knowing electronics ICs and circuit boards. I say the making of TV
(implementation details) is abstracted (hidden) from you. To make TV, you should be an electronics
engineer but to use a TV, you need not be an electronic engineer. Similarly, you are using printf() function
in C-lang without knowing the code of printf(). I say printf() implementation details are abstracted from
you. In true sense, abstraction and hidden looks similar but slightly varies in their usage.
I apply the above discussion to a Java class. There is an Employee class with many objects. All employees
have salary. One employee salary is not known to the other employee or one employee cannot change other
employee salary. Let us discuss the above terms through employee example.

2 {

5 {
26

## 6 Employee emp1 = new Employee();

Page
7 Employee emp2 = new Employee();

9 emp1.salary = 5000;

10 emp2.salary = 6000;

11

## 13 System.out.println("emp2.salary Rs." + emp2.salary); // prints 6000

14 }

15 }

salary is an instance variable which gives the property of salary paid to an Employee object. The salary of
Employee emp1 is assigned as 5000. This assignment is done by calling theemp1 object with instance
variable salary as emp1.salary. When called, both emp1 and salary are binded together (known as data
binding). When binded they occupy one location in the memory. Similarly emp2.salary is assigned as 6000
and this emp2.salary occupies different location in memory. One location is not known to another even
though both objects emp1and emp2 belong to the same class and there is only one instance variable. That
is, emp1does not know the salary of emp2 and likewise emp2 is not aware of emp1 salary. In other way,
they are hidden from each other and is known as data hiding. Data hiding is possible due to data binding,
other way impossible. This is known as encapsulation. emp1.salary is encapsulated from emp2.salary
and similarly emp2.salary is encapsulated from emp1.salary. The advantage of encapsulation
is emp1 cannot alter the emp2 salary and vice versa. Other classes can make use of emp1 salary of 5000
without knowing how the salary is assigned (or implemented). Other way, the salary assignment information
is abstracted for other classes, but still can make use of emp1 salary. The advantage of Java encapsulation is
one instance variable can be given different values, of course, calling with different objects.
27
Page
How to explain the difference between
Encapsulation and Abstraction before an
Interviewer?
Read the following points for more deeper study
1. In general, Abstraction lets you focus on what the object does instead of how it does it.
2. Encapsulation means hiding the internal details or mechanics of how an object does something.
Like when you drive a car, you know what the gas pedal does but you may not know the process
behind it because it is encapsulated.
3. Encapsulation means binding your data member (variable) function into one class (to one
object). Abstraction means hiding your logic whatever you are used in your program.
4. Encapsulation is to hide the variables or something inside a class, preventing unauthorized
parties to use. So the public methods like getter and setter access it and the other classes call
these methods for accessing.
5. Abstraction involves the facility to define objects that represent abstract “actors” that can
perform work, report and change their state and “communicate” with other objects in the system.
6. A real time example is as a driver you know how to start the car by pressing the start button and
internal details of the starting operations are hidden from you. So the entire starting process is
hidden from you otherwise we can tell starting operation is encapsulated from you or the driving
wheel is encapsulated the process of rotating the wheel from you.
7. Abstraction
Before mentioning anything about abstraction, we can take three different users here (I am calling
them as entity)

## 1) You 2) Local Mechanic 3) Expert

You Entity: Since you know only to start the car by pressing a button and all other operations
behind the scene are abstracted from you.
Local Mechanic Entity: Our local mechanic knows some of the implementation of starting the car,
i.e., he can open car’s bonnet and check the battery cable or choke etc. So in short Local
Mechanic Entity knows some of the implementations of the car but not all.
Expert Entity: Since our expert (Designer of the car) mechanic knows all the operations of our car,
he can repair it very quickly. So in short, Expert Entity knows all the implementations of the car.
The car’s operation is completely abstracted from you and it is partially implemented to Local
Mechanic Entity and fully implemented to Expert Entity. So you are an abstract class having only
abstract methods, Local Mechanic Entity has extended You (Since he is also an ordinary user)
and he implemented some of the methods and last our expert Entity extending Local Mechanic
and implementing all the methods.

8. In Simple words “Encapsulation is the feature of opps that is used to hide the data using Access
Modifiers (public, default, protected, private)”. In OOPS programming language, object has a
power to share certain properties or behaviour to outside package or outside class.
9. Abstraction is the feature used to hide the Complexity .
10. I would say that encapsulation is the process consisting of protecting internal instance state by
only preventing the class user from altering this internal state except through the use of public
methods (that of course handle the internal state in a consistent manner).
11. Abstraction is a mean to gather common attributes or methods in a same place, letting the
ability to concrete subclasses to use them and to provide the implementation that is specific.
Abstraction may also be used to use “abstract” objects with defined behavior with the ability to
28

choose the actual implementation of this behaviour afterward. This is what may lead to think it has
Page

some similiarities with encapsulation (this notion of public API). However, in my opinion, this latter
use of abstration in Java shall be replaced by the use of interfaces.
12. Thus, for me, in Java (and in more general context), encapsulation and abstraction are quite
different notions, but they may be used together.
13. Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation
(information hiding) prevents clients from seeing it’s inside view, where the behavior of the
abstraction is implemented.
14. Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverable of Abstraction. Encapsulation barely talks about grouping up your
abstraction to suit the developer needs.
15. Encapsulation is the way to achieve different level (class, object, method etc) of security if you
like. Abstraction is the way to achieve extensible to the feature of any application (like a developer
knows a method required but its functionality is not defined which will be defined when required.)
16. Abstraction:only expose the methods which are necessary. Encapsulation (Data Hiding) hides
complexity
17. Encapsulation uses abstraction.
18. Encapsulation is hiding the data with a wrapper class. For this technique you need to modify
the access identifier of the member variables or the inner classes,so that its hidden to external
environment.
For eg : If a field is declared private, it cannot be accessed by anyone outside the class, thereby
hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

19. The benefits are the fields of a class can be made read-only or write-only. A class can have
total control over what is stored in its fields.
20. Abstraction: It’s the ability to make a class abstract. It’s functionality still exists similar to other
classes but the class cannot be instantiated, as its way to abstract. You need to inherit the
properties of the abstract class to initiate the subclass. Similarly, if you define abstract method, it’s
signature is a bit different and need not require to write the implementation but the subclass must
override the abstract method and provide the implementation specific to its own properties.
29
Page
What is polymorphism in programming?
Polymorphism is the capability of a method to do different things based on the object that it
is acting upon. In other words, polymorphism allows you define one interface and have
multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in
detail.

 It is a feature that allows one interface to be used for a general class of actions.
 An operation may exhibit different behavior in different instances.
 The behavior depends on the types of data used in the operation.
 It plays an important role in allowing objects having different internal structures to share the
same external interface.
 Polymorphism is extensively used in implementing inheritance.

## Following concepts demonstrate different types of polymorphism in java.

2) Method Overriding

Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any
point in a program simply by utilizing the method’s name.

In Java, it is possible to define two or more methods of same name in a class, provided that
there argument list or parameters are different. This concept is known as Method

types refer my post Types of polymorphism in java: Static, Dynamic, Runtime and Compile
time Polymorphism.

1. To call an overloaded method in Java, it is must to use the type and/or number of arguments to
determine which version of the overloaded method to actually call.
2. Overloaded methods may have different return types; the return type alone is insufficient to
distinguish two versions of a method. .
3. When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
6. It can have different access modifiers.

Example:

{
void demo (int a)
{
System.out.println ("a: " + a);
30

}
void demo (int a, int b)
Page

{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
{
public static void main (String args [])
{
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one has 2
int parameters and third one is having double arg. The methods are invoked or called with the
same type and number of parameters used.

Output:

a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25

## 1. Overloading can take place in the same class or in its sub-class.

2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be the part of the same class (can also take place in sub
class), with same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.

2) Method Overriding
Child class has the same method as of base class. In such cases child class overrides the
parent class method without even touching the source code of the base class. This feature is
known as method overriding.
Example:

## public class BaseClass

{
public void methodToOverride() //Base class method
{
System.out.println ("I'm the method of BaseClass");
}
}
public class DerivedClass extends BaseClass
31

{
public void methodToOverride() //Derived Class method
{
Page

}
}

## public class TestMethod

{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();
}
}
Output:

## I'm the method of BaseClass

I'm the method of DerivedClass
Rules for Method Overriding:

## 1. applies only to inherited methods

2. object type (NOT reference variable type) determines which overridden method will be used at
runtime
3. Overriding method can have different return type (refer this)
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.

## super keyword in Overriding:

When invoking a superclass version of an overridden method the super keyword is used.
Example:

class Vehicle {
public void move () {
System.out.println ("Vehicles are used for moving from one place to another ");
}
}

## class Car extends Vehicle {

public void move () {
super. move (); // invokes the super class method
System.out.println ("Car is a good medium of transport ");
}
}

## public class TestCar {

public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
b.move (); //Calls the method in Car class
}
}
Output:
32
Page

## Vehicles are used for moving from one place to another

Car is a good medium of transport
If anybody says CUT to these people
1. The Surgeon
2. The Hair Stylist
3. The Actor
What will happen?

##  The Surgeon would begin to make an incision.

 The Hair Stylist would begin to cut someone's hair.
 The Actor would abruptly stop acting out of the current scene, awaiting directorial guidance.
So above representation shows What is polymorphism (same name, different behavior) in OOP.

If you are going for an interview and interviewer asks you tell/show a live example for polymorphism
in the same room we are sitting at, say-

## Answer - Door / Windows

Wondering How?

Through Door / Window - a person can come, air can come, light can come, rain can come, etc.

## If anybody says CUT to these people

1. The Surgeon
2. The Hair Stylist
3. The Actor
What will happen?

##  The Surgeon would begin to make an incision.

 The Hair Stylist would begin to cut someone's hair.
 The Actor would abruptly stop acting out of the current scene, awaiting directorial guidance.
So above representation shows What is polymorphism (same name, different behavior) in OOP.

If you are going for an interview and interviewer asks you tell/show a live example for polymorphism
in the same room we are sitting at, say-

## Answer - Door / Windows

Wondering How?

Through Door / Window - a person can come, air can come, light can come, rain can come, etc.
33
Page
Garbage Collector at work
It is said that garbage collection uses “mark and sweep” algorithm and some other details
however, the first thing we must know is that, when does one object become eligible for the
garbage collection….or shall we say, is a garbage to the JVM. When we run the main() thread
(one thread which will always be there along with other threads) and this thread can either be
alive that is running or dead that is the execution is complete but it may also be the case that
while main() thread is silent some other threads are working on it. And all the life cycle of the
thread is maintained on its stack trace. And when garbage collector finds this that the particular
object is no more accessible to any threads i.e. it is unreachable or no references exist to the
object, such an object becomes vulnerable to be caught by the garbage collector.

Now, to make the object unreachable it is clear that the references to that object should cease
to exist and this can be done by removing the reference to the object either by making the
references null or by reassigning a new object to the existing reference for the current object.

## Java Garbage Collection

In java, garbage means unreferenced objects.Garbage Collection is process of reclaiming the
runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

## How can an object be unreferenced?

1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;

## 2) By assigning a reference to another:

1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By annonymous object:
1. new Employee();
34
Page
KEYWORDS VS RESERVED WORDS
Keywords have a special meaning in a language, and are part of the syntax.
Reserved words are words that cannot be used as identifiers (variables, functions, etc.), because
they are reserved by the language.
In practice most keywords are reserved words and vice versa. But because they're two different things
it may happen that a keyword is not a reserved word (e.g. a keyword only has meaning in a special
context, and can therefore be used as an identifier), or a reserved word is not a keyword (e.g. because
it is reserved for future use).

## Update: Some examples as given by others that illustrate the distinction:

 In Java, goto is a reserved word but not a keyword (as a consequence, you cannot use it at all)
 Fortran has no reserved words, all keywords (if, then, etc.) can be used as identifiers

A good example of this distinction is "goto" in Java. It's not a language keyword (i.e. it's not valid
Java), but it is a reserved word.
It seems that the java designers are telling us "We're not going to use 'goto', and neither are you"
35
Page
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.

a = 0011 1100

b = 0000 1101

~a = 1100 0011

## Binary AND Operator copies a bit to

& (bitwise (A & B) will give 12 which
the result if it exists in both
and) is 0000 1100
operands.

## Binary OR Operator copies a bit if it (A | B) will give 61 which

| (bitwise or)
exists in either operand. is 0011 1101

^ (bitwise Binary XOR Operator copies the bit if (A ^ B) will give 49 which
XOR) it is set in one operand but not both. is 0011 0001

## (~A ) will give -61 which

Binary Ones Complement Operator is
~ (bitwise is 1100 0011 in 2's
unary and has the effect of 'flipping'
compliment) complement form due to
bits.
a signed binary number.

## Binary Left Shift Operator. The left

operands value is moved left by the A << 2 will give 240
<< (left shift)
number of bits specified by the right which is 1111 0000
operand.

>> (right Binary Right Shift Operator. The left A >> 2 will give 15 which
shift) operands value is moved right by the is 1111
36

Page
operand.

## Shift right zero fill operator. The left

operands value is moved right by the
>>> (zero fill A >>>2 will give 15
number of bits specified by the right
right shift) which is 0000 1111
operand and shifted values are filled
up with zeros.

Example
public class Test {

## public static void main(String args[]) {

int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

## c = a & b; /* 12 = 0000 1100 */

System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );

## c = ~a; /*-61 = 1100 0011 */

System.out.println("~a = " + c );

## c = a << 2; /* 240 = 1111 0000 */

System.out.println("a << 2 = " + c );

c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );

## c = a >>> 2; /* 15 = 0000 1111 */

System.out.println("a >>> 2 = " + c );
}
37

}
Page

Output
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15

## Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the

## For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has

higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

## Equality >== != Left to right

38
Page
Bitwise AND >& Left to right

## Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left

39
Page
NOT A NUMBER
According to Wikipedia:

## There are three kinds of operation which return NaN:

 Operations with a NaN as at least one operand
 Indeterminate forms
 The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
 The multiplications 0×∞ and 0×−∞
 The power 1∞
 The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
 Real operations with complex results:
 The square root of a negative number
 The logarithm of a negative number
 The tangent of an odd multiple of 90 degrees (or π/2 radians)
 The inverse sine or cosine of a number which is less than −1 or greater than +1.

## NaN is triggered by the following occurrences:

 results that are complex values
 √x where x is negative
 log(x) where x is negative
 tan(x) where x mod 180 is 90
 asin(x) or acos(x) where x is outside [-1..1]
 0/0
 ∞/∞
 ∞/−∞
 −∞/∞
 −∞/−∞
 0×∞
 0×−∞
 1∞
 ∞ + (−∞)
 (−∞) + ∞
40
Page
Infinity
Operation Result
n ÷ ±Infinity 0
±Infinity × ±Infinity ±Infinity
±nonzero ÷ 0 ±Infinity
Infinity + Infinity Infinity
±0 ÷ ±0 NaN
Infinity - Infinity NaN
±Infinity ÷ ±Infinity NaN
±Infinity × 0 NaN
41
Page
WRAPPER CLASSES
Java is an object-oriented language and can view everything as an object. A simple file can be treated
as an object , an address of a system can be seen as an object , an image can be treated as an object
(with java.awt.Image) and a simple data type can be converted into an object (with wrapper classes).
This tutorial discusses wrapper classes. Wrapper classes are used to convert any data type into an
object.

The primitive data types are not objects; they do not belong to any class; they are defined in the
language itself. Sometimes, it is required to convert data types into objects in Java language. For
example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted
into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced
wrapper classes.

## What are Wrapper classes?

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object
appearance. Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type. It can be compared with a
chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution.
The user takes the chocolate, removes and throws the wrapper and eats it.

## Observe the following conversion.

int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in
Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object it1.

int m = it1.intValue();
System.out.println(m*m); // prints 10000
intValue() is a method of Integer class that returns an int data type.

## Importance of Wrapper classes

There are mainly two uses with wrapper classes.

1) To convert simple data types into objects, that is, to give object form to a data type; here
constructors are used.
2) To convert strings into data types (known as parsing operations), here methods of type parseXXX()
are used.
Features of the Java wrapper Classes.
1) Wrapper classes convert numeric strings into numeric values.
2) The way to store primitive data in an object.
3) The valueOf() method is available in all wrapper classes except Character
4) All wrapper classes have typeValue() method. This method returns the value of the object as its
primitive type.
42
Page
ACCESS SPECIFIERS

## | | |(same pkg)|(diff pkg)|

————————————+———————+—————————+——————————+——————————+————————

public | + | + | + | + | +

————————————+———————+—————————+——————————+——————————+————————

protected | + | + | + | + | o

————————————+———————+—————————+——————————+——————————+————————

no modifier | + | + | + | o | o

————————————+———————+—————————+——————————+——————————+————————

private | + | o | o | o | o

+ : accessible

o : not accessible
43
Page
What is Static
Static is a Non Access Modifier.

Applicable to
The Static keyword can be applied to

 Method
 Variable
 Class nested within another Class
 Initialization Block

Not Applicable to
The Static keyword can not be applied to

##  Class (Not Nested)

 Constructor
 Interfaces
 Method Local Inner Class(Difference then nested class)
 Inner Class methods
 Instance Variables
 Local Variables

## Purpose of Static Keyword in Java

The static word can be used to attach a Variable or Method to a Class. The variable or Method that
are marked static belong to the Class rather than to any particular instance.

## Java static keyword

1. Static variable

4. Static method

7. Static block

## 8. Can we execute a program without main method ?

44
Page
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.

3. block

4. nested class

## 1) Java static variable

If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects (that is not unique
for each object) e.g. company name of employees,college name of students etc.

o The static variable gets memory only once in class area at the time of class loading.

It makes your program memory efficient (i.e it saves memory).

## Understanding problem without static variable

1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created.All student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we make it static,this field will get
memory only once.

## Example of static variable

1. //Program of static variable
2.
3. class Student8{
4. int rollno;
5. String name;
45

## 6. static String college ="ITS";

7.
Page
8. Student8(int r,String n){
9. rollno = r;
10. name = n;
11. }
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13.
14. public static void main(String args[]){
15. Student8 s1 = new Student8(111,"Karan");
16. Student8 s2 = new Student8(222,"Aryan");
17.
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now

222 Aryan ITS

## Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each
46

## objects will have the value 1 in the count variable.

Page
1. class Counter{
2. int count=0;//will get memory when instance is created
3.
4. Counter(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter c1=new Counter();
12. Counter c2=new Counter();
13. Counter c3=new Counter();
14.
15. }
16. }
Test it Now

Output:1
1
1

## Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value.

1. class Counter2{
2. static int count=0;//will get memory only once and retain its value
3.
4. Counter2(){
5. count++;
6. System.out.println(count);
7. }
8.
9. public static void main(String args[]){
10.
11. Counter2 c1=new Counter2();
12. Counter2 c2=new Counter2();
13. Counter2 c3=new Counter2();
14.
15. }
16. }
Test it Now
47

Output:1
2
Page

3
2) Java static method
If you apply static keyword with any method, it is known as static method.

## o A static method belongs to the class rather than object of a class.

o A static method can be invoked without the need for creating an instance of a class.

o static method can access static data member and can change the value of it.

## Example of static method

1. //Program of changing the common property of all objects(static field).
2.
3. class Student9{
4. int rollno;
5. String name;
6. static String college = "ITS";
7.
8. static void change(){
9. college = "BBDIT";
10. }
11.
12. Student9(int r, String n){
13. rollno = r;
14. name = n;
15. }
16.
17. void display (){System.out.println(rollno+" "+name+" "+college);}
18.
19. public static void main(String args[]){
20. Student9.change();
21.
22. Student9 s1 = new Student9 (111,"Karan");
23. Student9 s2 = new Student9 (222,"Aryan");
24. Student9 s3 = new Student9 (333,"Sonoo");
25.
26. s1.display();
27. s2.display();
28. s3.display();
29. }
30. }
Test it Now
48

222 Aryan BBDIT
Page

## 333 Sonoo BBDIT

Another example of static method that performs normal calculation
1. //Program to get cube of a given number by static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Test it Now

Output:125

## Restrictions for static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.

## 2. this and super cannot be used in static context.

1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now

## Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method, jvm create
object first then call main() method that will lead the problem of extra memory allocation.

## 3) Java static block

o Is used to initialize the static data member.

## o It is executed before main method at the time of classloading.

49
Page
Example of static block
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now

Hello main

## Q) Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now

## In JDK7 and above, output will be:

public static void main(String[] args)
50
Page
PURE VS IMPURE FUNCTION
Characteristics of Pure Function:
1. The return value of the pure functions solely depends on its arguments Hence, if you call
the pure functions with the same set of arguments, you will always get the same return
values.
2. They do not have any side effects like network or database calls
3. They do not modify the arguments which are passed to them
Characterisitcs of Impure functions
1. The return value of the impure functions does not solely depend on its arguments Hence,
if you call the impure functions with the same set of arguments, you might get the differ-
ent return values For example, Math.random(), Date.now()
2. They may have any side effects like network or database calls
3. They may modify the arguments which are passed to them
function impureFunc(value){
return Math.random() * value;
}

function pureFunc(value){
return value * value;
}

## var impureOutput = [];

for(var i = 0; i < 5; i++){
impureOutput.push(impureFunc(5));
}

## var pureOutput = [];

for(var i = 0; i < 5; i++){
pureOutput.push(pureFunc(5));
}

## console.log("Pure result: " + pureOutput); // result is consistent with same input

51
Page
Constructors in Java – A complete study!!
Constructor is a block of code that allows you to create an object of class. This can also be
called creating an instance. Constructor looks like a method but it’s not, for example methods
can have any return type or no return type (considered as void) but constructors don’t have any
return type not even void.
There are several other differences between them, we will discuss them in detail at the end of

Types of Constructors
There are three types of constructors: default, no-arg and parameterised.
Default constructor: If you do not define any constructor in your class, java generates one for
you by default. This constructor is known as default constructor. You would not find it in your
source code but it would present there. It would look like this if you could see it. Default
constructor for class Demo:

public Demo()
{
}
no-arg constructor: Constructor with no arguments is known as no-arg constructor. The
signature is same as default constructor, however body can have any code unlike default
constructor where the body does nothing.

Important point to note here is that whatever constructor you write in your class cannot be
called default even if you write public Demo() { } in your class it cannot be called default since
you are writing it. The constructor is called default only when it has been generated by java.

## Example: A no-arg constructor for class Demo

class Demo
{
public Demo()
{
System.out.println("This is a default constructor");
}
}
Parameterized constructor: Constructor with arguments is known as parameterized
constructor.

class Demo
{
public Demo(int num, String str)
{
System.out.println("This is a parameterized constructor");
}
}
How to call a constructor?
To call a constructor use the keyword new, followed by the name of class, followed by
parameters if any. For example to create the object of class Demo, you can call the constructor
like this: new Demo()
52
Page
Object creation using constructor
Lets say class name is “Demo”

## 1) I’m declaring a reference variable of class Demo-

class Demo;
2) Object creation – Calling default constructor for creating the object of class Demo (new
keyword followed by class name)

new Demo();
3) Now, I’m assigning the object to the reference –

## class Demo = new Demo();

What if you don’t write a constructor in a class?
As discussed above, if you don’t write a constructor in your class, java would generate one for
you. Lets take a look at the code below to understand it litter better:

class Example
{
public void demoMethod()
{
System.out.println("hello");
}
public static void main(String args[])
{
Example obj = new Example();
obj.demoMethod();
}
}
In public static void main I am creating the object of class Example and in order to do that I
have invoked the default constructor of class Example( note the new Example()). But where did
I write the constructor? No I didn’t the java did it for me.

## If you understood the example then I may need to test your

skills – Guess the output of below Java program
class Example2
{
private int var;
public Example2()
{
//code for default one
var = 10;
}
public Example2(int num)
{
//code for parameterized one
var = num;
}
public int getValue()
53

{
return var;
Page

}
public static void main(String args[])
{
Example2 obj2 = new Example2();
System.out.println("var is: "+obj2.getValue());
}
}
Output:

var is: 10
Now replace the code of public static void main with the code below and guess answer –

## Example2 obj2 = new Example2(77);

System.out.println("var is: "+obj2.getValue());
Output:

var is: 77
Explanation: you must be wondering why the answer is 77- Let me explain why is it so – Observe
that while creating object I have passed 77 as a parameter inside parenthesis, that’s why
instead of default one, parameterized constructor with integer argument got invoked, where in
I have assigned the argument value to variable var.

Again, replace the code with the below code and try to find the answer –

## Example2 obj3 = new Example2();

Example2 obj2 = new Example2(77);
System.out.println("var is: "+obj3.getValue());
Output:

var is: 10
Important Point to Note: If you are defining parametrised constructor then you may ran into
trouble. Handle them with care :)
What kind of trouble? Lets have a look at the code below:

class Example3
{
private int var;
public Example3(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example3 myobj = new Example3();
System.out.println("value of var is: "+myobj.getValue());
}
}
Output: It will throw a compilation error!!. The reason is when you don’t define any
constructor in your class, compiler defines default one for you, however when you declare any
constructor (in above example I have already defined a parameterized constructor), compiler
doesn’t do it for you.
54

Since I have defined a constructor in above code, compiler didn’t create default one. While
creating object I am invoking default one, which doesn’t exist in above code. The code gives an
Page

compilation error.
If we remove the parametrised constructor from the code above then the code would run fine
because, java would generate the default constructor if it doesn’t find any in the code.

Constructor Chaining
Constructor chaining is nothing but a scenario where in one constructor calls the constructor of
its super class implicitly or explicitly. Suppose there is a class which inherits another class, in
this case if you create the object of child class then first super class(or parent class) constructor
will be invoked and then child class constructor will be invoked.

## Have a look at the example below:

class Human
{
String s1, s2;
public Human()
{
s1 ="Super class";
s2 ="Parent class";
}
public Human(String str)
{
s1= str;
s2= str;
}
}
class Boy extends Human
{
public Boy()
{
s2 ="Child class";
}
public void disp()
{
System.out.println("String 1 is: "+s1);
System.out.println("String 2 is: "+s2);
}
public static void main(String args[])
{
Boy obj = new Boy();
obj.disp();
}
}
Output:

## String 1 is: Super class

String 2 is: Child class
Explanation of the example:
Human is a super class of Boy class. In above program I have created an object of Boy class, As
per the rule super class constructor (Human()) invoked first which set the s1 & s2 value, later
child class constructor(Boy()) gets invoked, which overridden s2 value.

Note: Whenever child class constructor gets invoked it implicitly invokes the constructor of
parent class. In simple terms you can say that compiler puts a super(); statement in the child
55

Page
Question you may have: In the above example no-arg constructor of super class invoked, I want
to invoke arg constructor(Parameterized).

Its so simple.

## Note: super() should be the first statement in the constructor.

public Boy()
{
super("calling super one");
s2 ="Child class";
}
Understood till now – Here are few more points about
constructors
1. Every class has a constructor whether it’s normal one or a abstract class.
2. As stated above, constructor are not methods and they don’t have any return type.
3. Constructor name and class name should be the same.
4. Constructor can use any access specifier, they can be declared as private also. Private constructors
are possible in java but there scope is within the class only.
5. Like constructors method can also have name same as class name, but still they have return
type, though which we can identify them that they are methods not constructors.
6. If you don’t define any constructor within the class, compiler will do it for you and it will create a
constructor for you.
7. this() and super() should be the first statement in the constructor code. If you don’t mention
them, compiler does it for you accordingly.
8. Constructor overloading is possible but overriding is not possible. Which means we can have
overloaded constructor in our class but we can’t override a constructor.
9. Constructors can not be inherited.
10. If Super class doesn’t have a no-arg(default) constructor then compiler would not define a default
one in child class as it does in normal scenario.
11. Interfaces do not have constructors.
12. Abstract can have constructors and these will get invoked when a class, which implements
interface, gets instantiated. (i.e. object creation of concrete class).
13. A constructor can also invoke another constructor of the same class – By using this(). If you wanna
invoke a arg-constructor then give something like: this(parameter list).

## THE MAIN DIFFERENCE IS

1.Constructor are used to initialize the state of object,where as method is expose the behaviour of
object.
2.Constructor must not have return type where as method must have return type.
3.Constructor name same as the class name where as method may or may not the same class
name.
4.Constructor invoke implicitly where as method invoke explicitly.
5.Constructor compiler provide default constructor where as method compiler does't provide.
56
Page
Static and dynamic binding in java
Static and Dynamic Binding in Java
Association of method definition to the method call is known as binding. There are two types of
binding: Static binding and dynamic binding. Lets discuss them one by one.

## Static Binding or Early Binding

The binding which can be resolved at compile time by compiler is known as static or early
binding. All the static, private and final methods have always been bonded at compile-
time . Why binding of Static, final and private methods is always a static binding? You would
understand it better after reading dynamic binding. Still let me explain this – Compiler knows
that all such methods cannot be overridden and will always be accessed by object of local class.
Hence compiler doesn’t have any difficulty to determine object of class (local class for sure).
That’s the reason binding for such methods is static.

## Static binding example

class Human{
....
}
class Boy extends Human{
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
Boy obj1 = new Boy();
obj1.walk();
}
}
Here we have created an object of Boy class and calling the method walk() of the same class.
Since nothing is ambiguous here, compiler would be able to resolve this binding during compile-
time, such kind of binding is known as static binding.

## Dynamic Binding or Late Binding

When compiler is not able to resolve the call/binding at compile time, such binding is known as
Dynamic or late Binding. Overriding is a perfect example of dynamic binding as in overriding
both parent and child classes have same method. Thus while calling the overridden method, the
compiler gets confused between parent and child class method(since both the methods have
same name).

## Dynamic binding example

Here Human is a super class and Boy is a child class since Boy extends Human. Both these classes
have a same method void walk(). Since we have assigned the parent class reference to the child
class object, during call of walk() method the compiler would not be able to decide
57

which walk() method to call. It will be confused between the walk() method of Human class
Page
and walk() method of Boy class. Such kind of bindings are known as dynamic binding as compiler
figures out the object type in runtime.

package beginnersbook.com;
class Human{
public void walk()
{
System.out.println("Human walks");
}
}
class Boy extends Human{
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
//Reference is of parent class
Human myobj = new Boy();
myobj.walk();
}
}
Output:

Boy walks

## Static Binding vs Dynamic Binding

Lets discuss the difference between static and dynamic binding in Java.

## 1. Static binding happens at compile-time while dynamic binding happens at runtime.

2. Binding of private, static and final methods always happen at compile time since these methods
cannot be overridden. Binding of overridden methods happen at runtime.
3. Java uses static binding for overloaded methods and dynamic binding for overridden methods.

That’s all I have regarding static and dynamic binding in java. Let me know if you have any
questions regarding it.
58
Page
String literal VS String object
A String literal is a Java language concept. This is a String literal:
"a String literal"
A String object is an individual instance of the java.lang.String class.
String s1 = "abcde";
String s2 = new String("abcde");
String s3 = "abcde";
All are valid, but have a slight difference. s1 will refer to an interned String object. This means, that the
character sequence "abcde" will be stored at a central place, and whenever the same literal "abcde" is
used again, the JVM will not create a new String object but use the reference of the cached String.
s2 is guranteed to be a new String object, so in this case we have:
s1 == s2 // is false
s1 == s3 // is true
s1.equals(s2) // is true
What is String literal and String Pool
Since String is one of the most used type in any application, Java designer took a step further to optimize uses
of this class. They know that Strings will not going to be cheap, and that's why they come up with an idea
to cache all String instances created inside double quotes e.g. "Java". These double quoted literal is known
as String literal and the cache which stored these String instances are known as as String pool. In earlier version
of Java, I think up-to Java 1.6 String pool is located in permgen area of heap, but in Java 1.7 updates its moved
to main heap area. Earlier since it was in PermGen space, it was always a risk to create too many String object,
because its a very limited space, default size 64 MB and used to store class metadata e.g. .class files. Creating
too many String literals can cause java.lang.OutOfMemory: permgen space. Now because String pool is moved
to a much larger memory space, it's much more safe. By the way, don't misuse memory here, always try to
minimize temporary String object e.g. "a", "b" and then "ab". Always use StringBuilder to deal with temporary
String object.

## Difference between String literal and String object

At high level both are String object, but main difference comes from the point that new() operator always
creates a new String object. Also when you create String using literal they are interned. This will be much more
clear when you compare two String objects created using String literal and new operator, as shown in below
example :
59
Page
String a = "Java";
String b = "Java";
System.out.println(a == b); // True

Here two different objects are created and they have different references:

## String c = new String("Java");

String d = new String("Java");
System.out.println(c == d); // False

Similarly when you compare a String literal with an String object created using new() operator
using == operator, it will return false, as shown below :

String e = "JDK";
String f = new String("JDK");
System.out.println(e == f); // False

In general you should use the string literal notation when possible. It is easier to read and it gives the compiler a
chance to optimize your code. By the way any answer to this question is incomplete until you explain what
is String interning, so let's see that in next section.

Java.html#ixzz4WNcWLvoj
60
Page
JAVA API
Java application programming interface (API) is a list of all classes that are part
of the Java development kit (JDK). It includes all Java packages, classes, and
interfaces, along with their methods, fields, and constructors. These prewritten
classes provide a tremendous amount of functionality to a programmer. A
programmer should be aware of these classes and should know how to use
them.
Straight from Wikipedia:
down In computer science, an application programming interface (API) is an interface that defines
vote
acc epted
the ways by which an application program may request services from libraries
Java contains many libraries in those packages (Swing, etc.), and the API is the interface by
which we request services (perform actions, etc.).
61
Page
What are Packages in java and how to use
them?
BY CHAITANYA SINGH | FILED UNDER: OOPS CONCEPT

## Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub

packages. Many implementations of Java use a hierarchical file system to manage source and
class files. It is easy to organize class files into packages. All we need to do is put related class
files in the same directory, give the directory a name that relates to the purpose of the classes,
and add a line to the top of each class file that declares the package name, which is the same
as the directory name where they reside.

In java there are already many predefined packages that we use while programming.

## For example: java.lang, java.io, java.util etc.

However one of the most useful feature of java is that we can define our own packages

## Advantages of using a package

Before discussing how to use them Let see why we should use packages.

 Reusability: Reusability of code is one of the most important requirements in the software
industry. Reusability saves time, effort and also ensures consistency. A class once developed can
be reused by any number of programs wishing to incorporate the class in that particular program.
 Easy to locate the files.
 In real life situation there may arise scenarios where we need to define files of the same name.
This may lead to “name-space collisions”. Packages are a way of avoiding “name-space collisions”.

Types of package:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as
built-in packages.

Defining a Package:
This statement should be used in the beginning of the program to include that program in that
particular package.
package <package name>;

Example:

package tools;
62

## public class Hammer {

public void id ()
Page

{
System.out.println ("Hammer");
}
}
Points to remember:
1. At most one package declaration can appear in a source file.
2. The package declaration must be the first statement in the unit.

Naming conventions:
A global naming scheme has been proposed to use the internet domain names to uniquely
identify packages. Companies use their reversed Internet domain name in their package names,
like this:
com.company.packageName

## com.myPackage1.myPackage2 myNewClass = new com.myPackage1.myPackage2();

However this method is very time consuming. So normally we use the second method.

2. We use the “import” keyword to access packages. If you say import com.myPackage1.myPackage2,
then every time we type “myPackage2”, the compiler will understand that we
mean com.myPackage1.myPackage2. So we can do:

import com.myPackage1.myPackage2;
class myClass {
myPackage2 myNewClass= new myPackage2 ();

}
There are two ways of importing a package:
Importing only a single member of the package

## //here ‘subclass’ is a java file in myPackage2

import com.myPackage1.myPackage2.subClass;
class myClass {
subClass myNewClass= new subClass();

}
Importing all members of a package.

import com.myPackage1.*;
import java.sql.* ;
Also, when we use *, only the classes in the package referred are imported, and not the classes
in the sub package.

## The Java runtime automatically imports two entire packages by default:

The java.lang package and the current package by default (the classes in the current
folder/directory).
63

Points to remember:
Page

## 1. Sometimes class name conflict may occur. For example:

There are two packages myPackage1 and myPackage2.Both of these packages contains a class
with the same name, let it be myClass.java. Now both this packages are imported by some other
class.

import myPackage1.*;
import myPackage2.*;
This will cause compiler error. To avoid these naming conflicts in such a situation, we have to
be more specific and use the member’s qualified name to indicate exactly
which myClass.java class we want:

## myPackage1.myClass myNewClass1 = new myPackage1.myClass ();

myPackage2.myClass myNewClass2 = new myPackage1.myClass ();
2. While creating a package, which needs some other packages to be imported, the package
statement should be the first statement of the program, followed by the import statement.

## Compiling packages in java:

The java compiler can place the byte codes in a directory that corresponds to the package
declaration of the compilation unit. The java byte code for all the classes(and interfaces)
specified in the source files myClass1.java and myClass2.java will be placed in the directory
named myPackage1/myPackage2 , as these sources have the following package declaration

package myPackage1.myPackage2;
The absolute path of the myPackage1/myPackage2 directory is specified by using the –d
(destination directory) option when compiling with the javac compiler.

Assume that the current directory is /packages/project and all the source files are to be found
here,the command,

## javac –d .file1.java file2.java

Issued in the working directory will create ./ myPackage1/myPackage2(and any sub directories
required) under the current directory, and place the java byte code for all the classes(and
interfaces) in the directories corresponding to the package names. The dot (.) after the –d
option denotes the current directory. Without the –d option, the default behaviors of the java
compiler is to place all the class files in the current directory rather than the appropriate sub
directories.

## How do we run the program?

Since the current directory is /packages/project and we want to run file1.java,the fully qualified
name of the file1 class must be specified in the java command,

java myPackage1.myPackage2.file1
Classpath :
It is a environmental variable, which contains the path for the default-working directory (.).
The specific location that java compiler will consider, as the root of any package hierarchy is,
controlled by Classpath

Access Specifiers
64

##  private: accessible only in the class

 no modifier: so-called “package” access — accessible only in the same package
Page

##  protected: accessible (inherited) by subclasses, and accessible by code in same package

 public: accessible anywhere the class is accessible, and inherited by subclasses

## Notice that private protected is not syntactically legal.

References:
The Complete Reference- JAVA 2, Herbert Schildt
A Programmer Guide to Java Certification (Second Edition)
65
Page
Java 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.

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it
is safe and will result in an order.

## Important Constructors of StringBuffer class

1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.

## 2. StringBuffer(String str): creates a string buffer with the specified string.

3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.

## StringBuffer versus String

Java provides the StringBuffer and String classes, and the String class is used to manipulate
character strings that cannot be changed. Simply stated, objects of type String are read only and
immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster
than String when performing simple concatenations. In String manipulation code, character
strings are routinely concatenated. Using the String class, concatenations are typically performed
as follows:

## String str = new String ("Stanford ");

str += "Lost!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that
looks like this:

## StringBuffer str = new StringBuffer ("Stanford ");

str.append("Lost!!");
66
Page
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is
same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

## Important Constructors of StringBuilder class

1. StringBuilder(): creates an empty string Builder with the initial capacity of 16.

## 2. StringBuilder(String str): creates a string Builder with the specified string.

3. StringBuilder(int length): creates an empty string Builder with the specified capacity as
length.

First lets see the similarities: Both StringBuilder and StringBuffer are mutable. That means you
can change the content of them, with in the same location.
Differences: StringBuffer is mutable and synchronized as well. Where as StringBuilder is mutable
but not synchronized by default.
Meaning of synchronized (synchronization): When some thing is synchronized, then multiple
threads can access, and modify it with out any problem or side effect. StringBuffer is
synchronized, so you can use it with multiple threads with out any problem.
Which one to use when? StringBuilder : When you need a string, which can be modifiable,
and only one thread is accessing and modifying it. StringBuffer : When you need a string,
which can be modifiable, and multiple threads are accessing and modifying it.
Note : Don't use StringBuffer unnecessarily, i.e., don't use it if only one thread is modifying and
accessing it because it has lot of locking and unlocking code for synchronization which will
unnecessarily take up CPU time. Don't use locks unless it is required.
67
Page
Java Language Keywords
Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your

programs. The keywordsconst and goto are reserved, even though they are
not currently used. true, false, and null might seem like

## keywords, but they are actually literals; you

cannot use them as identifiers in your
programs.
abstract continue for new switch
*** default * package synchronized
assert goto
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

## Keyword vs Reserved (sure)

Java comes with total 53 keywords words that cannot be used in
programming.
1. 48 Keywords as on JDk 1.5 release (from JDK 1.5 to 1.8 nothing is added to list).
2. 2 Reserved words of "const" and "goto".
3. 3 Literals of true, false and null.
Let us go in detail on Keyword vs Reserved word Java
.
1. Keywords: Keywords has special meaning (functionality) to the
compiler. For this reason they cannot be used as identifiers in coding.
2. Reserved words: When Java was developed Designers wanted to
eliminate two words const and goto. Thinking so, they removed them
from the Java language and released the first version JDK 1.0 (in the
year 1995). But still they were doubtful whether a language can exist
without these two words in future; in the sense, they may be required
in future versions. For this reason, const and goto were placed
in reserved list. That is, they may be brought back into the Java
68

## language anytime in future. Right now as on JDK 1.8, Java proved a

language can exist without these two words.
Page
Ofcourse, const place is taken by final keyword in Java. goto is against
to structured programming language where with goto, the
Programmer looses control over the flow or the structure of coding.
3. Literals: The literals also cannot be used as identifiers but can be given
as values to identifiers (like boolean b1 = true).
Some people use keyword and reserved word interchangeably
treating as one and the same. It may be true in other languages
but in Java, both are very different.
69
Page
Final Keyword In Java – Final variable,
Method and Class
BY CHAITANYA SINGH | FILED UNDER: OOPS CONCEPT

In this tutorial we will learn the usage of final keyword. final keyword can be used along with
variables, methods and classes. We will cover following topics in detail.

## Final keyword has a numerous way to use:

 A final class cannot be subclassed.
 A final method cannot be overridden by subclasses
 A final variable can only be initialized once

1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it
is initialized. Lets have a look at the below code:

class Demo{

## final int MAX_VALUE=99;

void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
Output:

## Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The final field Demo.MAX_VALUE cannot be assigned

at beginnersbook.com.Demo.myMethod(Details.java:6)
at beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the value of a final
variable “MAX_VALUE”.

## Blank final variable

A final variable that is not initialized at the time of declaration is known as blank final variable.
We must initialize the blank final variable in constructor of the class otherwise it will throw a
compilation error (Error: variable MAX_VALUE might not have been initialized).

## This is how a blank final variable is used in a class:

70
Page

class Demo{
//Blank final variable
final int MAX_VALUE;

Demo(){
//It must be initialized in constructor
MAX_VALUE=100;
}
void myMethod(){
System.out.println(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
Output:

100
Whats the use of blank final variable?
Lets say we have a Student class which is having a field called Roll No. Since Roll No should not
be changed once the student is registered, we can declare it as a final variable in a class but we
cannot initialize roll no in advance for all the students(otherwise all students would be having
same roll no). In such case we can declare roll no variable as blank final and we initialize this
value during object creation like this:

class StudentData{
//Blank final variable
final int ROLL_NO;

StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Output:

Roll no is:1234
More about blank final variable at StackOverflow and Wiki.

## Uninitialized static final variable

A static final variable that is not initialized during declaration can only be initialized in static
block. Example:

class Example{
//static blank final variable
static final int ROLL_NO;
static{
71

ROLL_NO=1230;
}
Page

## public static void main(String args[]){

System.out.println(Example.ROLL_NO);
}
}
Output:

1230

2) final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it.

Example:

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}

## class ABC extends XYZ{

void demo(){
System.out.println("ABC Class Method");
}

## public static void main(String args[]){

ABC obj= new ABC();
obj.demo();
}
}
The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: This program would run
fine as we are not overriding the final method. That shows that final methods are inherited but
they are not eligible for overriding.

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}

## class ABC extends XYZ{

public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
Output:

## XYZ Class Method

3) final class
We cannot extend a final class. Consider the below example:

72

}
Page

## class ABC extends XYZ{

void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
Output:

## The type ABC cannot subclass the final class XYZ

Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be
changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and
finalize is a method that is called by JVM during garbage collection.
73
Page
Java - String valueOf() Method

Previous Page
Next Page

Description
This method has the following variants, which depend on the passed parameters.
This method returns the string representation of the passed argument.

##  valueOf(char c) − Returns the string representation of the char argument.

 valueOf(char[] data) − Returns the string representation of the char array argument.

 valueOf(char[] data, int offset, int count) − Returns the string representation of a
specific subarray of the char array argument.

##  valueOf(Object obj) − Returns the string representation of the Object argument.

Syntax
Here is the syntax of this method −

## static String valueOf(boolean b)

or
static String valueOf(char c)
or
static String valueOf(char[] data)
or
static String valueOf(char[] data, int offset, int count)
or
static String valueOf(double d)
or
static String valueOf(float f)
or
static String valueOf(int i)
74

or
static String valueOf(long l)
or
Page

## static String valueOf(Object obj)

Parameters
Here is the detail of parameters −

##  See the description.

Return Value
 This method returns the string representation.

Example
import java.io.*;
public class Test {

## public static void main(String args[]) {

double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };

## System.out.println("Return Value : " + String.valueOf(d) );

System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) );
}
}

## This will produce the following result −

Output
Return Value : 1.02939939939E8
Return Value : true
Return Value : 1232874
Return Value : abcdefg
75
Page
Integer.parseInt VS Integer.valueOf
up Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted
vote264down exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns
a new Integer() object whereas parseInt(String) returns a primitive int.
vote acce pted

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also
use this eyesore:
Integer k = Integer.valueOf(Integer.parseInt("123"))
Now, if what you want is the object and not the primitive, then using valueOf(String) may be
more attractive than making a new object out of parseInt(String) because the former is
consistently present across Integer, Long, Double, etc.
76
Page