Hotcourses Java
Hotcourses Java
B
DAY-1
Selvakumar.B
Index
What Is Java?
Getting Started Programming in Java
o Creating a Java Application
o What are Compiler and Interpreter?
o Compiling and Running the Source File
o Naming conventions
Java comments
Variables (Identifier)
o Rules in creating the variable
o Legal Variable
o Illegal Variable
Statements and Expressions
Data Types
o Primitive Data Types
o Casting
o Upcasting
o DownCasting
Variable Types
o Instance Variables (Non-Static Fields)
o Class Variables (Static Fields)
o Local Variables
o Parameters
Exercise
Selvakumar.B
What Is Java?
Java was created by a team led by James Gosling for Sun Micro-systems, The first Java
1.0 was released to the public in 1996, over 6.5million developers worldwide using Java for
developing their web-pages.
The current version is Java is 1.7 beta, we are going to cover the Java version 1.4.
Java is :
Platform Independent: Java was written to be a portable language that doesn't care about
the operating system or the hardware of the computer
In the Java programming language, all source code is first written in plain text files ending
with the .java extension. Those source files are then compiled into .class files by the javac
compiler. A .class file does not contain code that is native to your processor; it instead
contains bytecodes
As with all programming languages, your Java source files are created in a plain text editor,
or in an editor that can save files in plain ASCII without any formatting characters.
1: class HelloWorld {
2: public static void main (String args[]) {
3: System.out.println("Hello World!");
4: }
5: }
After you've finished typing in the program, save the file somewhere on your disk with the
name HelloWorld.java. This is very important. Java source files must have the same name as
the class they define (including the same upper- and lowercase letters), and they must have
the extension .java.
Here, the class definition has the name HelloWorld, so the filename must
be HelloWorld.java. If you name your file something else (even something
likehelloworld.java or Helloworld.java), you won't be able to compile it. Make absolutely
certain the name is HelloWorld.java.
Selvakumar.B
What are Compiler and Interpreter?
The compilertakes the file that you have written and produces another file from it. In
the case of Java programs, for instance, you might write a program called myProg.java and
the Java compiler would translate it into the file myProg.class (bytecode) which you could
then run.
The compiler has another task apart from translating your program. It also checks it to make
sure that it is grammatically correct. Only when it is sure that there are no grammatical
errors does it do the translation. Any errors that the compiler detects are called compile-time
errors or syntax errors, at this state the another file wont create (.class)
JAVA (Compiler)
JAVAC (Interpreter JVM)
Selvakumar.B
Naming conventions
Selvakumar.B
Java comments
Comments can be specified in several ways:
Using /** and */The /** prefix is used by the Javadoc utility for generating standardized
Selvakumar.B
Variables (Identifier)
A variable is a container that holds values that are used in a Java program. Every
variable must be declared to use a data type. The variables could be declared to use one of the
eight primitive data types: byte, short, int, long, float, double, char or boolean. And, every
variable must be given an initial value before it can be used.
Legal Variable
_a;
$c;
______2_w;
_$;
this_is_a_very_detailed_name_for_an_identifier;
Selvakumar.B
Illegal Variable
:b;
-d;
e#;
.f;
7g;
Selvakumar.B
Data Types
Java supports eight basic data types known as primitive types. In addition, it supports
classes and arrays as composite data types, or reference types
Examples
Correct data assignment
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
float f = 58.0f;
double d = 67.123;
--------------------Configuration: <Default>--------------------
C:\Example.java:4: possible loss of precision
found : int
required: byte
byte b = 132;
Process completed.
Selvakumar.B
Assignment compatibility between Integer Types
byte Assignable Cast needed Cast needed Cast needed Cast needed Cast needed Cast needed
char Cast needed Assignable Cast needed Cast needed Cast needed Cast needed Cast needed
short Assignable Cast needed Assignable Cast needed Cast needed Cast needed Cast needed
int Assignable Assignable Assignable Assignable Cast needed Cast needed Cast needed
long Assignable Assignable Assignable Assignable Assignable Cast needed Cast needed
Boolean No No No No No No No
Examples
Process completed.
Selvakumar.B
Casting (Type Conversion)
Automatic Conversion
Java performs automatic type conversion when the type of the expression on the right
hand side of an assignment operator safely promotes to the type of the variable on the left
hand side of the assignment operator. Thus we can safely assign:
Example:
public class Example {
public static void main(String[] args) {
float f = 58.0f;
double d = 67.123;
d = f;
f = d; //error
// 64 bit long integer
long myLongInteger = 0;
// 32 bit standard integer
int myInteger = 0 ;
myLongInteger = myInteger;
}
}
Upcasting
Casting a reference with the class hierarchy in a direction from the sub classes towards the
root then this type of casting is termed as upcasting. Upcasting does not require a cast
operator.
DownCasting
On the other hand, casting a reference with hierarchal class order in a direction from the
root class towards the children or subclasses, then it is known as downcasting.
Selvakumar.B
Variable Types
Selvakumar
Selvakumar
Selvakumar
Raj
Selvakumar.B
Selvakumar
Selvakumar
Raj
Raj
Local Variables
Similar to how an object stores its state in fields, a method will often store its
temporary state in local variables. A variable as local, which comes between the opening and
closing braces of a method. As such, local variables are only visible to the methods in which
they are declared; they are not accessible from the rest of the class.
{
String myName = „Selvakumar”;
}
public class Example {
public Example() {}
public static void main(String[] args) {
System.out.println(myMethodVariable); // Error
Example E1 = new Example();
System.out.println(E1.myMethod()); //Correct
System.out.println(new Example().myMethod()); //Correct
}
public int myMethod() {
int myMethodVariable = 100;
return myMethodVariable;
}
}
100
100
Parameters
Signature for the main method is public static void main(String[] args). Here, the
args variable is the parameter to this method. The important thing to remember is that
parameters are always classified as "variables" not "fields". We can pass „N‟ number of
parameters; the repeated name with the same data type will produce any compile time error,
parameter variables are only visible to the methods in which they have passed.
Selvakumar.B
public int myMethod(int n1, int n1){
int myMethodVariable = 100;
return myMethodVariable;
}
--------------------Configuration: <Default>--------------------
C:\Example.java:10: n1 is already defined in myMethod
public int myMethod(int n1, int n1){
^
1 error
Process completed.
Syntax:
public char charAt(int index)
Example:
public class Test {
Selvakumar.B
DAY-2
Selvakumar.B
Index
Predefined Classes
o String class
o Number class
o Character class
Exercise
Selvakumar.B
Predefined Methods
o String methods
o Class methods.
o Number Methods
String methods
Example
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
s = s.concat(" all the time");
System.out.println(s);
}
}
This produces following result:
Strings are immutable all the time
Example
public class Test {
public static void main(String args[]) {
String Str1 = new String("This is really not immutable!!");
Selvakumar.B
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;
retVal = Str1.equals( Str2 ); System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str4 ); System.out.println("Returned Value = " + retVal );
}
}
This produces following result:
Returned Value = true
Returned Value = true
Returned Value = false
Example
public class Test {
public static void main(String args[]) {
String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
String Str4 = new String("This IS REALLY NOT IMMUTABLE!!");
boolean retVal;
retVal = Str1.equals( Str2 );System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str3 ); System.out.println("Returned Value = " + retVal );
retVal = Str1.equalsIgnoreCase( Str4 );
System.out.println("Returned Value = " + retVal );
}
}
This produces following result:
Returned Value = true
Returned Value = true
Returned Value = true
Selvakumar.B
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Hotcourses.com");
String SubStr1 = new String("Hotcourses");
String SubStr2 = new String("Shotcourses");
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o' ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o', 5 ));
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1 ));
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1, 15 ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( SubStr2 ));
}
}
This produces following result:
Found Index :4
Found Index :9
Found Index :11
Found Index :-1
Found Index :-1
Selvakumar.B
System.out.print("Found Last Index :" );
System.out.println(Str.lastIndexOf( SubStr2 ));
}
}
13 int length()
Returns the length of this string
Example
import java.io.*;
Selvakumar.B
15 String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given
replacement.
Example
import java.io.*;
Selvakumar.B
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 0)){
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-")){
System.out.println(retval);
}
}
}
This produces following result:
Return Value :
Welcome
to-Hotcourses.com
Return Value :
Welcome
to
Hotcourses.com
Return Value :
Welcome
to
Hotcourses.com
Return Value :
Welcome
to
Hotcourses.com
Selvakumar.B
}
This produces following result:
Return Value :true
Return Value :false
Return Value :true
22 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
Example
import java.io.*;
23 String toString()
This object (which is already a string!) is itself returned.
Example
import java.io.*;
Selvakumar.B
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :");
System.out.println(Str.toString());
}
}
This produces following result:
Return Value :Welcome to Hotcourses.com
24 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
Example
import java.io.*;
25 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Example
import java.io.*;
Syntex
static String valueOf(boolean b)
or
static String valueOf(char c)
or
static String valueOf(char[] data)
or
static String valueOf(char[] data, int offset, int count)
Selvakumar.B
or
static String valueOf(double d)
or
static String valueOf(float f)
or
static String valueOf(int i)
or
static String valueOf(long l)
or
static String valueOf(Object obj)
Example
import java.io.*;
Selvakumar.B
NumberMethods
byte byteValue()
short shortValue()
intintValue()
long longValue()
float floatValue()
double doubleValue()
Example
public class Test{
public static void main(String args[]){
Integer x = 5;
// Returns byte primitive data type
System.out.println( x.byteValue() );
2 toString()
Returns a String object representing the value of specified int or Integer.The method is used
to get a String object representing the value of the Number Object.
Example
public class Test{
Selvakumar.B
public static void main(String args[]){
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
}
}
This produces following result:
5
12
3 parseXXX()
This method is used to get the primitive data type of a certain String.Following are most
commonly used conversion methods for the String value
Integer.parseInt(String)
Float.parseFloat(String)
Double.parseDouble(String)
Byte.parseByte(String)
Short.parseShort(String)
Boolean.parseBoolean String);
Example
String myAge = “100”;
intmyAgeValue = Integer.parseInt(myAge);
System.out.println(myAgeValue+10);
This produces following result:
110
4 ceil()
Returns the smallest integer that is greater than or equal to the argument. Returned as a
double.
double ceil(double d)
double ceil(float f)
Example
public class Test{
public static void main(String args[]){
double d = -100.675;
float f = 100.675f;
System.out.println(Math.ceil(d));
System.out.println(Math.ceil(f)); }
}
This produces following result:
-100.0
101.0
5 floor()
Returns the largest integer that is less than or equal to the argument. Returned as a double.
double floor(double d)
double floor(float f)
Selvakumar.B
Example
public class Test{
public static void main(String args[]){
double d = -100.675;
float f = 100.675f;
System.out.println(Math.floor(d));
System.out.println(Math.floor(f));
}
}
This produces following result:
-101.0
100.0
6 random()
Returns a random number.
static double random()
Example
public class Test{
public static void main(String args[]){
System.out.println( Math.random() );
System.out.println( Math.random() );
}
}
This produces following result:
0.16763945061451657
0.400551253762343
Selvakumar.B
CharacterMethods
Following table shows the Java escape sequences:
Example
If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes:
Example
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
}
}
This produces following result:
true
false
2 isDigit()
Determines whether the specified char value is a digit.
booleanisDigit(char ch)
Selvakumar.B
Example
public class Test {
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));
}
}
This produces following result:
false
true
3 isWhitespace()
Determines whether the specified char value is white space.
booleanisWhitespace(char ch)
Example
public class Test{
public static void main(String args[]){
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));
}
}
This produces following result:
false
true
true
true
4 isUpperCase()
Determines whether the specified char value is uppercase.
booleanisUpperCase(char ch)
Example
public class Test{
public static void main(String args[]){
System.out.println( Character.isUpperCase('c'));
System.out.println( Character.isUpperCase('C'));
System.out.println( Character.isUpperCase('\n'));
System.out.println( Character.isUpperCase('\t'));
}
}
This produces following result:
false
true
false
false
Selvakumar.B
5 isLowerCase()
Determines whether the specified char value is lowercase.
booleanisLowerCase(char ch)
Example
public class Test{
public static void main(String args[]){
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
System.out.println(Character.isLowerCase('\n'));
System.out.println(Character.isLowerCase('\t'));
}
}
This produces following result:
true
false
false
false
6 toUpperCase()
Returns the uppercase form of the specified char value.
char toUpperCase(char ch)
Example
public class Test{
public static void main(String args[]){
System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C'));
}
}
This produces following result:
C
C
7 toLowerCase()
Returns the lowercase form of the specified char value.
char toLowerCase(char ch)
Example
public class Test{
public static void main(String args[]){
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
This produces following result:
c
c
Selvakumar.B
8 toString()
Returns a String object representing the specified character valuethat is, a one-character string.
Selvakumar.B
DAY-3
Selvakumar.B
Index
Java Decision Making
o The if Statement
o The if...else Statement
o The if...else if...else Statement
o Nested if...else Statement
o The switch Statement
Java Loop Control
o The for Loop
o The nested for Loop
o The while Loop
o The do...while Loop
o The break Keyword
o The continue Keyword
Java Arrays
Exercise
Selvakumar.B
Java Decision Making
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.
decision-making statements
The "if" Statement "if" Statement
if (test condition) { "if - else" Statement
statements "if - else if - else" Statements
…….
} Switch Statement
The test condition can be any relational comparison (or logically TRUE) statement
and must be enclosed in parentheses. The block of statements is enclosed in braces and
indented for readability. The braces are NOT required if only ONE statement follows the
"if", but it is a good idea to include them.
The block executes only if the test condition is TRUE. If the test condition is FALSE,
the block is ignored and execution continues to the next statement following the block.
Keep in mind:
if (a = 3) will cause an ERROR. The condition a = 3 is an assignment statement,
whereas test conditions are looking for Boolean true or false expressions.
Examples:
Selvakumar.B
The "if-else" Statement
if (test condition) {
statements
…….
}else{
statements
…….
}
If the test condition is TRUE, the block of statements following the "if" executes. If
the test condition FALSE, the block of statements following the "else" executes instead.
Example:
// example of if ... else
intstate = “Tamilnadu”;
int population = 1000;
if (test condition-2) {
statements
…….
}elseif (test condition-2) {
statements
…….
}elseif (test condition-3) {
statements
…….
} else{
statements
…….
}
If the test condition-1 is TRUE, the block of statements following the "if" executes if
false then checks for test condition-2, if true then the block of statements following the
respective else-if gets executes and repeats the same for all the else-if block if found, if no
matches then execute the statement following the else statement, if any one of the condition
satisfied then it executes the respective statements and gets breaks. The else statements is not
mandatory
Selvakumar.B
Example:
// example of if ... else if … else
int a = 100;
int b =123;
if(a= = b){
System.out.println("They are equal!\n");
}else if( a < b){
System.out.println("The first number is smaller.\n");
}else{
System.out.println("The second number is smaller.\n");
}
If you need to have several choices give the same responses, you need to use the
following coding style:
switch (expression) {
case (expression 1): {
one or more Java statements;
break;
}
case (expression 2): {
one or more Java statements;
break;
}
…..
…..
default: {
one or more Java statements;
break;
}
}
RULES:
You MUST use a break statement after each "case" block to keep execution from
"falling through" to the remaining case statements.
Only integer or character types may be used as control expressions in "switch"
statements.
It is best to place the most often used choices first to facilitate faster execution.
While the "default" is not required, it is recommended.
Selvakumar.B
Example:
// example of switch
switch (value){
case (1):
case (2):
case (3): {
//The case code for 1, 2, 3
break;
}
case (4):
case (5):
case (6): {
//The case code for 4, 5, 6
break;
}
default: {
//The code for other values
break;
}
}
looping statements
The FOR Loop
Nested FOR Loops
The WHILE Loop
The DO-WHILE Loop
The statements in the for loop repeat continuously for a specific number of times.
The while and do-while loops repeat until a certain condition is met. The for loop repeats
until a specific count is met. The coding format is:
The countExpression executes after each trip through the loop. The count may
increase/decrease by an increment of 1 or of some other value. The testExpression evaluates
to TRUE or FALSE. While TRUE, the body of the loop repeats. When the
Selvakumar.B
testExpressionbecomes FALSE, Java stops looping and the program continues with the
statement immediately following the for loop in the body of the program.
Braces are not required if the body of the for loop consists of only ONE statement.
Please indent the body of the loop for readability.
Example:
// example of forloop
for (int x= 1; x<=10; x++) {
some code here;
}
When working with nested loops, the outer loop changes only after the inner loop is
completely finished (or is interrupted.).
while(test condition) {
block of code;
}
Selvakumar.B
The test condition must be enclosed in parentheses. The block of code is known as the body
of the loop and is enclosed in braces and indented for readability. (The braces are not required if the
body is composed of only ONE statement.) Semi-colons follow the statements within the block only.
When a program encounters a while loop, the test condition is evaluated first. If it is TRUE,
the program executes the body of the loop. The program then returns to the test condition and
reevaluates. If still TRUE, the body executes again. This cycle of testing and execution continues
until the test condition evaluates to FALSE. If you want the loop to eventually terminate, something
within the body of the loop must affect the test condition. Otherwise, a disastrous INFINITE LOOP
is the result.
Example:
// example of forloop
String name="Corky";
int i = 0;//begin with the first cell of string
while (i <name.length( )) // loop test condition
{
//print each cell on a new line
System.out.println(name.charAt(i));
i++; //increment counter by 1
}
System.out.println("There are "+ i + " characters.");
/*This last statement prints when the test condition is false and the loop terminates*/
do {
block of code;
}while (test condition);
The do-while loop is an exit-condition loop. This means that the body of the loop is always
executed First. Then, the test condition is evaluated. If the test condition is TRUE, the program
executes the body of the loop again. If the test condition is FALSE, the loop terminates and program
execution continues with the statement following the while.
Example:
// example of forloop
String name="Corky";
int i = 0;
do{
System.out.println(name.charAt(i));
Selvakumar.B
i++; //increment counter by 1
} while (i <name.length( )) ; // loop test condition
System.out.println("There are "+ i + " characters.");
branching statements
The BREAK statement
The CONTINUE statement
The RETURN statement
Example:
// example of break
for (int x= 1; x<=10; x++) {
if( x==3 ){
break;
}
}
// another example of break
for (int x= 1; x<=10; x++) {
for (intj = 1; j <=10; j++) {
if( j%3 == 2 ){
break;
}
}
}
Example:
// example of break
for (int x= 1; x<=10; x++) {
if( x==3 ){ continue; }
}
// another example of break
for (int x= 1; x<=10; x++) {
for (intj = 1; j <=10; j++) {
Selvakumar.B
if( j%3 == 2 ){
continue;
}
}
}
return ++count;
The data type of the returned value must match the type of the method's declared return value.
When the Method is declared void, use the form of return that doesn't return a value.
return;
Selvakumar.B
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection
of elements of the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays
using indexed variables.
Examples
int[] anArray; // declares an array of integers
anArray = new int[10]; // allocates memory for 10 integers
String[] anArray = new String[10]; // allocates memory for 10 integers
int[] anArray = new int[]{1,2,3,4,5,6,7,8,9};
int[] anArray = {1,2,3,4,5,6,7,8,9};
Selvakumar.B
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because
all of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Selvakumar.B
Declaring Multi Dimension Array
data-type[][] identifier =new data-type[n] [n]; or
data-type identifier[][]=new data-type[n] [n];
data-type identifier[][]=new data-type[][]{values};
data-type identifier[][]={values};
Examples
int[][] a2 = newint[10][5];
byte[][] smallArray = { { 10, 11, 12, 13 }, { 20, 21, 22, 23 }, { 30, 31, 32, 33 }, { 40, 41, 42, 43 }};
intsudoku[][] = new int[][]{ { 2, 1, 3}, { 1, 3, 2}, { 3, 2, 1} };
After you instantiate an array, default values are automatically assigned to it in the following manner. String[]
anArray = new String[10];
byte 0
char ‘\u0000′.
short 0
int 0
long 0L
float 0.0f
double 0.0d
boolean False
String null
Selvakumar.B
Common array exceptions
NullPointerException is accessing a null from a java array
==========================================================
Exception in thread "main" java.lang.NullPointerException
atExample.main(Example.java:5)
Process completed.
==========================================================
==============================================================
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
atExample.main(Example.java:5)
Process completed.
==============================================================
Selvakumar.B
DAY-4
Selvakumar.B
Index
Java methods
o Creating a method
o Calling a Method
o The return Keyword
o The void Keyword
o Passing Parameters by Values
Overloading Methods
o Method Overloading by changing the no. of arguments
o Method Overloading by changing data type of argument
o Method Overloaing is not possible by changing the return
type of method
The Scope of Variables
Exercise
Selvakumar.B
Java - Methods
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the System.out.println method, for example, the system actually
executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, overload methods using the same names, and apply
method abstraction in the program design.
Creating a Method:
In general, a method has the following syntax:
A method definition consists of a method header and a method body. Here are all the parts of
a method:
Modifiers: The modifier, which is optional, tells the compiler how to call the method.
This defines the access type of the method.
Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without
returning a value. In this case, the returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name and the
parameter list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a method.
Parameters are optional; that is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the
method does.
Selvakumar.B
Example:
Here is the source code of the above defined method called max(). This method takes two
parameters num1 and num2 and returns the maximum between the two:
return result;
}
Calling a Method:
There are two ways to call a method; the choice is based on whether the method returns a
value or not.
When a program calls a method, program control is transferred to the called method. A
called method returns control to the caller when its return statement is executed or when its
method-ending closing brace is reached.
Example:
Following is the example to demonstrate how to define a method and how to call it:
Selvakumar.B
The void Keyword:
Means it does not return any value back to the calling method. Following example gives a
program that declares a method named printGrade and invokes it to print the grade for a
given score.
Example:
public class TestVoidMethod {
Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3)
statement passes the actual string parameter, "Hello", to the parameter, message; passes 3 to
n; and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be
wrong.
Selvakumar.B
Overloading Methods:
If a class has multiple methods by same name but different parameters, it is known as
Method Overloading. The main advantage is increases the readability of the program
There are 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);
}
}
-------------------------------
30
40
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 Calculation{
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[]){
Calculation obj = new Calculation();
obj.sum(10.5, 10.5);
obj.sum(20, 20);
}
}
-------------
21.0
40
Selvakumar.B
C. Method Overloaing 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:
Example
class Calculation{
int sum(int a, int b){
System.out.println(a+b);
}
double sum(int a, int b){
System.out.println(a+b);
}
public static void main(String args[]){
Calculation obj = new Calculation();
int result=obj.sum(20, 20); //Compile Time Error
}
}
As displayed in the above diagram, byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int, long, float or double. The char datatype
can be promoted to int, long, float or double and so on
Selvakumar.B
A. Method Overloading with TypePromotion
class Calculation{
void sum(int a, long 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(20, 20);//now second int literal will be promoted to long
obj.sum(20, 20, 20);
}
}
----------------------
40
60
If there are matching type arguments in the method, type promotion is not performed.
class Calculation{
void sum(int a, int b){
System.out.println("int arg method invoked");
}
void sum(long a, long b){
System.out.println("long arg method invoked");
}
public static void main(String args[]){
Calculation obj = new Calculation();
obj.sum(20, 20);//now int arg sum() method gets invoked
}
}
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity
class Calculation{
void sum(int a, long b){
System.out.println("a method invoked");
}
void sum(long a, int b){
System.out.println("b method invoked");
}
public static void main(String args[]){
Calculation obj = new Calculation();
obj.sum(20, 20);//now ambiguity
}
}
------------------------
Compile Time Error
Selvakumar.B
The Scope of Variables:
A variable defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the
block that contains the variable. A local variable must be declared before it can be used.
You can declare a local variable with the same name multiple times in different non-
nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
Selvakumar.B
DAY-5 & 6
Selvakumar.B
Index
What is a package?
What is a Class?
Constructors
Access modifier?
o Default Access Modifier - No keyword:
o Public Access Modifier - public:
o Private Access Modifier - private:
o Protected Access Modifier - protected
Non Access modifier?
o Static Methods:
o The final Modifier:
o The abstract Modifier
o Synchronized Modifier:
Member level access is formulated as a table
This keyword
Super keyword
Exercise
Selvakumar.B
What is a package?
A package is a namespace that organizes a set of related classes and interfaces.
Conceptually you can think of packages as being similar to different folders on your
computer.
You might keep HTML pages in one folder, images in another, and scripts or applications
in yet another.
Because software written in the Java programming language can be composed of
hundreds or thousands of individual classes, it makes sense to keep things organized by
placing related classes and interfaces into packages.
Selvakumar.B
What is a Class?
Classes are the fundamental building blocks of a Java program. Basically its is a
program / file where we are going to write all our Java coding. The extension of the
file/program need to be .JAVA, from example from the below the file should be like
“TestClass.java”.
package …
import ..
….
<Access Modifier> class <Name of the class> extends <Class Name> implements <Interface>{
Java coding
...
...
}
Package sample
//sample program
Import java.io.*;
/*class stats from here*/
class TestClass{
int n1=100;
void add(){}
}
After creating java class you have to follow the following rules. These rules are
applicable for all java programs.
1. The package statement in program should come as first line of the program.
2. If you use any import statement and it has to come after package statement.
3. Comments can be placed anywhere in the program.
4. After import statement, you can define class definition or interface declaration etc,
5. There can be only one public class per file. (ie. you cannot have more than one public
class in single java program file)
6. The name of the file name should match with the name of the pubic class. If you have
only one class in a single file means it can be default access or public access.
7. A single java program file may have more than one non public classes, But there can
be only one public class.
Selvakumar.B
Constructors:
A constructor is a special method that is used to initialize a newly created object and
is called just after the memory is allocated for the object. It can be used to initialize the
objects, to required, or default values at the time of object creation. It is not mandatory for
the coder to write a constructor for the class
If we do not explicitly write a constructor for a class the java compiler builds a default
constructor for that class.
Each time a new object is created at least one constructor will be invoked. The main rule
of constructors is
Constructor overloading
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
Account(int a);
Account (int a, int b);
Account (String a, int b);
Access modifier?
Access modifiers specify who can access them (gives the visibility to class). A java
class can have two types of modifiers; there are Access modifiers and non-access modifiers.
There are four access modifiers used in java. They are public, private, protected, default
(declaring without an access modifer).
Default: Default means package level access. It CAN ONLY be accessed from ‟same
package‟.
Selvakumar.B
Public: It CAN be accessed from ANYWHERE
Private : It can be accessed only with in class. A class cannot have private as modifier.
Private modifier is applicable to only methods and variable of a class.
Protected: CAN be accessed from ‟same package‟ and a subclass existing in any package can
access. Protected modifier is applicable to only methods and variable of a class.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
Example:
Variables and methods can be declared without any modifiers, as in the following examples:
boolean processOrder() {
return true;
}
However if the public class we are trying to access is in a different package, then the public
class still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.
Example:
Selvakumar.B
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within
the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.
Variables that are declared private can be accessed outside the class if public getter methods
are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.
Example:
Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly.
So to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String), which sets
its value.
The protected access modifier cannot be applied to class and interfaces. Methods, fields
can be declared protected, however methods and fields in a interface cannot be declared
protected.
Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.
Example:
The following parent class uses protected access control, to allow its child class override
openSpeaker() method:
Selvakumar.B
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Static
The static keyword can be used with “static variables", "static methods", "static classes"
and "static blocks".
Static variable
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once, at the start of the execution. These variables
will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn‟t need any object
Selvakumar.B
Example
public class InstanceCounter {
private int numInstances = 0; private static int statisNumInstances = 0;
public static void myName(){
statisNumInstances = statisNumInstances +1;
numInstances = numInstances +2; //error
}
}
Example
public class InstanceCounter {
public static void main(String[] arguments) {
myName(); mySurName(); //error
}
public static void myName() { System.out.println("Selvakumar"); }
public void mySurName() { System.out.println("balraj"); }
}
Example
public class InstanceCounter {
public static void main(String[] arguments) {
myName();
new InstanceCounter().mySurName();
}
public static void myName() { System.out.println("Selvakumar"); }
public void mySurName() { System.out.println("balraj"); }
}
Static method
It is a method which belongs to the class and not to the object (instance)
A static method can access only static data. It cannot access non-static data (instance
variables)
A static method can call only other static methods and cannot call a non-static method
from it.
A static method can be accessed directly by the class name and doesn‟t need any object
A static method cannot refer to “this” or “super” keywords in anyway
Example
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
b++; //Constructor incrementing static variable b
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
Selvakumar.B
class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}
Value of a = 0
Value of a = 1
Value of a = 0
Value of a = 2
Static Blocks
Static blocks are also called Static initialization blocks . A static initialization block
is a normal block of code enclosed in braces, { }, and proceeded by the static keyword.
Here is an example:
static {
// whatever code is needed for initialization goes here
}
A static block helps to initialize the static data members, just like constructors help
to initialize instance members
A class can have any number of static initialization blocks, and they can appear
anywhere in the class body. The runtime system guarantees that static initialization blocks
are called in the order that they appear in the source code. And dont forget, this code will
be executed when JVM loads the class. JVM combines all these blocks into one single
static block and then executes. Here are a couple of points I like to mention:
you have executable statements in the static block, JVM will automatically execute
If
these statements when the class is loaded into JVM.
If you‟re referring some static variables/methods from the static blocks, these
statements will be executed after the class is loaded into JVM same as above i.e., now the
static variables/methods referred and the static block both will be executed.
Selvakumar.B
public StaticExample(){
System.out.println("This is constructor");
}
public static String staticString = "Static Variable";
static {
System.out.println("This is second static block and "+ staticString);
}
public static void main(String[] args){
StaticExample statEx = new StaticExample();
StaticExample.staticMethod2();
}
static {
staticMethod();
System.out.println("This is third static block");
}
public static void staticMethod() {
System.out.println("This is static method");
}
public static void staticMethod2() {
System.out.println("This is static method2");
}
}
This would produce following result:
You cannot declare a top-level class as a static class. Java will throw a compilation
error. Only inner classes that are member classes can be declared as static. If we declare
member classes as static, we can use it as a top-level class outside the context of top-level
class.
but when you want to use the static inner class, you need to instantiate like
Selvakumar.B
The final Modifier:
final Variables:
A final variable can be explicitly initialized only once. A reference variable declared
final can never be reassigned to refer to a different object.
However the data within the object can be changed. So the state of the object can be
changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class
variable.
Example:
Final Methods:
A final method cannot be overridden by any subclasses. As mentioned previously the
final modifier prevents a method from being modified in a subclass.
class Test1 {
public final void changeName(){
// body of method
}
}
----------------------
class Test extends Test1 {
public void changeName(){ // throws error
// body of method
}
}
Error(11,23): final method changeName () in class view.ExtendClass cannot be overridden by method changeName () in
class view.Example
Example:
You declare methods using the final modifier in the class declaration, as in the
following example:
Selvakumar.B
Final Classes:
The main purpose of using a class being declared as final is to prevent the class from
being subclassed. If a class is marked as final then no class can inherit any feature from the
final class.
Example:
A class cannot be both abstract and final. (since a final class cannot be extended). If a
class contains abstract methods then the class should be declared abstract. Otherwise a
compile error will be thrown.
An abstract class may contain both abstract methods as well normal methods.
Example:
Abstract Methods:
An abstract method is a method declared without any implementation. The methods
body(implementation) is provided by the subclass. Abstract methods can never be final
Any class that extends an abstract class must implement all the abstract methods of
the super class unless the subclass is also an abstract class.
If a class contains one or more abstract methods then the class must be declared
abstract. An abstract class does not need to contain abstract methods.
Selvakumar.B
The abstract method ends with a semicolon. Example: public abstract sample();
Example:
public abstract class SuperClass{
abstract void m(); //abstract method
}
Synchronized Modifier:
The synchronized key word used to indicate that a method can be accessed by only
one thread at a time. The synchronized modifier can be applied with any of the four access
level modifiers.
Example:
Selvakumar.B
Member level access is formulated as a table:
This keyword
this is a keyword in Java, which can be used inside method or constructor of class. It
works as a reference to current object whose method or constructor is being
invoked. this keyword can be used to refer any member of current object from within an
instance method or a constructor.
Example
class JBT {
int variable = 5;
Selvakumar.B
this keyword with Constructor
this keyword can be used to call Constructor with argument from Constructor without
argument.
this keyword can only be the first statement in Constructor.
A constructor can have either this or super keyword but not both.
Example
class JBT {
JBT() {
this("JBT");
System.out.println("Inside default Constructor");
}
JBT(String str) {
System.out.println("Inside Param Constructor " + str);
}
public static void main(String[] args) {
JBT obj = new JBT();
}
}
Output of above programme
void methodOne(){
System.out.println("Inside Method ONE");
}
void methodTwo(){
System.out.println("Inside Method TWO");
this.methodOne();// same as calling methodOne()
}
Selvakumar.B
Output of above programme
super keyword
super is a reference variable that is used to refer immediate parent class object.
Selvakumar.B
Bike b=new Bike();
}
}
-------------------
Vehicle is created
Bike is created
Selvakumar.B
DAY-7
Selvakumar.B
Index
Java exceptions
Types of Exception
o Checked Exception
o Unchecked Exception
o Error
Exception keywords
o try & catch
o try & final
o throw keyword
o throws keyword
User defined exception
Exercise
Selvakumar.B
Java exceptions?
An exception is a problem that arises during the execution of a program. An exception
can occur for many different reasons, including the following:
A network connection has been lost in the middle of communications, or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Types of Exception
Checked Exception
Unchecked Exception
Error
o IOException,
o SQLException etc.
Runtime exceptions: The classes that extend RuntimeException are known as unchecked
exceptions e.g.
o ArithmeticException,
o NullPointerException,
o ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. e.g.
o OutOfMemoryError,
o VirtualMachineError,
o AssertionError etc.
Selvakumar.B
Exception keywords
There are 5 keyword following that used in exceptions,
1. try
2. catch
3. finally
4. throw
5. throws
The catch block contains the code that handles the exceptions and may correct the
exceptions that ensure normal execution of the program. The catch block should immediately
follow the try block. We can have multiple catch blocks for a single try block. The catch block
executed only if there is any exception within the try block.
try{
......
......
}catch(Exception_class_Name reference){}
Example
class Excep4{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed");
}catch(Exception e){
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}
-----------------
task1 is completed
rest of the code...
Selvakumar.B
try & final
The finally block is always executed, regardless of whether or not an exception happens during
the try block, or whether an exception could be handled within the catch blocks. Since it
always gets executed, it is recommended that you do some cleanup here. Implementing the
finally block is optional.
If no exception occurs during the running of the try-block, all the catch-blocks are
skipped, and finally-block will be executed after the try-block.
If one of the statements in the try-block throws an exception, the Java runtime
ignores the rest of the statements in the try-block, and begins searching for a matching
exception handler. It matches the exception type with each of the catch-blocks sequentially. If
a catch-block catches that exception class or catches a superclass of that exception, the
statement in that catch-block will be executed. The statements in the finally-block are then
executed after that catch-block. The program continues into the next statement after the try-
catch-finally, unless it is pre-maturely terminated or branch-out.
Selvakumar.B
Example
class Simple{
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...");
}
}
-----------------
finally block is always executed
rest of the code...
The catch blocks and finally block must always appear in conjunction with a try
block.
A try block must be followed by either at least one catch block or one finally block.
The order exception handlers in the catch block must be from the most specific
exception
Final block gets executed even if we have the break or the or the continue statement
for the return statement it won‟t execute the final block.
Syntex:
try {
<code>
} catch (<exception type1><parameter1>) {
// 0 or more<statements>
} catch (<exception type1><parameter1>) {
// 0 or more<statements>
}
….
…..
finally {
// finally block<statements>
}
Selvakumar.B
throw keyword
The throw keyword is used to explicitly throw an exception. We can throw either checked
or uncheked exception. The throw keyword is mainly used to throw custom exception.
1. The throw statement causes termination of the normal flow of control of the java code
and stops the execution of the subsequent statements.
2. The throw clause transfers the control to the nearest catch block handling the type of
exception object throws.
Syntax
throw new ThrowableObj
Example
The below example the validate method that takes integer value as a parameter. If the age is
less than 18, we are throwing the ArithmeticException otherwise print a message welcome to
vote
class Excep13{
Selvakumar.B
throws keyword (User-defined Exceptions)
The throws keyword is used to declare an exception. Though Java provides an extensive
set of in-built exceptions, there are cases in which we may need to define our own exceptions
in order to handle the various application specific errors that we might encounter.
While defining an user defined exception, we need to take care of the following aspects:
The user defined exception class should extend from Exception class.
The toString() method should be overridden in the user defined exception class in
order to display meaningful information about the exception.
Simple example, how to define and make use of user defined exceptions.
EXAMPLE-1
NegativeAgeException.java
CustomExceptionTest.java
Selvakumar.B
EXAMPLE-2
MyDefinedException.java
MyClass.java
}catch(MyDefinedException mde) {
mde.printStackTrace();
}
}
}
Selvakumar.B
Object
Throwable
Exceptions Error
OutOfMemory
Error
Runtime IOExcepti
Exception on ThreadDeath
Others
VirtualMach
ineError
Others
Selvakumar.B
Runtime Exception The java.lang package defines the following exception
Other Exception
Below are some other type of exception.
CloneNotSupportedException This exception is thrown when the clone() method has been called
for an object that does not implement the Cloneable interface and
thus cannot be cloned.
Exception The appropriate subclass of this exception is thrown in response to
an error detected at the virtual machine level. If a program defines
its own exception classes, they should be subclasses of the Exception
class.
IllegalAccessException This exception is thrown when a program tries to dynamically load a
class (i.e., uses the forName() method of the Class class, or the
findSystemClass() or the loadClass() method of the ClassLoader
Selvakumar.B
# Exception Name Description
class) and the currently executing method does not have access to
the specified class because it is in another package and not public.
This exception is also thrown when a program tries to create an
instance of a class (i.e., uses the newInstance() method of the Class
class) that does not have a zero-argument constructor accessible to
the caller.
InstantiationException This exception is thrown in response to an attempt to instantiate an
abstract class or an interface using the newInstance() method of the
Class class.
InterruptedException This exception is thrown to signal that a thread that is sleeping,
waiting, or otherwise paused has been interrupted by another
thread.
NoSuchFieldException This exception is thrown when a specified variable cannot be found.
This exception is new in Java 1.1.
NoSuchMethodException This exception is thrown when a specified method cannot be found.
Error
Selvakumar.B
is changed after the class that references it was last compiled.
InternalError This error is thrown to signal an internal error within the virtual
machine.
LinkageError The appropriate subclass of this error is thrown when there is a
problem resolving a reference to a class. Reasons for this may
include a difficulty in finding the definition of the class or an
incompatibility between the current definition and the expected
definition of the class.
NoClassDefFoundError This error is thrown when the definition of a class cannot be found.
NoSuchFieldError This error is thrown in response to an attempt to reference an
instance or class variable that is not defined in the current definition
of a class. Usually this error is caught by the compiler; this error
can occur at run-time if the definition of a class is changed after the
class that references it was last compiled.
NoSuchMethodError This error is thrown in response to an attempt to reference a method
that is not defined in the current definition of a class. Usually this
error is caught by the compiler; this error can occur at run-time if
the definition of a class is changed after the class that references it
was last compiled.
OutOfMemoryError This error is thrown when an attempt to allocate memory fails.
StackOverflowError This error is thrown when a stack overflow error occurs within the
virtual machine.
ThreadDeath This error is thrown by the stop() method of a Thread object to kill
the thread. Catching ThreadDeath objects is not recommended. If it
is necessary to catch a ThreadDeath object, it is important to re-
throw the object so that it is possible to cleanly stop the catching
thread.
UnknownError This error is thrown when an error of unknown origins is detected in
the run-time system.
UnsatisfiedLinkError This error is thrown when the implementation of a native method
cannot be found.
VerifyError This error is thrown when the byte-code verifier detects that a class
file, though well-formed, contains some sort of internal
inconsistency or security problem.
VirtualMachineError The appropriate subclass of this error is thrown to indicate that the
Java virtual machine has encountered an error.
Selvakumar.B
DAY-8
Selvakumar.B
Index
Java beans
Java Collections
Commonly used methods of Collection interface
How to use an Iterator ?
o The Methods Declared by Iterator
ArrayList class?
o Hierarchy of ArrayList class
o Example of ArrayList:
List Interface
o Commonly used methods of List Interface
o Example
Map Interface / HashMap class
o Hierarchy of class
o Commonly used methods of Map interface
o Example
The Vector Class?
o Commonly used methods of Vector
o Example
Exercise
Selvakumar.B
Java beans
A JavaBean is a specially constructed Java class written in the Java and coded according
to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes:
JavaBeans Properties:
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation class:
Method Description
JavaBeans Example:
Consider a student class with few properties:
package com.hotcourses;
Selvakumar.B
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
Selvakumar.B
Java Collections
Collection simply means a single unit of objects. Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc)
Selvakumar.B
Commonly used methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
public boolean add(object element):
o is used to insert an element in this collection.
In general, to use an iterator to cycle through the contents of a collection, follow these steps:
Obtain an iterator to the start of the collection by calling the collection's iterator( )
method.
Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( )
returns true.
Selvakumar.B
The Methods Declared by Iterator:
SN Methods with Description
boolean hasNext( )
1
Returns true if there are more elements. Otherwise, returns false.
Object next( )
2
Returns the next element. Throws NoSuchElementException if there is not a next element.
Example
import java.util.*;
ArrayList class:
Uses a dynamic array for storing the elements. It extends AbstractList class and implements
List interface.
Can contain duplicate elements.
Maintains insertion order.
Not synchronized.
Random access because array works at the index basis.
Manipulation slows because a lot of shifting needs to be occurred.
Selvakumar.B
ArrayList class supports three constructors. The first constructor builds an empty array list:
ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity) - The capacity grows automatically as elements are added to an array list.
Example of ArrayList:
import java.util.*;
class Simple{
public static void main(String args[]){
class Simple{
public static void main(String args[]){
al.addAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
-----------------
Ravi
Vijay
Ajay
Sonoo
Hanumat
Selvakumar.B
Example of removeAll() method:
import java.util.*;
class Simple{
public static void main(String args[]){
al.removeAll(al2);
import java.util.*;
class Simple{
public static void main(String args[]){
al.retainAll(al2);
Selvakumar.B
Example storing data to a bean
class Student{
public int rollno;
public String name;
public int age;
import java.util.*;
class Simple{
public static void main(String args[]){
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
---------------------------
101 Selvakumar 44
102 Thangaraj 35
103 Sivapriya 12
List Interface
The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements.
Elements can be inserted or accessed by their position in the list, using a zero-based index.
In addition to the methods defined by Collection, List defines some of its own, which are
summarized in the following below Table.
Selvakumar.B
Commonly used methods of List Interface:
public void add(int index, Object element);
public boolean addAll(int index, Collection c);
public object get(int Indexposition);
public object set(int index, Object element);
public object remove(int index);
import java.util.*;
Selvakumar.B
==> While Loop Example....
eBay
Paypal
Google
Yahoo
Given a key and a value, you can store the value in a Map object. After the value is stored, you
can retrieve it by using its key.
It maintains no order
A NullPointerException is thrown if an attempt is made to use a null object and null is not
allowed in the map.
Hierarchy of class
Selvakumar.B
public boolean containsKey(Object key):
o is used to search the specified key from this map.
HashMap( )
HashMap(Map m)
HashMap(int capacity)
Example
import java.util.*;
}
}
Selvakumar.B
The Vector Class
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance, or you just
need one that can change sizes over the lifetime of a program.
The Vector class supports four constructors. The first form creates a default vector, which has an
initial size of 10:
Vector( )
The second form creates a vector whose initial capacity is specified by size:
Vector(int size)
The third form creates a vector whose initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of elements to allocate each time that a vector is
resized upward:
The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
Selvakumar.B
public Object lastElement()
o Returns the last component of the vector.
Example-1
import java.util.Vector;
Selvakumar.B
Example-2
import java.util.Iterator;
import java.util.Vector;
Selvakumar.B
DAY-9 & 10
Index
Selvakumar.B
What is JDBC?
Creating JDBC Application
o Import the package:
o Register the JDBC driver
o Open a connection
o Execute a query
o Clean up the environment
JDBC - Statements
o The Statement Objects
o The PreparedStatement Objects
o The CallableStatement Objects
SQLException Methods
JDBC - Data Types
Exercise
What is JDBC?
Selvakumar.B
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a wide
range of databases.
The JDBC library includes APIs for each of the tasks commonly associated with database
usage:
3. Open a connection:
This requires using the DriverManager.getConnection() method to create a Connection
object, which represents a physical connection with the database as follows:
Selvakumar.B
4. Execute a query:
This requires using an object of type Statement or PreparedStatement for building and
submitting an SQL statement to the database as follows:
Selvakumar.B
Example
Based on the above steps, we can have following consolidated sample code which we
can use as a template while writing our JDBC code:
Selvakumar.B
JDBC - Statements
Once a connection is obtained we can interact with the database. The
JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods
and properties that enable you to send SQL or PL/SQL commands and receive data from
your database.
Statement Use for general-purpose access to your database. Useful when you are using
static SQL statements at runtime. The Statement interface cannot accept
parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
Once you've created a Statement object, you can then use it to execute a SQL statement with one of its
three execute methods.
boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when
you need to use truly dynamic SQL.
int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the
SQL statement. Use this method to execute SQL statements for which you expect to get a number
of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you
expect to get a result set, as you would with a SELECT statement.
Selvakumar.B
Example
//STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
Selvakumar.B
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}catch(Exception e){
}//end try
}//end main
}//end JDBCExample
Connecting to database...
Creating statement...
Return value is : false
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
Selvakumar.B
The setXXX() methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter. If you forget to supply the values, you will
receive an SQLException.
Each parameter marker is referred to by its ordinal position. The first marker represents position 1,
the next position 2, and so forth. This method differs from that of Java array indices, which start at 0.
All of the Statement object's methods for interacting with the database (a) execute(), (b)
executeQuery(), and (c) executeUpdate() also work with the PreparedStatement object. However, the
methods are modified to use SQL statements that can take input the parameters.
Example
//STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
Selvakumar.B
try{
//finally block used to close resources
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}catch(Exception e){
}//end try
}//end main
}//end JDBCExample
Connecting to database...
Creating statement...
Rows impacted : 1
Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all three.
Parameter Description
A parameter whose value is unknown when the SQL statement is created. You bind
IN
values to IN parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You retrieve
OUT
values from theOUT parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables with the
INOUT
setXXX() methods and retrieve values with the getXXX() methods.
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate
aCallableStatement object based on the preceding stored procedure:
Selvakumar.B
. . .
}
catch (SQLException e) {
. . .
}
finally {
try{
. . .
cstmt.close();
}catch(Exception e){
}
The String variable SQL represents the stored procedure, with parameter placeholders.
If you have IN parameters, just follow the same rules and techniques that apply to a
PreparedStatement object; use the setXXX() method that corresponds to the Java data type you are
binding.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the
appropriate getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Example
//STEP 1. Import required packages
import java.sql.*;
// Database credentials
static final String USER = "username";
static final String PASS = "password";
Selvakumar.B
//Retrieve employee name with getXXX method
String empName = stmt.getString(2);
System.out.println("Emp Name with ID:" +empID + " is " + empName);
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
try{
//finally block used to close resources
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}catch(Exception e){
}//end try
}//end main
}//end JDBCExample
Connecting to database...
Creating statement...
Executing stored procedure...
Emp Name with ID:102 is Zaid
SQLException Methods:
A SQLException can occur both in the driver and the database. When such an exception
occurs, an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving
additional information about the exception:
Method Description
Gets the JDBC driver's error message for an error handled by the
getMessage( ) driver or gets the Oracle error number and message for a
database error.
By utilizing the information available from the Exception object, you can catch an exception
and continue your program appropriately. Here is the general form of a try block:
Selvakumar.B
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
ResultSet object provides corresponding getXXX() method for each data type to retrieve
column value. Each method can be used with column name or by its ordinal position.
Selvakumar.B
DAY-11
Selvakumar.B