You are on page 1of 62

lOMoARcPSD|17471924

UNIT- I : Fundamentals of Java Technology and Programming

1 Features of Java
There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple
and easy to understand.
1.Simple 2.Object-Oriented 3.Platform independent 4.Secured 5.Robust
6.Architecture neutral 7.Portable 8.Dynamic 9.Interpreted 10.High Performance 11.Multithreaded
1.1 Simple
According to Sun, Java language is simple because:
 syntax is based on C++ (so easier for programmers to learn it after C++).
 removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage Collection in java.
1.2 Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that incorporates both
data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and maintenance by providing
some rules.
Basic concepts of OOPs are:
Object ,Class, Inheritance, Polymorphism, Abstraction, Encapsulation

1.3 Platform Independent


A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs on the top
of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is compiled by the
compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).

1.4 Secured
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Classloader: adds security by separating the package for the classes of the local file system from those that are imported
from network sources.
Bytecode Verifier: checks the code fragments for illegal code that can violate access right to objects.
Security Manager: determines what resources a class can access such as reading and writing to the local disk.
These security are provided by java language. Some security can also be provided by application developer through SSL,
JAAS, Cryptography etc.

1.5 Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java.
All these points makes java robust.

1.6 Architecture-neutral
There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

1.7 Portable
We may carry the java bytecode to any platform.

1.8 High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a
compiled language (e.g., C++)

1.9 Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access
files by calling the methods from any machine on the internet.

1.10 Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at
once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web applications etc.

2. Java Technologies: JCP and JSR


The JCP program holds the responsibility for the development of Java technology. As an open, inclusive organization of
active members and non-member public input, it primarily guides the development and approval of Java technical
specifications. Anyone can register and join the JCP and have a part in its process, and you don't even have to join to
contribute as a public participant.

The work of the Java Community under the JCP program helps to ensure Java technology's standard of stability and cross-
platform compatibility, enabling it to operate on hundreds of millions of devices, from desktop computers to consumer
electronics to industrial robots.
In detail, the procedures of the JCP are complex, but in general they follow a simple, time-proven path, of course, still
open to revision. Three introductory pages may help you understand the process and answer your initial questions:

Timeline View Take a look at the overall schedule of events for the Java Specification Request (JSR) process
Glossary The JCP is built on a specific language of its own, and here are definitions to the terms you will need to know.
The JCP has gone through many revisions for improvement since its founding on December 8, 1998. The most current and
important procedures for working with the JCP is available at The Java Community Process Program. The Java
Community Process Program page is a good reference for anyone who plans to become a JCP Member and wants to
review the process and procedures in detail. Go to JCP Procedures Overview

Just as important, the JCP program continually grows the platform's specification portfolio to meet the emerging
technology needs of developers and organizations globally who depend on Java technology.

Java Specification Requests (JSRs) are the actual descriptions of proposed and final specifications for the Java platform.
At any one time there are numerous JSRs moving through the review and approval process.
A simple way to stay up to date and track the JSRs in each stage of review is to join the Mailing List. As a Mailing List
member, you can automatically receive emails on JSRs as they move through the stages in review.
Of course, at any time, you can see a list of all JSRs, by visiting the Java Specification Requests list. Using the links near
the top of the page, you can sort the list by JSR ID number, Title, and the Spec Lead Company Name.

3. Variables and Data Types in Java


3.1 Variable is a name of memory location. There are three types of variables in java: local, instance and static.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a
combination of "vary + able" that means its value can be changed.

int data=50;//Here data is variable


1) Local Variable : A variable which is declared inside the method is called local variable.
2) Instance Variable: A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.
3) Static variable: A variable that is declared as static is called static variable. It cannot be local.
Example
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
3.2 Data Types in Java A data type is a classification of data, which can store a specific type of information.
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
Primitive data types
Non-primitive data types

Data Type Default Value Default size

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

boolean false 1 bit


char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte

3.2.1 Eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a
keyword. Let us now look into the eight primitive data types in detail.
byte
Byte data type is an 8-bit signed two's complement integer. Minimum value is -128 (-2^7). Maximum value is 127
(inclusive)(2^7 -1). Default value is 0. Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
short
Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15). Maximum value is 32,767
(inclusive) (2^15 -1). Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an
integer Default value is 0.
Example: short s = 10000, short r = -20000

int
Int data type is a 32-bit signed two's complement integer.. Minimum value is - 2,147,483,648 (-2^31). Maximum value is
2,147,483,647(inclusive) (2^31 -1). Integer is generally used as the default data type for integral values unless there is a
concern about memory.. The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1). This type is used when a wider range than int is
needed. Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of
floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data
type for decimal values, generally the default choice. Double data type should never be used for precise values such as
currency. Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information.There are only two possible values: true and false. This data type is
used for simple flags that track true/false conditions. Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Maximum value is '\uffff' (or 65,535
inclusive). Char data type is used to store any character
Example: char letterA = 'A'
3.2.2 Non-primitive data types are not defined by the programming language, but are instead created by the programmer.
They are sometimes called "reference variables," or "object references," since they reference a memory location, which
stores the data. In the Java programming language, non-primitive data types are simply called "objects" because they are

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

created, rather than predefined. While an object may contain any type of data, the information referenced by the object
may still be stored as a primitive data type. Reference variables are created using defined constructors of the classes. They
are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example,
Employee, Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");

4. Keywords
The Java programming language has total of 50 reserved keywords which have special meaning for the compiler and cannot be
used as variable names. Following are some noteworthy points regarding Java keywords
1. const and goto are reserved words but not used.
2. true, false and null are literals, not keywords.
3. all keywords are in lower-case.

The following table shows the keywords grouped by category:


Cate Keywords
gory
Access private, protected, public
modifie
rs
Class, abstract, class, extends, final, implements, interface, native,new, sta
method tic, strictfp, synchronized, transient, volatile
,
variabl
e
modifie
rs
Flow break, case, continue, default, do, else, for, if, instanceof,return, swit
control ch, while
Packag import, package
e
control
Primitiv boolean, byte, char, double, float, int, long, short
e types
Error assert, catch, finally, throw, throws, try
handlin
g
Enumer enum
ation
Others super, this, void
Unused const, goto

5. Scoping rule The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block. The lifetime of a variable refers

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

to how long the variable exists before it is destroyed. Destroying variables refers to deallocating the memory that was
allotted to the variables when declaring it.
5.1 Instance variables
Instance variables are those that are defined within a class itself and not in any method or constructor of the class. They
are known as instance variables because every instance of the class (object) contains a copy of these variables. The scope
of instance variables is determined by the access specifier that is applied to these variables. We have already seen about
it earlier. The lifetime of these variables is the same as the lifetime of the object to which it belongs. Object once created
do not exist for ever. They are destroyed by the garbage collector of Java when there are no more reference to that
object. We shall see about Java's automatic garbage collector later on.
5.2 Argument variables
These are the variables that are defined in the header oaf constructor or a method. The scope of these variables is the
method or constructor in which they are defined. The lifetime is limited to the time for which the method keeps
executing. Once the method finishes execution, these variables are destroyed.
5.3 Local variables
A local variable is the one that is declared within a method or a constructor (not in the header). The scope and lifetime
are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can be applied to instance
variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined in bocks life an if block and
an else block. The scope and is the same as that of the block itself.
5.4 Static Variables
In java, only class variables can be declared as static i.e. Single copy of static variable must be available to all the
objects of class and should be accessible directly by using class name.
You cannot declare a static variable within ANY method. Static variables have to be declared at a class level .

6. Automatic Type Conversion


There are two kinds of conversion: Widening or Narrowing

6.1 Widening or Implicit or Automatic conversions:


An implicit conversion means that a value of one type is changed to a value of another type without any special directive from the
programmer. Automatic Type casting take place when,
the two types are compatible
the target type is larger than the source type
A char can be implicitly converted to an int, a long, a float, or a double. For example, the following will compile without error:
char c = 'a';
int k = c;
long x = c;
float y = c;
double d = c;

For the other (numeric) primitive types, the basic rule is that implicit conversions can be done from one type to another if the range
of values of the first type is a subset of the range of values of the second type. For example, a byte can be converted to a short, int,
long or float; a short can be converted to an int, long, float, or double, etc.

6.2 Narrowing or Explicit conversions:


Explicit conversions are done via casting. The name of the type to which you want a value converted is given, in parentheses, in
front of the value. For example, the following code casts a value of type double to a value of type int, and a value of type double to a
value of type short:

double d = 5.6;
int k = (int)d;
short s = (short)(d * 2.0);

Casting can be used to convert among any of the primitive types except boolean. Please note that casting can lose information; for
example, floating-point values are truncated when they are cast to integers.

7. Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is
created. After creation, its length is fixed.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration,
numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

7.1 One Dimensional Array


One dimensional array is a list of variables of same type that are accessed by a common name.
To create an array, you need to perform two steps :

1) Declare the array :

To declare an array below is a general form or syntax.

type varName[];

Where type is valid data type in java and varName is a name of an array.

Example : int iarr[];

2) Allocate space for its elements :

To allocate space for an array element use below general form or syntax.

varName = new type[size];

Where varName is the name of the array and type is a valid java type and sizespecifies the number of elements in the
array.

Example : iarr = new int[10];

Above statement will create an integer of an array with ten elements that can by accessed by iarr.

Example:

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
{System.out.println(a[i]);

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}}
Test it Now
Output: 10
20
70
40
50

7.2 Multidimensional array in java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
1. dataType[][] arrayRefVar; (or)
2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

class Testarray3{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}}
Test it Now
Output:1 2 3
245
445

8. Operators Precedence & Associativity

A Java operator is a special symbol that performs specific operation on one, two, or three operands depending upon the
type of the operator and returns a result.
Java provides a rich set of operators that are classified on two bases. First, on the basis of number of operands an
operator performs upon. Second, on the type or nature of operation an operator performs.
By first classification, Java operators can be unary, binary, or ternary. Unary operators operate on one operand e.g., ++,
and --. Binary operators operator on two operands. All arithmetic operators are example of binary operators. Third,
special type operator is ternary operator. Ternary operator operates on three operands. Java has only one ternary
operator, which is also called conditional operator. It is a combination of two symbols ? and :.
Another classification is based on the type of operation they perform. On the basis of the type of operation operators
can be classified in following categories:
Arithmetic Operators
Increment Decrement Operators
Bitwise Operators
Relational Operators
Logical Operators
Assignment Operators
Miscellaneous Operators
Java Operators Precedence and Associativity
Java operators have two properties those are precedence, and associativity. Precedence is the priority order of an
operator, if there are two or more operators in an expression then the operator of highest priority will be executed first
then higher, and then high.
if all operators in an expression have same priority? In that case the second property associated with an operator comes
into play, which is associativity. Associativity tells the direction of execution of operators that can be either left to
right or right to left. For example, in expression a = b = c = 8 the assignment operator is executed from right to left that
means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You can parenthesize this
expression as (a = (b = (c = 8))).

Table 1: Java operators - precedence chart highest to lowest


Precedence Operator Description Associativity
1 [] array index Left -> Right
() method call
. member access
2 ++ pre or postfix increment Right -> Left
-- pre or postfix decrement
+- unary plus, minus
~ bitwise NOT
! logical NOT
3 (type cast) type cast Right -> Left
new object creation
4 * multiplication Left -> Right

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

/ division
% modulus (remainder)
5 +- addition, subtraction Left -> Right
+ string concatenation
6 << left shift Left -> Right
>> signed right shift
>>> unsigned or zero-fill right shift
7 < less than Left -> Right
<= less than or equal to
> greater than
>= greater than or equal to
instanceof reference test
8 == equal to Left -> Right
!= not equal to
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ?: conditional (ternary) Right -> Left
15 = assignment and short hand assignment Right -> Left
+= operators
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
>>>=

9. Expression
An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax
of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below:

int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);

int result = 1 + 2; // result is now 3


if (value1 == value2)
System.out.println("value1 == value2");

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence =
0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is
an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type
required by one part of the expression matches the data type of the other. Here's an example of a compound expression:

1 * 2 * 3

Operators that have a higher precedence get evaluated first. In this particular example, the order in which the expression is evaluated is
unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply
the multiplications. When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first.
This practice makes code easier to read and to maintain.

10. Flow Control


The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control
flow statements, however, break up the flow of execution by employing decision making, looping, and branching,
enabling your program to conditionally execute particular blocks of code. There are three main categories of control flow
statements;
1. Selection statements: if, if-else and switch.
2. Loop statements: while, do-while and for.
3. Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution
10.1 SELECTION STATEMENTS
10.1.1 The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is
skipped and execution continues with the rest of the program. You can either have a single statement or a block of code
within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
10.1.1 The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the
else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the
conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>

10.1.2 Switch Statement


The switch case statement, also called a case statement is a multi-way branch with several choices. When the switch
statement executes, it compares the value of the controlling expression to the values of each case label. The program will
select the value of the case label that equals the value of the controlling expression and branch down that path to the
end of the code block. If none of the case label values match, then none of the codes within the switch statement code
block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested
switch within a case block of an outer switch. Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924


case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the
middle of the switch statement code block, you must insert a break statement, which causes the program to continue
executing after the current code block.
10.2 LOOP/ITERATION STATEMENTS
10.2.1 While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is true. You
can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing
expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
<statements>
10.2.2 Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the
beginning. This ensures that the loop will be executed at least once.
The syntax of the do-while loop is
do
<loop body>
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.
public class DoWhileLoopDemo {

public static void main(String[] args) {


int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter
controlled loop.
The syntax of the loop is as follows:
10.2.3 for (<initialization>; <loop condition>; <increment expression>)
<loop body>
The first part of a for statement is a starting initialization, which executes once before the loop begins. The
<initialization> section can also be a comma-separated list of expression statements. The second part of a for statement
is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the
first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the
instructions that are repeated each time the program executes the loop. The final part of the for statement is an
increment expression that automatically executes after each repetition of the loop body.
10.3 TRANSFER STATEMENTS
10.3.1 Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the
nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the
loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

10.3.2 Break Statement


The break statement has two forms: labeled and unlabeled .An unlabeled break statement terminates the
innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is
transferred to the statement immediately following the labeled (terminated) statement.
Example
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
10
20

10.3.3 Return Statement


At any time in a method the return statement can be used to cause execution to branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which it is executed. As soon as return is executed,
control passes back to the caller.
Syntax:
return;
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
return returnValue;
The data type of the return value must match the method's declared return type; you can't return an integer value from a
method declared to return a boolean.

10.3.4 try-catch-finally Statement


Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Java try block must be followed by either catch or finally block.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}

Java catch block is used to handle the Exception. It must be used after the try block only.You can use multiple catch
block with a single try. Let's see the solution of above problem by java try-catch block.
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

System.out.println("rest of the code...");


}
}
Test it Now
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block.
Usage of Java finally
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}
}
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...

10.3.5 Assert
"assert" statements are part of the Java assertion feature introduced in Java 1.4. Java assertion feature allows developer
to put "assert" statements in Java source code to help unit testing and debugging.
An "assert" statement has the following format:
assert boolean_expression : string_expression;
When this statement is executed:
If boolean_expression evaluates to true, the statement will pass normally.
If boolean_expression evaluates to false, the statement will fail with an "AssertionError" exception.
If you are using "assert" statements in your Java program for unit testing and debugging, you need to compile and
execute the program with extra command options to use them:
Compilation - "javac -source 1.4 MyClass.java". This tells the compiler to accept source code containing assertions.
Executionn - "java -ea MyClass". This tells the JVM to not skill "assert" statements. "-ea" is the same as "-
enableassertions".

11. New Features from Java 5 to Java 7

Java 5 Java 6

Features added: Features added:


- Support for older win9x versions dropped.
- Generics: provides compile-time (static) type safety for - Scripting lang support: Generic API for integration with
collections and eliminates the need for most typecasts scripting languages, & built-in mozilla javascript rhino
(type conversion). integration
- Metadata: also called annotations; allows language - Dramatic performance improvements for the core
constructs such as classes and methods to be tagged platform, and swing.
with additional data, which can then be processed by
metadata-aware utilities. - Improved web service support through JAX-WS JDBC 4.0
support
- Autoboxing/unboxing: automatic conversions between
primitive types (such as int) and primitive wrapper - Java compiler API: an API allowing a java program to
classes (such as integer). select and invoke a java compiler programmatically.
- Enumerations: the enum keyword creates a typesafe, - Upgrade of JAXB to version 2.0: including integration of
ordered list of values (such as day.monday, day.tuesday, a stax parser.
etc.). Previously this could only be achieved by non-
typesafe constant integers or manually constructed - Support for pluggable annotations
classes (typesafe enum pattern). - Many GUI improvements, such as integration of
- Swing: new skinnable look and feel, called synth. swingworker in the API, table sorting and filtering, and
true swing double-buffering (eliminating the gray-area
- Var args: the last parameter of a method can now be effect).
declared using a type name followed by three dots (e.g.
Void drawtext(string... Lines)). In the calling code any
number of parameters of that type can be used and they
are then placed in an array to be passed to the method,
or alternatively the calling code can pass an array of that
type.
- Enhanced for each loop: the for loop syntax is extended
with special syntax for iterating over each member of
either an array or any iterable, such as the standard
collection classesfix the previously broken semantics of
the java memory model, which defines how threads

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

interact through memory.


- Automatic stub generation for rmi objects.
- Static imports concurrency utilities in package
java.util.concurrent.
- Scanner class for parsing data from various input
streams and buffers.
- Assertions
- StringBuilder class (in java.lang package)
- Annotations

Java 7 Java 7

Features Added: Features Added:

- Upgrade to JDBC 4.1 and Rowset 1.1. - Upgrade class-loader architecture: A method that frees
- XRender pipeline for Java 2D, Create new platform APIs the underlying resources, such as open files, held by a
for 6u10 graphics features, Nimbus look-and-feel for URLClassLoader
Swing, Swing JLayer component, Gervill sound - Concurrency and collections updates: A lightweight
synthesizer. fork/join framework, flexible and reusable
- Upgrade the components of the XML stack to the most synchronization barriers, transfer queues, concurrent
recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS linked double-ended queues, and thread-local pseudo-
2.2. random number generators.
- Enhanced MBeans." Support for dynamically-typed - Internationalization Upgrade: Upgrade on Unicode 6.0,
languages (InvokeDynamic): Extensions to the JVM, the Locale enhancement and Separate user locale and user-
Java language, and the Java SE API to support the interface locale.
implementation of dynamically-typed languages at - More new I/O APIs for the Java platform (NIO.2), NIO.2
performance levels near to that of the Java language filesystem provider for zip/jar archives, SCTP, SDP, TLS
itself 1.2 support.
- Strict class-file checking: Class files of version 51 (SE 7) - Security & Cryptography implemented Elliptic-curve
or later must be verified with the typechecking verifier; cryptography (ECC).
the VM must not fail over to the old inferencing verifier.
- Small language enhancements (Project Coin): A set of
small language changes intended to simplify common,
day-to-day programming tasks: Strings in switch
statements, try-with-resources statements, improved
type inference for generic instance creation ("diamond"),
simplified varargs method invocation, better integral
literals, and improved exception handling (multi-catch).

12. Enhanced For Loop


The usual way to step through all the elements of an array in order is with a "standard" for loop, for example,
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
The so-called enhanced for loop is a simpler way to do this same thing. (The colon in the syntax can be read as "in.")
for (int myValue : myArray) {
System.out.println(myValue);
}
The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection
(Collections are not covered in these pages). It can also be used for arrays, as in the above example, but this is not the
original purpose.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array
in first-to-last order, and you do not need to know the index of the current element. In all other cases, the "standard" for
loop should be preferred.
Example: Java enhanced for loop integer array
class EnhancedForLoop {
public static void main(String[] args) {
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

for (int t: primes) {


System.out.println(t);
}
}
}
Download Enhanced for loop program.
Output of program:

Java enhanced for loop strings


class EnhancedForLoop {
public static void main(String[] args) {
String languages[] = { "C", "C++", "Java", "Python", "Ruby"};

for (String sample: languages) {


System.out.println(sample);
}
}
}

13. Handling Strings


Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings
are treated as objects.The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello
world!'.
As with any other object, you can create String objects by using the new keyword and a constructor. The String class has
11 constructors that allow you to provide the initial value of the string using different sources, such as an array of
characters.
Example

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

public class StringDemo {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This will produce the following result −
Output
hello.
Note − The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity
to make a lot of modifications to Strings of characters, then you should useString Buffer & String Builder Classes.
String Length
Methods used to obtain information about an object are known asaccessor methods. One accessor method that you can
use with strings is the length() method, which returns the number of characters contained in the string object.
The following program is an example of length(), method String class.
Example
public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This will produce the following result −
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with
string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
which results in −
"Hello, world!"
Let us look at the following example −
Example
public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This will produce the following result −
Output
Dot saw I was Tod
Creating Format Strings
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class
method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example,
instead of −
Example
System.out.printf("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the
string " + "is %s", floatVar, intVar, stringVar);
You can write −
String fs;
fs = String.format("The value of the float variable is " + "%f, while the value of the integer " + "variable is %d, and the
string " + "is %s", floatVar, intVar, stringVar);
System.out.println(fs);
String Methods
Here is the list of methods supported by String class −
Sr.No. Method & Description

char charAt(int index)


1
Returns the character at the specified index.

int compareTo(Object o)
2
Compares this String to another Object.

int compareTo(String anotherString)


3
Compares two strings lexicographically.

int compareToIgnoreCase(String str)


4
Compares two strings lexicographically, ignoring case differences.

String concat(String str)


5
Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb)


6 Returns true if and only if this String represents the same
sequence of characters as the specified StringBuffer.

static String copyValueOf(char[] data)


7 Returns a String that represents the character sequence in the
array specified.

static String copyValueOf(char[] data, int offset, int count)


8 Returns a String that represents the character sequence in the
array specified.

boolean endsWith(String suffix)


9
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)


10
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)


11 Compares this String to another String, ignoring case
considerations.

byte getBytes()
12 Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

byte[] getBytes(String charsetName)


13 Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int


dstBegin)
14
Copies characters from this string into the destination character
array.

int hashCode()
15
Returns a hash code for this string.

int indexOf(int ch)


16 Returns the index within this string of the first occurrence of the
specified character.

int indexOf(int ch, int fromIndex)


17 Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.

int indexOf(String str)


18 Returns the index within this string of the first occurrence of the
specified substring.

int indexOf(String str, int fromIndex)


19 Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.

String intern()
20
Returns a canonical representation for the string object.

int lastIndexOf(int ch)


21 Returns the index within this string of the last occurrence of the
specified character.

int lastIndexOf(int ch, int fromIndex)


Returns the index within this string of the last occurrence of the
22
specified character, searching backward starting at the specified
index.

int lastIndexOf(String str)


23 Returns the index within this string of the rightmost occurrence
of the specified substring.

int lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of the
24
specified substring, searching backward starting at the specified
index.

int length()
25
Returns the length of this string.

boolean matches(String regex)


26 Tells whether or not this string matches the given regular
expression.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

boolean regionMatches(boolean ignoreCase, int toffset, String


27 other, int ooffset, int len)
Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int


28 len)
Tests if two string regions are equal.

String replace(char oldChar, char newChar)


29 Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.

String replaceAll(String regex, String replacement


30 Replaces each substring of this string that matches the given
regular expression with the given replacement.

String replaceFirst(String regex, String replacement)


31 Replaces the first substring of this string that matches the given
regular expression with the given replacement.

String[] split(String regex)


32
Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


33
Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)


34
Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)


35 Tests if this string starts with the specified prefix beginning a
specified index.

CharSequence subSequence(int beginIndex, int endIndex)


36 Returns a new character sequence that is a subsequence of this
sequence.

String substring(int beginIndex)


37
Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)


38
Returns a new string that is a substring of this string.

char[] toCharArray()
39
Converts this string to a new character array.

String toLowerCase()
40 Converts all of the characters in this String to lower case using
the rules of the default locale.

String toLowerCase(Locale locale)


41 Converts all of the characters in this String to lower case using
the rules of the given Locale.

42 String toString()

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

This object (which is already a string!) is itself returned.

String toUpperCase()
43 Converts all of the characters in this String to upper case using
the rules of the default locale.

String toUpperCase(Locale locale)


44 Converts all of the characters in this String to upper case using
the rules of the given Locale.

String trim()
45 Returns a copy of the string, with leading and trailing whitespace
omitted.

static String valueOf(primitive data type x)


46 Returns the string representation of the passed data type
argument.

14. Entry Point for Java Programs


In computer programming, an entry point is where control is transferred from the operating system to a computer
program, at which place the processor enters a program or a code fragment and execution begins. In some operating
systems or programming languages, the initial entry is not part of the program but of the runtime library, in which case
the runtime library initializes the program and then the runtime library enters the program. In other cases, the program
may call the runtime library before doing anything when it is entered for the first time, and, after the runtime library
returns, the actual code of the program begins to execute. This marks the transition from load time (and dynamic link
time, if present) to run time.
In simple layouts, programs begin their execution at the beginning, which is common in scripting languages, simple
binary executable formats, and boot loaders. In other cases, the entry point is at some other fixed point, which is
some memory address than can be an absolute address or relative address (offset).
Alternatively, execution of a program can begin at a named point, either with a conventional name defined by the
programming language or operating system, or at a caller-specified name. In many programming languages, notably C,
this named point is a function called main ; as a result, the entry point is often called the main function.
In C, C++, D and Kotlin programs this is a function named main ; in Java it is a static method named main (although the
class must be specified at the invocation time), and in C# it is a static method named Main .
main method in Java is an standard method which is used by JVM to start execution of any Java program. main method is
referred as entry point of Java application which is true in case of core java application but in case of container managed
environment like Servlet, EJB or MIDlet this is not true as these Java programs have there own life-cycle methods
like init(), service() or destory() for Servlet's which is used by container. main method in Java is run by main thread
which is a non daemon thread and Java program runs until main method finishes or any other user thread is running. When we
start JVM by runningjava command we also provide name of class which contains main method, which is later invoked by JVM
to start Java program execution.

Unit-2: Classes, Objects and Streams

1. Class Fundamentals
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
Syntax to declare a class:
class <class_name>{
data member;
method;
}

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or
logical (tengible and intengible). The example of integible object is banking system.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user.
But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is
its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are creating the object of
the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)

public static void main(String args[]){


Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}

1.1 Declaring Objects


When we create class then we are creating new data type. Newly created data type is used to create an Object of that class
type.
Creating object is two step process.

Creation of Object involves two steps –


1. Declaration
2. Allocation and Assigning

Example:
Rectangle myrect1 = new Rectangle();
this statement is used to create an object we are going to break down this statement in two separate statements –
Rectangle myrect1 ;
myrect1 = new Rectangle();
First statement will just create variable myrect1 which will store address of actual object.First Statement will not allocate
any physical memory for an object . Second Statement will create actual object ranndomly at any memory address where
it found sufficient memory.Actual memory address of Object is stored inside myrect1.

1.2 Assigning Object Reference Variable

A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized
with a variable, either the variable name or the reference name may be used to refer to the variable.

Facts about Reference variable


 We can assign value of reference variable to another reference variable.
 Reference Variable is used to store the address of the variable.
 Assigning Reference will not create distinct copies of Objects.
 All reference variables are referring to same Object.

Assigning Object Reference Variables does not –

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

 Create Distinct Objects.


 Allocate Memory
 Create duplicate Copy

Consider This Example –


Rectangle r1 = new Rectangle();
Rectangle r2 = r1;

r1 is reference variable which contain the address of Actual Rectangle Object.


r2 is another reference variable
r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus it does not create duplicate object , nor
does it allocate extra memory.

1.3 Methods and Method Signatures


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.
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}

The syntax shown above includes −


modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional,
method may contain zero parameters.
method body − The method body defines what the method does with the statements.
There are two basic types of methods:
Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).
User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign
to them and perform tasks that you create.
When you want to use (we say invoke) a method, you create a method call to that method. A method call executes the
code inside the method. What the method call looks like depends on the method signature.
The method signature tells us what the method's return type is (int, boolean, String, etc. or void), what the method's
name is and what parameters are required. A parameter is a piece of information the method needs to do its job.
Methods that have no return type
For example, consider this method signature:
public void started()
This method has public access (meaning it can be called from inside or outside the class), its return type is void (meaning
it returns no value) and it has no parameters (there is nothing between the () brackets). So, it's called like this:
started();
Methods that have a return type
Now, consider the method signature:
public Color getColorAt( int x, int y)
This method also has public access, its return type is Color, meaning it will return a Color object (return types can be class
names). The name of the method is getColorAt and it has two parameters, x and y, which are both integers. It might be
called like this:
Color theColor = getColorAt( 200, 300)

1.4 Method Returning Values


A method returns to the code that invoked it when it
 completes all the statements in the method,
 reaches a return statement, or

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

 throws an exception (covered later),


whichever occurs first.
You declare a method's return type in its method declaration. Within the body of the method, you use the return statement
to return the value.
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a
case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
If you try to return a value from a method that is declared void, you will get a compiler error.
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
return returnValue;
The data type of the return value must match the method's declared return type; you can't return an integer value from a
method declared to return a boolean.
The getArea() method in the Rectangle Rectangle class that was discussed in the sections on objects returns an integer:
// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}
This method returns the integer that the expression width*height evaluates to.
The getArea method returns a primitive type. A method can also return a reference type.

1.5 Method with Parameters


The declaration for a method or a constructor declares the number and the type of the arguments for that method or
constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the
amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:
Example:
public double computePayment(double loanAmt, double rate, double futureValue, int numPeriods) {
double interest = rate / 100.0;
double partial1 = Math.pow((1 + interest), - numPeriods);
double denominator = (1 - partial1) / interest;
double answer = (-loanAmt / denominator)- ((futureValue * partial1) / denominator);
return answer;
}
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The
first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the
method body and at runtime will take on the values of the arguments that are passed in.

Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed
in when the method is invoked. When you invoke a method, the arguments used must match the declaration's
parameters in type and order.

Parameter Types
You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as
doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and
arrays.
Here's an example of a method that accepts an array as an argument. In this example, the method creates a
new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y
coordinate):
public Polygon polygonFrom(Point[] corners) {
// method body goes here
}
The terms "arguments" and "parameters" are used interchangeably; they mean the same thing. We use the term formal
parameters to refer to the parameters in the definition of the method. In the example that follows, x and y are the formal
parameters.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

We use the term actual parameters to refer to the variables we use in the method call. In the following example, length
and width are actual parameters.
// Method definition
public int mult(int x, int y)
{
return x * y;
}

// Where the method mult is used


int length = 10;
int width = 5;
int area = mult(length, width);
Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed. You can
change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages,
Java has no mechanism to change the value of an actual parameter. Isn't this very restrictive? Not really. In Java, we can
pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object;
we just can't change what object the handle refers to.

1.6 Variable Arguments in Java


The feature of variable argument has been added in Java 5 since its launch. Still I will write something about varargs.
varargs has been implemented in many languages such as C, C++ etc. These functionality enables to write
methods/functions which takes variable length of arguments. For example the popular printf() method in C. We can call
printf() method with multiple arguments.
printf("%s", 50);
printf("%d %s %s", 250, "Hello", "World");
Varargs was added in Java 5 and the syntax includes three dots … (also called ellipses). Following is the syntax of vararg
method.
public void testVar(int count, String... vargs) { }
Notice the dots … in above code. That mark the last argument of the method as variable argument. Also the vararg must
be the last argument in the method.
Now let us check simple hello world varargs code.
public class HelloWorldVarargs {

public static void main(String args[]) {


test(215, "India", "Delhi");
test(147, "United States", "New York", "California");
}

public static void test(int some, String... args) {


System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
}
In above code, the test() method is taking variable arguments and is being called from main method with number of
arguments.

2. I/O Basics: Byte Stream & Character Stream


Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output
operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output
without having every part of your code understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
Byte Stream : It provides a convenient means for handling input and output of byte.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses
Unicode and therefore can be internationalized.

2.1 Byte Stream Classes


Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream.

These two abstract classes have several concrete classes that handle various devices such as disk files, network
connection etc.

Some important Byte stream classes.


Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method


These classes define several key methods. Two most important are
read() : reads byte of data.
write() : Writes byte of data.

2.2 Character Stream Classes


Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer.

These two abstract classes have several concrete classes that handle unicode character.

Some important Charcter stream classes.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Reading Console Input:We use the object of BufferedReader class to take inputs from the keyboard.

Reading Characters
read() method is used with BufferedReader object to read characters. As this function returns integer type value has we
need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
class CharRead
{
public static void main( String args[])
{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}
Reading Strings
To read string we have to use readLine() function with BufferedReader class's object.
String readLine() throws IOException

Program to take String input from Keyboard in Java

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

import java.io.*;
class MyInput
{
public static void main(String[] args)
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine(); //Reading String
System.out.println(text);
}
}

Program to read from a file using BufferedReader class


import java. Io *;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch (IOException e)
{ e.printStackTrace(); }

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}
}

3.Getting user input

3.1Reading Console Input


In Java, there are 3 ways to read input from the command line environment (also known as the “console”).:
3.1.1 BufferedReader + InputStreamReader (Classic)
3.1.2 Scanner (JDK 1.5)
3.1.3 System.console (JDK 1.6)

3.1.1. Using BufferedReader class


By wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in aBufferedReader, we
can read input from the user in the command line. Here’s an example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");

String name = reader.readLine();


System.out.println("Your name is: " + name);
In the above example, the readLine() method reads a line of text from the command line.
Advantages: The input is buffered for efficient reading.
Drawbacks: The wrapping code is hard to remember.

3.1.2. Using Scanner class


The main purpose of the Scanner class (available since Java 1.5) is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user in the command line. Here’s an example:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your nationality: ");

String nationality = scanner.nextLine();


System.out.print("Enter your age: ");
int age = scanner.nextInt();
Advantages:
1. Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
2. Regular expressions can be used to find tokens.
Drawbacks:
The reading methods are not synchronized.

3.1.3. Using Console class


The Console class was introduced in Java 1.6, and it has been becoming a preferred way for reading user’s input from the
command line. In addition, it can be used for reading password-like input without echoing the characters entered by the
user; the format string syntax can also be used (like System.out.printf()). Here’s an example code snippet:
1 Console console = System.console();
2 if (console == null) {
3 System.out.println("No console: non-interactive mode!");
4 System.exit(0);
5 }
6
7 System.out.print("Enter your username: ");
8 String username = console.readLine();
9
10 System.out.print("Enter your password: ");
11 char[] password = console.readPassword();

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

12
13 String passport = console.readLine("Enter your %d (th) passport number: ", 2);
Advantages:
1.Reading password without echoing the entered characters.
2. Reading methods are synchronized.
3. Format string syntax can be used.
Drawbacks:
Does not work in non-interactive environment (such as in an IDE).
Combined Example Program
For your convenient and reference purpose, we combine the above code snippet into a demo program whose source
code looks like this:
package net.codejava.io;

import java.io.*;
import java.util.*;

public class UserInputConsoleDemo {

public static void main(String[] args) {

// using InputStreamReader
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");

String name = reader.readLine();


System.out.println("Your name is: " + name);
} catch (IOException ioe) {
ioe.printStackTrace();
}

// using Scanner
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your nationality: ");
String nationality = scanner.nextLine();
System.out.println("Your nationality is: " + nationality);

// using Console
Console console = System.console();
if (console == null) {
System.out.println("No console: not in interactive mode!");
System.exit(0);
}
System.out.print("Enter your username: ");
String username = console.readLine();
System.out.print("Enter your password: ");
char[] password = console.readPassword();
System.out.println("Thank you!");
System.out.println("Your username is: " + username);
System.out.println("Your password is: " + String.valueOf(password));

// using Console with formatted prompt


String job = console.readLine("Enter your job: ");

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

String passport = console.readLine("Enter your %d (th) passport number: ", 2);


System.out.println("Your job is: " + job);
System.out.println("Your passport number is: " + passport);
}
}

3.2 Writing Console Output


Console output is most easily accomplished with print() and println() methods, as described earlier. These methods are
defined by the class PrintStream which is the type of object referenced by System.in. Even though System.out is a byte
stream, using it for a simple program output is still acceptable.
Because the PrintStream is an output stream derived from the OutputStream, it also implements the low-level
method write(). Thus, write() can be used to write to the console. The simplest form of write() defined by
the PrintStream is shown below :
void write(int byteval)
This method writes the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits
are written. Following is a short example that uses write() to output the character 'X' followed by a newline to the
screen:
/* Java Program Example - Java Write Console Output
* This program writes the character X followed by newline
* This program demonstrates System.out.write() */

class WriteConsoleOutput
{
public static void main(String args[])
{
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');

}
}
This Java program will produce the following output:

You will not often use write() to perform console output (although doing so might be useful in some situations)
because print() and println() are substantially easier to use.

4. Reading and Writing files

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these
streams represent an input source and an output destination. The stream in the java.io package supports many data such
as primitives, object, localized characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic
functionality related to streams and I/O. We will see the most commonly used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte
streams but the most frequently used classes are, FileInputStream andFileOutputStream. Following is an example which
makes use of these two classes to copy an input file into an output file −
Example
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same
content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most
frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter
uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes
two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode
characters) into an output file −
Example
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content −
This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating output.txt file with the same
content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program can take input from a
keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages,
then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following
three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard is used as standard input stream
and represented as System.in.
Standard Output − This is used to output the data produced by the user's program and usually a computer screen is used
for standard output stream and represented as System.out.
Standard Error − This is used to output the error data produced by the user's program and usually a computer screen is
used for standard error stream and represented as System.err.
Following is a simple program, which createsInputStreamReader to read standard input stream until the user types a "q"

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

public static void main(String args[]) throws IOException {


InputStreamReader cin = null;

try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}
}
}
}
Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program.
This program continues to read and output the same character until we press 'q' −
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source
and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

The two important streams are FileInputStream andFileOutputStream, which would be discussed in this tutorial.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the keyword new and there are several
types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we create a file object
using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or
to do other operations on the stream.
Sr.No. Method & Description

public void close() throws IOException{}


1 This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that
2
the close method of this file output stream is called when there
are no more references to this stream. Throws an IOException.

public int read(int r)throws IOException{}


This method reads the specified byte of data from the
3
InputStream. Returns an int. Returns the next byte of data and -1
will be returned if it's the end of the file.

public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an
4
array. Returns the total number of bytes read. If it is the end of
the file, -1 will be returned.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

public int available() throws IOException{}


5 Gives the number of bytes that can be read from this file input
stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following links −
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist,
before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First, we create a file object
using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream
or to do other operations on the stream.
Sr.No. Method & Description

public void close() throws IOException{}


1 This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that
2
the close method of this file output stream is called when there
are no more references to this stream. Throws an IOException.

public void write(int w)throws IOException{}


3
This methods writes the specified byte to the output stream.

public void write(byte[] w)


4 Writes w.length bytes from the mentioned byte array to the
OutputStream.
There are other important output streams available, for more detail you can refer to the following links −
ByteArrayOutputStream
DataOutputStream
Example
Following is the example to demonstrate InputStream and OutputStream −
import java.io.*;
public class fileStreamTest {

public static void main(String args[]) {

try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i = 0; i < size; i++) {


System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e) {
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary format. Same would be the output on
the stdout screen.
File Navigation and I/O
There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
File Class
FileReader Class
FileWriter Class

5. New File System API NIO2

File APIs in NIO2 constitute one of the major new functional areas of the Java Platform that shipped with Java 7,
specifically a subset of the new file system API alongside Path APIs .
4.1 Setup
Setting up your project to use File APIs is just a matter of making this import:
1 import java.nio.file.*;
Since the code samples in this article will probably be running in different environments, let’s get a handle on the home
directory of the user, which will be valid across all operating systems:
private static String HOME = System.getProperty("user.home");
The Files class is one of the primary entry points of the java.nio.file package. This class offers a rich set of APIs for
reading, writing, and manipulating files and directories. The Files class methods work on instances of Path objects.
4.2 Checking a File or Directory
We can have a Path instance representing a file or a directory on the file system. Whether that file or directory it’s
pointing to exists or not, is accessible or not can be confirmed by a file operation.
For the sake of simplicity, whenever we use the term file, we will be referring to both files and directories unless stated
explicitly otherwise.
To check if a file exists, we use the exists API:
1 @Test
2 public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
3 Path p = Paths.get(HOME);
4
5 assertTrue(Files.exists(p));
6 }
To check that a file does not exist, we use the notExists API:
We can also check if a file is a regular file like myfile.txt or is just a directory, we use the isRegularFile API. There are
also static methods to check for file permissions. To check if a file is readable, we use the isReadable API: To check if it
is writable, we use the isWritable API: to check if it is executable: we use the isExecutable API. Creating Files
The file system API provides single line operations for creating files. To create a regular file, we use thecreateFile API
and pass to it a Path object representing the file we want to create.
All the name elements in the path must exist, apart from the file name, otherwise, we will get anIOException:
1 @Test
2 public void givenFilePath_whenCreatesNewFile_thenCorrect() {
3 String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
4 Path p = Paths.get(HOME + "/" + fileName);
5 assertFalse(Files.exists(p));

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

6
7 Files.createFile(p);
8
9 assertTrue(Files.exists(p));
10 }
In the above test, when we first check the path, it is inexistent, then after the createFile operation, it is found to be
existent.
To create a directory, we use the createDirectory API:
Deleting a File
To delete a file, we use the delete API. For clarity purpose, the following test first ensures that the file does not already
exist, then creates it and confirms that it now exists and finally deletes it and confirms that it’s no longer existent:
You can copy a file or directory by using the copy API: Files.copy(file1, file2);
You can move a file or directory by using the move API. It is in most ways similar to the copy operation. If the copy
operation is analogous to a copy and paste operation in GUI based systems, then move is analogous to a cut and
paste operation: Files.move(file1, file2);

6. Constructors

Constructor in java is a special type of method that is used to initialize the object.Java constructor is invoked at the time
of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor

6.1 Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

purpose of default constructor


Default constructor provides the default values to the object like 0, null etc. depending on the type.
6.2 Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of
parameters in the constructor.
class Student4{
int id;
String name;

Student4(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

7. This Keyword

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method (implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class instance.
The this keyword can be used to refer current class instance variable.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student10{
int id;
String name;

Student10(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are using this
keyword to distinguish between local variable and instance variable.
Solution of the above problem by this keyword
//example of this keyword
class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Karan
222 Aryan
Program where this keyword is not required
class Student12{
int id;
String name;

Student12(int i,String n){


id = i;
name = n;
}

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

void display(){System.out.println(id+" "+name);}


public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}

Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is
better if you have many constructors in the class and want to reuse that constructor.
//Program of this() constructor call (constructor chaining)

class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}

Student13(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the
constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this
keyword.
class Student14{
int id;
String name;
String city;

Student14(int id,String name){


this.id = id;
this.name = name;
}
Student14(int id,String name,String city){

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

this(id,name);//now no need to initialize id and name


this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){


Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
Output:111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}

Student15(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
Output:Compile Time Error
)The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method. Let's see the example
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:method is invoked

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

5) The this keyword can be passed as argument in the constructor call.


We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see
the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10

6) The this keyword can be used to return current class instance.


We can return the this keyword as an statement from the method. In such case, return type of the method must be the
class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}

class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference
variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

public static void main(String args[]){


A5 obj=new A5();
System.out.println(obj);//prints the reference ID

obj.m();
}
}
Output:A5@22b3ea59
A5@22b3ea59

8. Garbage Collector
In Java destruction of object from memory is done automatically by the JVM. When there is no reference to an object,
then that object is assumed to be no longer needed and the memory occupied by the object are released. This technique is
called Garbage Collection. This is accomplished by the JVM. Unlike C++ there is no explicit need to destroy object.
the Garbage Collection can not be forced explicitly. We may request JVM for garbage collection by
calling System.gc() method. But This does not guarantee that JVM will perform the garbage collection.
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform
the garbage collection. It only request the JVM for garbage collection. This method is present
inSystem and Runtime class.

Example for gc() method


public class Test
{

public static void main(String[] args)


{
Test t = new Test();
t=null;
System.gc();
}
public void finalize()
{
System.out.println("Garbage Collected");
}
}
Output :
Garbage Collected

Advantages of Garbage Collection


Programmer doesn't need to worry about dereferencing an object.
It is done automatically by JVM.
Increases memory efficiency and decreases the chances for memory leak.

9. finalize() method
Sometime an object will need to perform some specific task before it is destroyed such as closing an open connection or
releasing any resources held. To handle such situation finalize() method is used. finalize()method is called by garbage
collection thread before collecting object. Its the last chance for any object to perform cleanup utility.
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created
any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

Signature of finalize() method

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

protected void finalize()


{
//finalize-code
}

Some Important Points to Remember


finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
finalize() method is declare as proctected inside Object class.
finalize() method gets called only once by GC threads.

10. Overloading methods and Constructors


10.1 Method OverloadingIf a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
Advantage :Method overloading increases the readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing the return type of the method.
1) Example of Method Overloading by changing the no. of arguments
In this example, we have created two overloaded methods, first sum method performs addition of two numbers and
second sum method performs addition of three numbers.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
Test it Now
Output:30
40
2) Example of Method Overloading by changing data type of argument
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two
integer arguments and second sum method receives two double arguments.
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Test it Now
Output:21.0
40
 Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity.
Let's see how ambiguity may occur:
because there was problem:
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

double sum(int a,int b){System.out.println(a+b);}


public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20); //Compile Time Error

}
}
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?


Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the
simple example:
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}

10.2 Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in
parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list
and their type.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Java Constructor Java Method


Constructor is used to initialize the state of an object. Method is used to expose behaviour
of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if you Method is not provided by compiler
don't have any constructor. in any case.
Constructor name must be same as the class name. Method name may or may not be
same as class name.

11.Using object as parameters


Passing Object as Parameter :
package com.pritesh.programs;

class Rectangle {
int length;
int width;

Rectangle(int l, int b) {
length = l;
width = b;
}

void area(Rectangle r1) {


int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}

Output of the program :


Area of Rectangle : 200

Explanation :
We can pass Object of any class as parameter to a method in java.
We can access the instance variables of the object passed inside the called method.
area = r1.length * r1.width
It is good practice to initialize instance variables of an object before passing object as parameter
to method otherwise it will take default initial values.
Different Ways of Passing Object as Parameter :
Way 1 : By directly passing Object Name
void area(Rectangle r1) {
int areaOfRectangle = r1.length * r1.width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
Way 2 : By passing Instance Variables one by one
package com.pritesh.programs;

class Rectangle {
int length;
int width;

void area(int length, int width) {


int areaOfRectangle = length * width;
System.out.println("Area of Rectangle : "
+ areaOfRectangle);
}
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();

r1.length = 20;
r1.width = 10;

r2.area(r1.length, r1.width);
}
}
Actually this is not a way to pass the object to method. but this program will explain you how to
pass instance variables of particular object to calling method.
Way 3 : We can pass only public data of object to the Method.
Suppose we made width variable of a class private then we cannot update value in a main
method since it does not have permission to access it.
private int width;
after making width private –
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();

r1.length = 20;
r1.width = 10;

r2.area(r1.length, r1.width);
}
}

12. Returning Object in Methods


In Java Programming A method can return any type of data, including class types that you create.
For example, in the following program, the getRectangleObject( ) method returns an object.
Java Program : Returning the Object From Method

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

package com.pritesh.programs;

import java.io.File;
import java.io.IOException;

class Rectangle {
int length;
int breadth;

Rectangle(int l,int b) {
length = l;
breadth = b;
}

Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
}

class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;

ob2 = ob1.getRectangleObject();
System.out.println("ob1.length : " + ob1.length);
System.out.println("ob1.breadth: " + ob1.breadth);

System.out.println("ob2.length : " + ob2.length);


System.out.println("ob2.breadth: " + ob2.breadth);

}
}
Output of the Program :
ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20

Explanation :
In the above program we have called a method getRectangleObject() and the method creates object of class
from which it has been called.
All objects are dynamically allocated using new, you don’t need to worry about an object going out-of-scope because
the method in which it was created terminates.
The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no
references to it, the object will be reclaimed the next time garbage collection takes place.

13. Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called
recursive method.
It makes the code compact but complex to understand.
Syntax:
returntype methodname(){
//code to be executed

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

methodname();//calling same method


}
Java Recursion Example 1: Infinite times
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}

public static void main(String[] args) {


p();
}
}
Output:
hello
hello
...
java.lang.StackOverflowError
Java Recursion Example 3: Factorial Number
public class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Output:
Factorial of 5 is: 120
Working of above program:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

14. Access Control


Class Access
There are two types of modifiers that can be used for class declaration
Access Modifiers - public and default (package)
Nonaccess Modifiers - strictfp, final and abstract
Every class you declare has an access control, whether you explicity type one or not. When a class has access to another
class it means he can do one of 3 things
Create an instance of that class
Extend the class (become a subclass)
Access certain methods and variables within that class
Access means visibility, if you do not have access to a class you cannot use any methods or variables of that class.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Class Access Modifiers


Default When no modifier is present then default access is applied, think of default access as package access, a class with
Access default access can be seen only by classes within the same package
When declared with public access it gives all classes from all packages access to the public class, although you still n
Public Access
to import the class
Class non-Access Modifers
When used with classes this means that the class cannot be subclassed (cannot extend). Many of classes in the Java
Final Classes
library are final classes.
An abstract class can never be instantiated, its sole purpose is to be extended (subclassed). If a single method in a cla
abstract the whole class must be declared abstract. You can put non-abstract methods in a abstract class (also known
concrete method), you will be unable to override the non-abstract method. An abstract class can extend another abstr
Abstract class.
Classes You cannot mark a class as both abstract and final as they mean the opposite, you will get a compiler error (illegal
combination of modifiers).
The first concrete class to extend an abstract class must implement all abstract methods.
Abstract classes can have constructors.
Method and Variable Access
Methods and Variables within a class are collectively known as members.There are two types of modifiers that can be
used for a member declaration
Access Modifiers - private, protected, public and default
Nonaccess Modifiers - final, abstract, transient, synchronized, native, strictfp and static
Every member you declare has an access control, whether you explicity type one or not. Members accessed with using the
dot operator (.) must belong to the same class, the this keyword is used to reference the currently executing object.
Member Access Modifiers
When the member is declared protected it means that only the following can access the member
class that declared the member
Public Access any subclasses
any class thats in the same package can access it
any class
When the member is declared protected it means that only the following can access the member
class that declared the member
Protected Access
any subclasses
any class thats in the same package can access it
When the member has no modifier it has default access only the following can access the member
Default Access class that declared the member
any subclasses
When the member is declared protected it means that only the following can access the member. Methods that
Private Access declaredprivate are implicity final.
class that declared the member
Member non-Access Modifers
When used this means that the member (method or variable) cannot be overridden. A variable in a interface is i
Final
final.
An abstract method is a method that has been declared but not implemented, in other words the method contain
Abstract
The abstract method must be implemented in either the sub-class or any other subclass that has extend it.
This modifier can only be applied to variables, you are telling JVM to skip this variable when you attempt to se
Transient
declaring it.
Synchronized When used this means that the method can be accessed by only one thread at a time. It can only be applied to m
Native Indicates that a method is implemented in a platform-dependent language such as C.
Strictfp Indicates that strict floating-point will be adhered too.
Static The best way i can describe a static variable or method is that one copy of the static member is contained in me
instances to access this copy, an example of this is like having a single counter variable that all classes can upd
There is a rule that states that a static method of a class can't access a nonstatic member or variable of its own c

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

are also declared final implicity.


You can Make Static: Methods, Variables and Top-Level nested Classes
You cannot make static: Constructors, Classes, Interfaces, Inner Classes, Inner Class Methods/Variables, Loc
There is also no this reference when using static, also all static variables and methods are loaded first in order o
may find a simple static block of code to initialize variables or execute code.

15. Static and final Keyword


15.1 The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can
be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or
uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda();
honda.run();

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}
}
Test it Now
Output:Compile Time Error
final method is inherited but you cannot override it.

15.2 Static Key


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.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
1) Java static variable
If you declare any variable as static, it is known static variable.
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.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
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.
Java static property is shared to all objects.
Example of static variable
//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Test it Now
Output:111 Karan ITS
222 Aryan ITS

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

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 objects will have the value 1 in the count variable.
class Counter{
int count=0;//will get memory when instance is created

Counter(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}
}
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.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}
Test it Now
Output:1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
3) Java static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Test it Now
Output:static block is invoked
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.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Test it Now
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)

16. Nested and Inner class

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

16.1 Inner class are defined inside the body of another class (known as outer class). These classes can have access
modifier or even can be marked as abstract and final. Inner classes have special relationship with outer class instances.
This relationship allows them to have access to outer class members including private members too.
Inner classes can be defined in four different following ways as mentioned below:
1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class
1) Inner class
An inner class is declared inside the curly braces of another enclosing class. Inner class is coded inside a Top level class as
shown below:-
//Top level class definition
class MyOuterClassDemo {
private int myVar= 1;

// inner class definition


class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Value of myVar is :" + myVar);
}
} // close inner class definition
} // close Top level class definition
Inner class acts as a member of the enclosing class and can have any access
modifiers: abstract, final, public,protected, private, static.
Inner class can access all members of the outer class including those marked private as shown in the above example where
inner class is accessing the private variable"myVar" of outer class.
Instantiating an inner class
To instantiate an instance of inner class, there should be a live instance of outer class. An inner class instance can be
created only from an outer class instance. An inner class shares a special relationship with an instance of the enclosing
class.
Instantiating an inner class from within code in outer class:
class MyOuterClassDemo {
private int x= 1;
public void innerInstance()
{
MyInnerClassDemo inner = new MyInnerClassDemo();
inner. seeOuter();
}
public static void main(String args[]){
MyOuterClassDemo obj = new MyOuterClassDemo();
obj.innerInstance();
}
// inner class definition
class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
} // close inner class definition
} // close Top level class definition
Output:
Outer Value of x is :1
Instantiating an inner class from outside the outer class Instance Code:
The public static void main code in the above example can be replaced with this one. It will also give the same output.
public static void main(String args[]){
MyOuterClassDemo.MyInnerClassDemo inner = new MyOuterClassDemo().new MyInnerClassDemo();
inner. seeOuter();

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

}
2) Method–Local inner classes
A method local inner class is defined within a method of the enclosing class. If you want to use inner class , you must
instantiate the inner class in the same method, but after the class definition code. Only two modifiers are allowed for
method-local inner class which are abstract and final.The inner class can use the local variables of the method (in which it
is present), only if they are marked final.
//Top level class definition
class MyOuterClassDemo {
private int x= 1;

public void doThings(){


String name ="local variable";
// inner class defined inside a method of outer class
class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
System.out.println("Value of name is :" + name);//compilation error!!
} //close inner class method
} // close inner class definition
} //close Top level class method
} // close Top level class
The above code will throw a compilation error as Inner class cannot use the non-final variables of the method, in which it
is defined.
This is how it can be fixed: If we mark the variable as final then inner class can use it.
final String name ="local variable";// inner object can use it
3) Anonymous Inner Classes
It is a type of inner class which
has no name
can be instantiated only once
is usually declared inside a method or a code block ,a curly braces ending with semicolon.
is accessible only at the point where it is defined.
does not have a constructor simply because it does not have a name
cannot be static
Example:
package beginnersbook.com;
class Pizza{
public void eat()
{
System.out.println("pizza");
}
}
class Food {
/* There is no semicolon(;)
* semicolon is present at the curly braces of the method end.
*/
Pizza p = new Pizza(){
public void eat()
{
System.out.println("anonymous pizza");
}
};
}
4) Static Nested Classes
A static nested classes are the inner classes marked with static modifier.Because this is static in nature so this type of inner
class doesn’t share any special kind of relationship with an instance of outer class.A static nested class cannot access non
static members of outer class.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

Example:
class Outer{
static class Nested{}
}
A static nested class can be instantiated like this:
class Outer{// outer class
static class Nested{}// static nested class
}

class Demo{
public static void main(string[] args){
// use both class names
Outer.Nested n= new Outer.Nested();
}
}
16.2 Nested Class
A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing
class.

Static Nested Class


A satic nested class is the one that has static modifier applied. Because it is static it cannot refer to non-static members of
its enclosing class directly. Because of this restriction static nested class is seldom used.

Non-static Nested class


Non-static Nested class is most important type of nested class. It is also known as Inner class. It has access to all
variables and methods of Outer class and may refer to them directly. But the reverse is not true, that is,Outer class cannot
directly access members of Inner class.
One more important thing to notice about an Inner class is that it can be created only within the scope ofOuter class. Java
compiler generates an error if any code outside Outer class attempts to instantiate Innerclass.

Example of Inner class


class Outer
{
public void display()
{
Inner in=new Inner();
in.show();
}

class Inner
{

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

public void show()


{
System.out.println("Inside inner");
}
}
}

class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output :
Inside inner

17. Command Line Argument


The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an input.
So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and
so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java
In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one
argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
Output: Your first argument is: sonoo

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the
array using for loop.
class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output: sonoo
jaiswal
1
3
abc

18. String and String Buffer


18.1 String Class

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

In java, string is basically an object that represents sequence of char values. An array of characters works same as java
string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(), concat(), equals(), split(),
length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

18.2 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
StringBuffer(): creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.
Important methods of StringBuffer class
public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the
specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from
specified startIndex and endIndex.
public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified
startIndex and endIndex.
public synchronized StringBuffer reverse(): is used to reverse the string.
public int capacity(): is used to return the current capacity.
public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
public char charAt(int index): is used to return the character at the specified position.
public int length(): is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and
endIndex.

Difference between String and StringBuffer


There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are
given below:
No. String StringBuffer
1) String class is immutable. StringBuffer class is mutable.
2) String is slow and consumes more memory when you concat too StringBuffer is fast and consumes less
many strings because every time it creates new instance. memory when you cancat strings.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

3) String class overrides the equals() method of Object class. So you StringBuffer class doesn't override the
can compare the contents of two strings by equals() method. equals() method of Object class.

19. Java Bean Standards


A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of the properties, known as getter and setter methods.
Why use Java Bean?
According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object, so
we can access this object from multiple places. Moreover, it provides the easy maintenance.
Simple example of java bean class
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the java bean class?
To access the java bean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

System.out.println(e.getName());

}}
Note: There are two ways to provide values to the object, one way is by constructor and second is by setter method.
JavaBean Property Naming Rules
If the property is not a boolean, the getter method's prefix must be get. For example, getSize()is a valid JavaBeans getter
name for a property named "size." Keep in mind that you do not need to have a variable named size (although some IDEs
expect it).
The name of the property is inferred from the getters and setters, not through any variables in your class. What you return
from getSize() is up to you.
 If the property is a boolean, the getter method's prefix is either get or is. For example, getStopped() or isStopped() are
both valid JavaBeans names for a boolean property.
 The setter method's prefix must be set. For example, setSize() is the valid JavaBean name for a property named size.
 To complete the name of a getter or setter method, change the first letter of the property name to uppercase, and then
append it to the appropriate prefix (
get, is, or set).
 Setter method signatures must be marked
public, with a void return type and an argument that represents the property type.
 Getter method signatures must be marked
public, take no arguments, and have a return type that matches the argument type of the setter method for that property.
JavaBean Listener Naming Rules
Listener method names used to "register" a listener with an event source must use the prefix

Downloaded by Harendra Sharma (harendra.pth@gmail.com)


lOMoARcPSD|17471924

add, followed by the listener type. For example, addActionListener() is a valid name for a method that an event source
will have to allow others to register for Action events.
 Listener method names used to remove ("unregister") a listener must use the prefix
remove, followed by the listener type (using the same rules as the registration add method).
 The type of listener to be added or removed must be passed as the argument to the method.
 Listener method names must end with the word "Listener".
Examples of valid JavaBean method signatures are
public void setMyValue(int v)
public int getMyValue()
public boolean isMyStatus()
public void addMyListener(MyListener m)
public void removeMyListener(MyListener m)
Examples of invalid JavaBean method signatures are
void setCustomerName(String s) // must be public
public void modifyMyValue(int v) // can't use 'modify'
public void addXListener(MyListener m) // listener type mismatch

20. Java Naming conventions

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable,
constant, method etc.
But, it is not forced to follow. So, it is known as convention not rule.
All the classes, interfaces, packages, methods and fields of java programming language are given according to java
naming convention.
Advantage of naming conventions in java
By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers.
Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.

CamelCase in java naming conventions


Java follows camelcase syntax for naming the class, interface, method and variable.
If name is combined with two words, second word will start with uppercase letter always e.g. actionPerformed(),
firstName, ActionEvent, ActionListener etc.

Downloaded by Harendra Sharma (harendra.pth@gmail.com)

You might also like