0% found this document useful (0 votes)
95 views

Hotcourses Java

The document provides an overview of Java programming concepts including: 1) It defines Java as a platform independent, object oriented programming language that is compiled to bytecode rather than machine code. 2) It discusses getting started with Java programming including creating a Java application with a basic "Hello World" program, compiling and running source code files, and naming conventions. 3) It covers Java programming fundamentals such as variables, data types, casting, and variable scopes including instance variables, class variables, local variables, and parameters.

Uploaded by

vishnuselva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

Hotcourses Java

The document provides an overview of Java programming concepts including: 1) It defines Java as a platform independent, object oriented programming language that is compiled to bytecode rather than machine code. 2) It discusses getting started with Java programming including creating a Java application with a basic "Hello World" program, compiling and running source code files, and naming conventions. 3) It covers Java programming fundamentals such as variables, data types, casting, and variable scopes including instance variables, class variables, local variables, and parameters.

Uploaded by

vishnuselva
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 117

Selvakumar.

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 :

HLL: Java is High Level language .

The fundamentals of Java came from a programming language called c++.

Platform Independent: Java was written to be a portable language that doesn't care about
the operating system or the hardware of the computer

Java supports Multithreading.

Java supports automaticGarbagecollection and make lot of programming problems simple.

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

 Getting Started Programming in Java


Creating a Java Application

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)

Compiling and Running the Source File?

 JAVA (Compiler)
 JAVAC (Interpreter JVM)

Selvakumar.B
Naming conventions

Selvakumar.B
 Java comments
Comments can be specified in several ways:

 Using // All characters after // are treated as comments by the compiler.

 Using /* and */A multi-line comment is enclosed between a /* and */ pair

 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.

Rules in creating the variable


Java language has its own set of rules and conventions for the kinds of names that you're
allowed to use

 Variable names are case-sensitive.


 The variables need to be formed with the below character sets
o Unicode letters and digits (A-Z, a-z, 0-9)
o Dollar sign "$"
o Underscore character "_" (Connecting character).
 The variable should always beginning with a letter, the dollar sign "$", or the
underscore character "_".
 Subsequent characters may be letters, digits, dollar signs, or underscore characters.
 White space is not permitted.
 Unlimited-length
 Variable not be a java Keywords
 If no value is assigned prior to use, then the compiler will give an error

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

Java Primitive Data Types


Type Contains Default Size Range
boolean true or false false 1 bit NA
char Unicode character \u0000 16 bits \u0000 to \uFFFF
byte Signed integer 0 8 bits -128 to 127
short Signed integer 0 16 bits -32768 to 32767
int Signed integer 0 32 bits -2147483648 to 2147483647
-9223372036854775808 to
long Signed integer 0 64 bits
9223372036854775807
float floating point 0.0 32 bits ±1.4E-45 to ±3.4028235E+38
±4.9E-324 to
double floating point 0.0 64 bits
±1.7976931348623157E+308
Objects null

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;

Incorrect data assignment


byte b = 180; // The compiler does not allow this
short s =32768; // The compiler does not allow this
int i = 13;
byte b = i; // The compiler does not allow this

--------------------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

To/From byte char short Int long Float double

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

Float Assignable Assignable Assignable Assignable Assignable Assignable Cast needed

Double Assignable Assignable Assignable Assignable Assignable Cast needed Assignable

Boolean No No No No No No No

Examples

public class Example {


public Example() {}
public static void main(String[] args) {
byte b = 122;
char c ='A';
short s = 32760;
int i = 10;
long l = 234;
float f = 58.23f;
double d = 67.123;
i = b;
i = c;
i = s;
i = i;
i = (int)l;
i = f;
i = (int)d;
}
}
--------------------Configuration: <Default>--------------------
C:\Example.java:17: possible loss of precision
found : float
required: int
i = f;
^
1 error

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:

byte short int long  float  double.

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.

// 64 bit long integer


long myLongInteger = 0;
// 32 bit standard integer
int myInteger = 0 ;
myLongInteger = myInteger;

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.

// 64 bit long integer


long myLongInteger = 0;
// 32 bit standard integer
int myInteger = 0 ;
myInteger = (int) myLongInteger;

Selvakumar.B
Variable Types

 Instance Variables (Non-Static Fields)


Non-static fields are also known as instance variables because their values are unique
to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is
independent from the currentSpeed of another.

String myName = „Selvakumar”;

public class Example {


public Example() {}
String myName = "Selvakumar";
public static void main(String[] args) {
Example E1 = new Example();
System.out.println(E1.myName);
Example E2 = new Example();
System.out.println(E2.myName);
E2.myName = "Raj";
System.out.println(E1.myName);
System.out.println(E2.myName);
}
}

Selvakumar
Selvakumar
Selvakumar
Raj

 Class Variables (Static Fields)


A class variable is any field declared with the static modifier; this tells the compiler
that there is exactly one copy of this variable in existence; regardless of how many times the
class has been instantiated.
static String myName = „Selvakumar”;

public class Example {


public Example() {}
static String myName = "Selvakumar";
public static void main(String[] args) {
Example E1 = new Example();
System.out.println(E1.myName);
Example E2 = new Example();
System.out.println(E2.myName);
E2.myName = "Raj";
System.out.println(E1.myName);
System.out.println(E2.myName);
}
}

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.

Convert String to character


charAt(index)
This method returns the character located at the String's specified index. The string
indexes start from zero.

Syntax:
public char charAt(int index)

 index -- Index of the character to be returned.

 This method Returns a char at the specified index.

 Example:
public class Test {

public static void main(String args[]) {


String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}

This produces following result:

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

No Methods with Description


1 char charAt(int index)
Returns the character at the specified index.
Example
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces following result:
a

2 String concat(String str)


Concatenates the specified string to the end of this string.This methods returns a string that
represents the concatenation of this object's characters followed by the string argument's
characters.

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

3 boolean equals(Object anObject)


Compares this string to the specified object. This method returns true if the String are equal;
false otherwise.

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

4 boolean equalsIgnoreCase(String anotherString)


Compares this String to another String, ignoring case considerations.his method returns true if
the argument is not null and the Strings are equal, ignoring case; false otherwise

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

5 int indexOf(int ch)


Returns the index within this string of the first occurrence of the specified character.
6 int indexOf(intch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting
the search at the specified index.
7 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
8 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at
the specified index.
Example
import java.io.*;

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

9 int lastIndexOf(int ch)


Returns the index within this string of the last occurrence of the specified character.
10 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.
11 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
12 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.
Example
import java.io.*;

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 Last Index :" );
System.out.println(Str.lastIndexOf( 'o' ));
System.out.print("Found Last Index :" );
System.out.println(Str.lastIndexOf( 'o', 5 ));
System.out.print("Found Last Index :" );
System.out.println( Str.lastIndexOf( SubStr1 ));
System.out.print("Found Last Index :" );
System.out.println( Str.lastIndexOf( SubStr1, 15 ));

Selvakumar.B
System.out.print("Found Last Index :" );
System.out.println(Str.lastIndexOf( SubStr2 ));
}
}

This produces following result:


Found Last Index :23
Found Last Index :4
Found Last Index :11
Found Last Index :11
Found Last Index :-1

13 int length()
Returns the length of this string
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str1 = new String("Welcome to Hotcourses.com");
String Str2 = new String("Hotcourses" );
System.out.print("String Length :" );
System.out.println(Str1.length());
System.out.print("String Length :" );
System.out.println(Str2.length());
}
}
This produces following result:
String Length :25
String Length :10

14 String replace(char oldChar, char newChar)


Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.replace('o', 'T'));
System.out.print("Return Value :" );
System.out.println(Str.replace('l', 'D'));
}
}
This produces following result:
eturn Value :WelcTmetTHTtcTurses.cTm
Return Value :WeDcome to Hotcourses.com

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.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.replaceAll("(.*)Hotcourses(.*)","AMROOD" ));
}
}
This produces following result:
Return Value :AMROOD

16 String replaceFirst(String regex, String replacement)


Replaces the first substring of this string that matches the given regular expression with the
given replacement.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.replaceFirst("(.*)Hotcourses(.*)","AMROOD" ));
System.out.print("Return Value :" );
System.out.println(Str.replaceFirst("Hotcourses", "AMROOD" ));
}
}
This produces following result:
Return Value :AMROOD
Return Value :Welcome to AMROOD.com

17 String[] split(String regex)


Splits this string around matches of the given regular expression.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome-to-Hotcourses.com");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 2)){
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 3)){
System.out.println(retval);

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

18 boolean startsWith(String prefix)


Tests if this string starts with the specified prefix.
19 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Welcome") );

System.out.print("Return Value :" );


System.out.println(Str.startsWith("Hotcourses") );

System.out.print("Return Value :" );


System.out.println(Str.startsWith("Hotcourses", 11) );
}

Selvakumar.B
}
This produces following result:
Return Value :true
Return Value :false
Return Value :true

20 String substring(int beginIndex)


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

21 String substring(in tbeginIndex, int endIndex)


Returns a new string that is a substring of this string.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.substring(10) );
System.out.print("Return Value :" );
System.out.println(Str.substring(10, 15) );
}
}
This produces following result:
Return Value : Hotcourses.com
Return Value : Hotc

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.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :");
System.out.println(Str.toLowerCase());
}
}
This produces following result:
Return Value :welcome to hotcourses.com

23 String toString()
This object (which is already a string!) is itself returned.
Example
import java.io.*;

public class Test {


public static void main(String args[]) {

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.*;

public class Test{


public static void main(String args[]){
String Str = new String("Welcome to Hotcourses.com");
System.out.print("Return Value :" );
System.out.println(Str.toUpperCase() );
}
}
This produces following result:
Return Value :WELCOME TO HOTCOURSES.COM

25 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
Example
import java.io.*;

public class Test{


public static void main(String args[]){
String Str = new String(" Welcome to Hotcourses.com ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
}
}
This produces following result:
Return Value :Welcome to Hotcourses.com

26 static String valueOf(primitive data type x)


Returns the string representation of the passed data type argument.

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.*;

public class Test{


public static void main(String args[]){
double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };

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


System.out.println("Return Value : " + String.valueOf(b) );
System.out.println("Return Value : " + String.valueOf(l) );
System.out.println("Return Value : " + String.valueOf(arr) );
}
}
This produces following result:
Return Value : 1.02939939939E8
Return Value : true
Return Value : 1232874
Return Value : abcdefg

Selvakumar.B
NumberMethods

SN Methods with Description


1 xxxValue()
Converts the value of this Number object to the xxx data type and returned it.

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() );

// Returns double primitive data type


System.out.println(x.doubleValue());

// Returns long primitive data type


System.out.println( x.longValue() );
}
}
This produces following result:
5
5.0
5

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:

Escape Sequence Description

\t Insert a tab in the text at this point.

\b Insert a backspace in the text at this point.

\n Insert a newline in the text at this point.

\r Insert a carriage return in the text at this point.

\f Insert a form feed in the text at this point.

\' Insert a single quote character in the text at this point.

\" Insert a double quote character in the text at this point.

\\ Insert a backslash character in the text at this point.

Example
If you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes:

public class Test {


public static void main(String args[]) {
System.out.println("She said \"Hello!\" to me.");
}
}
This produces following result:
She said "Hello!" to me.

SN Methods with Description


1 isLetter()
Determines whether the specified char value is a letter.
booleanisLetter(char ch)

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.

String toString(char ch)


Example
public class Test{
public static void main(String args[]){
System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}
This produces following result:
c
C

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.

This section describes the decision-making statements (if-then, if-then-else, if-elseif- -


else,switch), the looping statements (for, while, do-while), and the branching statements
(break, continue, return) supported by the Java programming language.

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.

if (a = = 3) is a Boolean test condition. This statement is true ONLY if the value


stored ina is the number 3.

Examples:

// using a character literal // logically true


if (grade = = 'A'){ if (true){
System.out.println("Frig Grade"); System.out.print("The x is true!");
} }
// using two variables // using a calculation
if(enemyCount<heroCount){ if (cost * number = = paycheck){
System.out.print("Good wins!"); inventory = 0;
} }

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 (population >= 543876){


System.out.println(state + " is one of \n the 100 largest states.");
}else{
System.out.println(state + " is not one of \n the 100 largest states.");
}

The "if-else if-else" Statement

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");
}

The "switch" Statement

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;
}
}

 Java Loop Control

looping statements
 The FOR Loop
 Nested FOR Loops
 The WHILE Loop
 The DO-WHILE Loop

The "for" loop Statement

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:

for(startExpression; testExpression; countExpression) {


block of code;
}

The startExpression is evaluated before the loop begins. It is acceptable to declare


and assign in thestartExpression (such as int x = 1;). Java evaluates the startExpression
only once, at the beginning of the loop.

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;
}

//the loop finished, the value 16 is stored in x.


for(x = 0; x <= 15; x++)
System.out.println("Patty");

The nested "for" loop Statement


The placing of one loop inside the body of another loop is called nesting. When you
"nest" two loops, the outer loop takes control of the number of complete repetitions of the
inner loop. While all types of loops may be nested, the most commonly nested loops are for
loops.

When working with nested loops, the outer loop changes only after the inner loop is
completely finished (or is interrupted.).

The "while" loop Statement


The while loop allows programs to repeat a statement or series of statements, over and over,
as long as certain test condition is true.

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*/

The "do-while" loop Statement


The do-while loop is similar to the while loop, except that the test condition occurs at the end
of the loop. This guarantees that the body of the loop always executes at least once.

do {
block of code;
}while (test condition);

The test condition must be enclosed in parentheses and FOLLOWED BY A SEMI-COLON.


Semi-colons also follow each of the statements within the block. The body of the loop (the block of
code) is enclosed in braces and indented for readability. (The braces are not required if only ONE
statement is used in the body of the loop.)

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

The " BREAK" Statement


The break statement gets you out of a loop. No matter what the loop's ending condition,
break immediately says "I'm out here!" The program continues with the next statement immediately
following the loop. Break stops only the loop in which it resides. It does not break out of a "nested
loop" (a loop within a loop).

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;
}
}
}

The "CONTINUE" Statement


Continue performs a "jump" to the next test condition in a loop. The test condition is then
evaluated as usual, and the loop is executed as long as the test condition remains true. The continue
statement may be used ONLY in iteration statements (loops). It serves to bypass a portion of the body
of the loop within iteration.

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;
}
}
}

The "RETURN" Statement


The last of the branching statements is the return statement. The return statement exits from
the current MEthod, and control flow returns to where the method was invoked. The return statement
has two forms: one that returns a value, and one that doesn't. To return a value, simply put the value
after the return keyword.

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.

Declaring/ Creating Array Variables:


data-type[] identifier =new data-type[n]; or
data-type identifier[]=new data-type[n]; or
data-type identifier[]=new data-type[]{values};
data-type identifier[]={values};

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:

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This would produce following result:

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} };

Array Default Values

After you instantiate an array, default values are automatically assigned to it in the following manner. String[]
anArray = new String[10];

Data types Default value

byte 0

char ‘\u0000′.
short 0

int 0

long 0L

float 0.0f

double 0.0d

boolean False

reference types Null

String null

Selvakumar.B
Common array exceptions
 NullPointerException is accessing a null from a java array

String[] anArray = new String[10];


anArray[8].trim();

==========================================================
Exception in thread "main" java.lang.NullPointerException
atExample.main(Example.java:5)

Process completed.
==========================================================

 ArrayIndexOutOfBoundsException when you access an array with an illegal index that is


with a negative number or with a number greater than or equal to its size.

String[] anArray = new String[10];


anArray[11]

==============================================================
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:

modifier returnValueType methodName(list of parameters) {


// Method body;
}

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 the max between two numbers */


public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;

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.

The return Keyword:


If the method returns a value, a call to the method is usually treated as a value. For example:

String name = printMyName();

Example:
Following is the example to demonstrate how to define a method and how to call it:

public class TestName {


/** Main method */
public static void main(String[] args) {
String name = printMyName();
System.out.println("My name is ” + name);
}

public static String printMyName () {


return “Balraj selvakumar”;
}
}

This would produce following result:

My name is 5 Balraj selvakumar

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 {

public static void main(String[] args) {


printGrade(78.5);
}

public static void printGrade(double score) {


if (score >= 90.0) {
System.out.println('A');
}
else if (score >= 80.0) {
System.out.println('B');
}
else if (score >= 70.0) {
System.out.println('C');
}
else if (score >= 60.0) {
System.out.println('D');
}
else {
System.out.println('F');
}
}
}

This would produce following result:

Passing Parameters by Values:


When calling a method, you can provide arguments, which must be given in the same order
as their respective parameters in the method specification. This is known as parameter order
association.

For example, the following method prints a message n times:

public static void nPrintln(String message, int n) {


for (int i = 0; i < n; i++)
System.out.println(message);
}

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

Different ways to overload the method


 By changing number of arguments
 By changing the data type

A. Method Overloading by changing the no. of arguments

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

B. 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 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
}
}

 Method Overloading and TypePromotion

One type is promoted to another implicitly if no matching datatype is found.

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

B. Method Overloading with TypePromotion if matching found

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
}
}

C Method Overloading with TypePromotion in case ambiguity

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

 It has the same name as the class


 It should not return a value not even void
 If used ,the keyword super needs to be the first line of code in the constructor of the
child class
Example of a constructor is given below:

public class Puppy{


public puppy(){ }
public puppy(String name){ }
}

 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

Examples of valid constructors for class Account are

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.

 Default Access Modifier - No keyword:


Default access modifier means we do not explicitly declare an access modifier for a class,
field, method etc.

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:

String version = "1.5.1";

boolean processOrder() {
return true;
}

 Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed from any other
class. Therefore fields, methods, blocks declared inside a public class can be accessed from
any class belonging to the Java Universe.

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:

The following function uses public access control:

public static void main(String[] arguments) {


// ...
}

The main() method of an application has to be public. Otherwise, it could not be


called by a Java interpreter (such as java) to run the class.

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:

The following class uses private access control:

public class Logger {


private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

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.

 Protected Access Modifier - protected:


Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.

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
}
}

Here if we define openSpeaker() method as private then it would not be accessible


from any other class other than AudioPlayer. If we define it as public then it would become
accessible to all the outside world. But our intension is to expose this method to its subclass
only, thats why we usedprotected modifier.

 Non Access modifier?


Java provides a Five non access modifiers to achieve many other functionality. They are
static, final, abstract, synchronized and volatile

 The static modifier for creating class methods and variables


 The final modifier for finalizing the implementations of classes, methods, and
variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

 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

Syntax : static <return=type> <class-name>.<variable-name>


Example
public class InstanceCounter {
private int numInstances = 0;
private static int statisNumInstances = 0;

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

Syntax : public static <return=type> <method-name>(){}


<class-name>.<method-name>

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();
}
}

This would produce following result:

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.

public class StaticExample{


static {
System.out.println("This is first static block");
}

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:

This is first static block


This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2

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.

<<Class Name>>.<<Variable Name>>

but when you want to use the static inner class, you need to instantiate like

<<Top-level class name>>.<<Inner static class name>> newClass = new <<Top-level


class name>>.<<Inner static class name>>();

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:

public class Test{


final int value = 10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";

public void changeValue(){


value = 12; //will give an error
}
}

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:

public class Test{


public final void changeName(){ // body of method}
}

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:

public final class Test {


// body of class
}

public class Test extends Test1{


// body of class
}
----------------------------------
public final class Test1 {
// body of class
}

 The abstract Modifier:


Abstract Class:
An abstract class can never be instantiated. If a class is declared as abstract then the
sole purpose is for the class to be extended.

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 class Caravan{


private double price;
private String model;
private String year;
public abstract void goFast(); //an abstract method
public abstract void changeColor();
}

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
}

class SubClass extends SuperClass{


// implements the abstract method
void m(){
.........
}
}

 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:

public synchronized void showDetails(){


.......
}

Selvakumar.B
Member level access is formulated as a table:

Access Modifiers Same Class Same Package Subclass Other packages


public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N

 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.

 this keyword with field(Instance Variable)


this keyword can be very useful in case of Variable Hiding. We can not create two
Instance/Local Variable with same name. But it is legal to create One Instance Variable &
One Local Variable or Method parameter with same name. In this scenario Local Variable
will hide the Instance Variable which is called Variable Hiding.

Example
class JBT {
int variable = 5;

public static void main(String args[]) {


JBT obj = new JBT();
obj.method(20);
}

void method(int variable) {


variable = 10;
System.out.println("Value of Instance variable :" +
this.variable);
System.out.println("Value of Local variable :" +
variable);
}
}
Output of the above programme

Value of Instance variable :5


Value of Local variable :10

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

Inside Param Constructor JBT


Inside default Construct

 this keyword with Method


this keyword can also be used inside methods to call another method from same class.
Example
class JBT {
public static void main(String[] args) {
JBT obj = new JBT();
obj.methodTwo();
}

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

Inside Method TWO


Inside Method ONE

 super keyword
super is a reference variable that is used to refer immediate parent class object.

 super is used to refer immediate parent class instance variable.


 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

1. Example calling the parent variable


class Vehicle{
int speed=50;
}

class Bike extends Vehicle{


int speed=100;
void display(){
System.out.println(super.speed);
}

public static void main(String args[]){


Bike b=new Bike();
b.display();
}
}
------------------
50

2. Example calling the parent constructor


class Vehicle{
Vehicle(){
System.out.println("Vehicle is created");
}
}

class Bike extends Vehicle{


Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){

Selvakumar.B
Bike b=new Bike();
}
}
-------------------
Vehicle is created
Bike is created

3. Example calling the parent method


class Person{
void message(){
System.out.println("welcome");
}
}

class Student extends Person{


void message(){
System.out.println("welcome to java");
}
void dislay(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[]){


Student s=new Student();
s.display();
}
}
---------------------------
welcome to java
welcome

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 user has entered invalid data.

 A file that needs to be opened cannot be found.

 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

 Checked exceptions: A checked exception is an exception that is typically a user error or


a problem that cannot be foreseen by the programmer. e.g.

o IOException,
o SQLException etc.

Checked exceptions are checked at compile-time.

 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

 try & catch


Enclose the code that might throw an exception in try block. It must be used within the
method and must be followed by either catch or finally block.

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.

Syntax of try with catch 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.

Before terminating the program, JVM executes finally block(if any)

Syntax of try with catch finally


try{
......
......
}finally{}

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...

Rules for try, catch and finally Blocks


 For each try block there can be zero or more catch blocks, but only one finally block.

 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.

Using the throw Statement

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.

3. If no such catch block exists, the program terminates.

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{

static void validate(int age){


if(age < 18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}

public static void main(String args[]){


validate(13);
System.out.println("rest of the code...");
}
}
---------------
Exception in thread main java.lang.ArithmeticException:not valid

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.

Syntax of throws keyword:

void method_name() throws exception_class_name{


...
}

Simple example, how to define and make use of user defined exceptions.
EXAMPLE-1
NegativeAgeException.java

public class NegativeAgeException extends Exception {

private int age;

public NegativeAgeException(int age){


this.age = age;
}

public String toString(){


return "Age cannot be negative" + " " +age ;
}
}

CustomExceptionTest.java

public class CustomExceptionTest {

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

int age = -10;

if (age < 0){


throw new NegativeAgeException(age);
}else{
System.out.println("Age entered is " + age);
}
}
}

Selvakumar.B
EXAMPLE-2

MyDefinedException.java

class MyDefinedException extends Exception {

public MyDefinedException(String str) {


super(str);
}
}

MyClass.java

Public class MyClass {

public static void main(String a[]) {


try{

String str = "What is your Name?";


if(str.equals("What is your Name?")){
thrownew MyDefinedException("My name is Blah Blah");
}

}catch(MyDefinedException mde) {
mde.printStackTrace();
}
}
}

 Difference between throw and throws:


1. throw is used to explicitly throw an throws is used to declare an exception.
exception.
2. checked exception can not be checked exception can be propagated with throws.
propagated without throws.
3. throw is followed by an instance. throws is followed by class.
4. throw is used within the method. throws is used with the method signature.
5. You cannot throw multiple You can declare multiple exception e.g. public void
exception method()throws IOException, SQLException.

Selvakumar.B
Object

Throwable

Exceptions Error

OutOfMemory
Error

Runtime IOExcepti
Exception on ThreadDeath
Others

VirtualMach
ineError

Others

ClassCastExcepti NullPointerEx ArithmeticExc


on ception eption

ArrayIndexOutOfBound NumberFormatExc IllegalArgument


sException eption Exception
Others

Selvakumar.B
Runtime Exception The java.lang package defines the following exception

Below are some run time exception.

# Exception Name Description


 ArithmeticException This exception is thrown to indicate an exceptional arithmetic
condition, such as integer division by zero.
 ArrayIndexOutOfBoundsException This exception is thrown when an out-of-range index is
detected by an array object. An out-of-range index occurs when
the index is less than zero or greater than or equal to the size of
the array.
 ClassCastException This exception is thrown when there is an attempt to cast a
reference to an object to an inappropriate type.
 IndexOutOfBoundsException The appropriate subclass of this exception
(i.e.,ArrayIndexOutOfBoundsException or String
IndexOutOfBoundsException) is thrown when an array or
string index is out of bounds.
 NegativeArraySizeException This exception is thrown in response to an attempt to create an
array with a negative size.
 NullPointerException This exception is thrown when there is an attempt to access an
object through a null object reference. This can occur when
there is an attempt to access an instance variable or call a
method through a null object or when there is an attempt to
subscript an array with a null object.
 NumberFormatException This exception is thrown to indicate that an attempt to parse
numeric information in a string has failed.
 SecurityException This exception is thrown in response to an attempt to perform
an operation that violates the security policy implemented by
the installed SecurityManager object.
StringIndexOutOfBoundsException This exception is thrown when a String or StringBuffer object
detects an out-of-range index. An out-of-range index occurs
when the index is less than zero or greater than or equal to the
length of the string.

Other Exception
Below are some other type of exception.

# Exception Name Description


 ClassNotFoundException This exception is thrown to indicate that a class that is to be loaded
cannot be found.

 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

Below are some error type exception.

## Exception Name Description


 AbstractMethodError This error is thrown in response to an attempt to invoke an abstract
method.
 ClassCircularityError This error is thrown when a circular reference among classes is
detected during class initialization.
 ClassFormatError This error is thrown when an error is detected in the format of a file
that contains a class definition.
 Error The appropriate subclass of this error is thrown when an
unpredictable error, such as running out of memory, occurs.
Because of the unpredictable nature of these errors, methods that
can throw objects that are instances of Error or one of its subclasses
are not required to declare that fact in their throws clauses.
 ExceptionInInitializerError This error is thrown when an unexpected exception is thrown in a
static initializer. This error is new in Java 1.1.
 IllegalAccessError This error is thrown when a class attempts to access a field or call a
method it does not have access to. Usually this error is caught by the
compiler; this error can occur at run-time if the definition of a class
changes after the class that references it was last compiled.
 IncompatibleClassChangeError This error or one of its subclasses is thrown when a class refers to
another class in an incompatible way. This situation occurs when
the current definition of the referenced class is incompatible with the
definition of the class that was found when the referring class was
compiled. For example, say class A refers to a method in class B.
Then, after class A is compiled, the method is removed from class B.
When class A is loaded, the run-time system discovers that the
method in class B no longer exists and throws an error.
 InstantiationError This error is thrown in response to an attempt to instantiate an
abstract class or an interface. Usually this error is caught by the
compiler; this error can occur at run-time if the definition of a class

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:

 It provides a default, no-argument constructor.


 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.
 Properties need to be declared as private
 Properties access via public method

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

For example, if property name is firstName, your method name would


getPropertyName()
be getFirstName() to read that property. This method is called accessor.

For example, if property name is firstName, your method name would


setPropertyName()
be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only


attribute will have only a setPropertyName() method.

JavaBeans Example:
Consider a student class with few properties:

package com.hotcourses;

public class StudentsBean


{
public StudentsBean() {}

private String firstName = null;


private String lastName = null;
private int age = 0;

Selvakumar.B
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}

public String getLastName(){


return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}

public int getAge(){


return age;
}
public void setAge(Integer age){
this.age = age;
}
}

Selvakumar.B
 Java Collections

Collection Framework provides an architecture to store and manipulate the group of


objects. All the operations that you perform on a data such as searching, sorting, insertion,
deletion etc. can be performed by Java Collection Framework.

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.

 public boolean addAll(collection c):


o is used to insert the specifed collection elements in the invoking collection.
 public boolean remove(object element):
o is used to delete an element from this collection.

 public boolean removeAll(Collection c):


o is used to delete all the elements of specified collection from the invoking
collection.

 public boolean retainAll(Collection c):


o is used to delete all the elements of invoking collection except the specified
collection.

 public int size():


o return the total number of elements in the collection.

 public void clear():


o removes the total no of element from the collection.

 public boolean contains(object element):


o is used to search an element.

 public boolean containsAll(collection c):


o is used to search the specified collection in this collection.

 public Iterator iterator():


o returns an iterator.

 How to use an Iterator ?


Often, you will want to cycle through the elements in a collection. For example, you might
want to display each element. Each of the collection classes provides an iterator( ) method
that returns an iterator to the start of the collection. By using this iterator object, you can
access each element in the collection, one element at a time.

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.

 Within the loop, obtain each element by calling next( ).

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.*;

public class IteratorDemo {

public static void main(String args[]) {


// Create an array list
ArrayList alist = new ArrayList();

Iterator itr = alist.iterator();


while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element);
}
}
}

 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.

 Hierarchy of ArrayList class

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[]){

ArrayList al = new ArrayList();


al.add("Selvakumar");
al.add("Bala");
al.add("Gayathri");
al.add("Latha.T");

Iterator itr = al.iterator();


while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
-------------------
Selvakumar
Bala
Gayathri
Latha.T

Example of addAll(Collection c) method:


import java.util.*;

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

ArrayList al=new ArrayList();


al.add("Ravi"); al.add("Vijay"); al.add("Ajay");

ArrayList al2=new ArrayList();


al2.add("Sonoo"); al2.add("Hanumat");

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[]){

ArrayList al=new ArrayList();


al.add("Ravi"); al.add("Vijay"); al.add("Ajay");

ArrayList al2=new ArrayList();


al2.add("Ravi"); al2.add("Hanumat");

al.removeAll(al2);

System.out.println("iterating elements after removing elements of al2");


Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
---------------------
iterating elements after removing elements of al2
Vijay
Ajay

Example of retainAll() method:

import java.util.*;
class Simple{
public static void main(String args[]){

ArrayList al=new ArrayList();


al.add("Ravi"); al.add("Vijay"); al.add("Ajay");

ArrayList al2=new ArrayList();


al2.add("Ravi"); al2.add("Hanumat");

al.retainAll(al2);

System.out.println("iterating elements after retaining elements of al2");


Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
-----------------------------------
iterating elements after retaining elements of al2
Ravi

Selvakumar.B
Example storing data to a bean

class Student{
public int rollno;
public String name;
public int age;

public Student(int rollno, String name, int age){


this.rollno = rollno;
this.name = name;
this.age = age;
}
}

import java.util.*;
class Simple{
public static void main(String args[]){

Student s1 = new Student(101,"Selvakumar",44);


Student s2 = new Student(102,"Thangaraj",35);
Student s3 = new Student(103,"Sivapriya",12);

ArrayList al=new ArrayList();


al.add(s1);
al.add(s2);
al.add(s3);

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.

 A list may contain duplicate elements.

 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.*;

public class CollectionsDemo {


public static void main(String[] argv) {
// create list
List<String> listobject = new ArrayList<String>();

// add 4 different values to list


listobject.add("eBay");
listobject.add("Paypal");
listobject.add("Google");
listobject.add("Yahoo");

System.out.println("==>For Loop Example.");


for (int i = 0; i < listobject.size(); i++) {
System.out.println(listobject.get(i));
}

System.out.println("\n==> Advance For Loop Example..");


for (String temp : listobject) {
System.out.println(temp);
}

System.out.println("\n==> Iterator Example...");


Iterator<String> iter = listobject.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}

System.out.println("\n==> While Loop Example....");


int i = 0;
while (i < listobject.size()) {
System.out.println(listobject.get(i));
i++;
}
}
}
-------
==>For Loop Example.
eBay
Paypal
Google
Yahoo

==> Advance For Loop Example..


eBay
Paypal
Google
Yahoo

==> Iterator Example...


eBay
Paypal
Google
Yahoo

Selvakumar.B
==> While Loop Example....
eBay
Paypal
Google
Yahoo

 Map Interface / HashMap class


The Map interface maps unique keys to values. A key is an object that you use to retrieve a value
at a later date.

 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.

 Map contains only unique elements.

 It may have one null key and multiple null values

 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

 Commonly used methods of Map interface


 public Object put(object key,Object value):
o is used to insert an entry in this map.

 public void putAll(Map map):


o is used to insert the specifed map in this map.

 public Object remove(object key):


o is used to delete an entry for the specified key.

 public Object get(Object key):


o is used to return the value for the specified key.

Selvakumar.B
 public boolean containsKey(Object key):
o is used to search the specified key from this map.

 public boolean containsValue(Object value):


o is used to search the specified value from this map.

 public Set keySet():


o returns the Set view containing all the keys.

 public Set entrySet():


o returns the Set view containing all the keys and values.

 public Object getKey():


o is used to obtain key

 public Object getValue():


o is used to obtain value.

The HashMap class supports below constructors.

 HashMap( )
 HashMap(Map m)
 HashMap(int capacity)

Example
import java.util.*;

public class CollectionsDemo {

public static void main(String a[]){


HashMap hm=new HashMap();
hm.put("100","Selva");
hm.put("101","Bala");
hm.put("102","Priyaa");

Set keys = hm.entrySet();


Iterator itr=keys.iterator();
while(itr.hasNext()){
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+" "+m.getValue());
}

Set<String> keys1 = hm.keySet();


for(String key: keys1){
System.out.println("Value of "+key+" is: "+hm.get(key));
}

}
}

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:

Vector(int size, int incr)

The fourth form creates a vector that contains the elements of collection c:

Vector(Collection c)

 Commonly used methods of Vector


 public int capacity()
o Returns the current capacity of this vector.

 public void clear()


o Removes all of the elements from this Vector.

 public Object elementAt(int index)


o Returns the component at the specified index.

 public Enumeration elements()


o Returns an enumeration of the components of this vector.

 public Object firstElement()


o Returns the first component (the item at index 0) of this vector.

 public Object get(int index)


o Returns the element at the specified position in this Vector.

 public boolean isEmpty()


o Tests if this vector has no components.

Selvakumar.B
 public Object lastElement()
o Returns the last component of the vector.

 public Object set(int index, Object element)


o Replaces the element at the specified position in this Vector with the specified element.

 public void setElementAt(Object obj, int index)


o Sets the component at the specified index of this vector to be the specified object.

 public void setSize(int newSize)


o Sets the size of this vector.

 public int size()


o Returns the number of components in this vector.

Example-1
import java.util.Vector;

public class BasicVectorOperations {

public static void main(String a[]){


Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
System.out.println(vct);

//adding element at specified index


vct.add(2,"Random");
System.out.println(vct);

//getting elements by index


System.out.println("Element at index 3 is: "+vct.get(3));
//getting first element
System.out.println("The first element of this vector is:
"+vct.firstElement());
//getting last element
System.out.println("The last element of this vector is:
"+vct.lastElement());
//how to check vector is empty or not
System.out.println("Is this vector empty? "+vct.isEmpty());
vct.clear();
System.out.println("Is this vector empty? "+vct.isEmpty());
}
}
----
[First, Second, Third]
[First, Second, Random, Third]
Element at index 3 is: Third
The first element of this vector is: First
The last element of this vector is: Third
Is this vector empty? False
Is this vector empty? true

Selvakumar.B
Example-2
import java.util.Iterator;
import java.util.Vector;

public class VectorIterator {

public static void main(String a[]){


Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
vct.add("Random");

Iterator<String> itr = vct.iterator();


while(itr.hasNext()){
System.out.println(itr.next());
}

Enumeration<String> enm = vct.elements();


while(enm.hasMoreElements()){
System.out.println(enm.nextElement());
}
}
}
-------------------
First
Second
Third
Random
First
Second
Third
Random

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:

 Making a connection to a database


 Creating SQL or MySQL statements
 Executing that SQL or MySQL queries in the database
 Viewing & Modifying the resulting records

 Creating JDBC Application:


There are 6 steps involved in building a JDBC application which I'm going to brief in this
tutorial:

1. Import the packages:


This requires that you include the packages containing the JDBC classes needed for
database programming. Most often, using import java.sql.* will suffice as follows:

//STEP 1. Import required packages


import java.sql.*;

2. Register the JDBC driver:


This requires that you initialize a driver so you can open a communications channel with the
database. Following is the code snippet to achieve this:

//STEP 2: Register JDBC driver


Class.forName("com.mysql.jdbc.Driver");

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:

//STEP 3: Open a connection


// Database credentials
static final String USER = "username";
static final String PASS = "password";
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

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:

//STEP 4: Execute a query


stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

If there is an SQL UPDATE,INSERT or DELETE statement required, then following code


snippet would be required:

//STEP 4: Execute a query


stmt = conn.createStatement();
String sql = "DELETE FROM Employees";
ResultSet rs = stmt.executeUpdate(sql);

5. Extract data from result set:


This step is required in case you are fetching data from the database. You can use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set as follows:

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}

6. Clean up the environment:


You should explicitly close all database resources versus relying on the JVM's garbage
collection as follows:

//STEP 6: Clean-up environment


rs.close();
stmt.close();
conn.close();

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:

//STEP 1. Import required packages


import java.sql.*;

public class FirstExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
//STEP 6: Clean-up environment
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{
try{
if(stmt!=null){ stmt.close(); }
if(conn!=null) { conn.close(); }
}catch(Exception e){}
}//end finally try
}//end main
}//end FirstExample
------------------------------------------------
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan

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.

Interfaces Recommended Use

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.

 The Statement Objects:


Before you can use a Statement object to execute a SQL statement, you need to create one
using the Connection object's createStatement( ) method, as in the following example:

Statement stmt = null;


try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
try{
if(stmt!=null)
stmt.close();
}
}catch(Exception e){
}

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.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Employees set age=30 WHERE id=103";

// Let us check if it returns a true Result Set or not.


Boolean ret = stmt.execute(sql);
System.out.println("Return value is : " + ret.toString() );

// Let us update age of the record with ID = 103;


int rows = stmt.executeUpdate(sql);
System.out.println("Rows impacted : " + rows );

// Let us select all the records and display them.


sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//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

 The PreparedStatement Objects:


The PreparedStatement interface extends the Statement interface which gives you added
functionality with a couple of advantages over a generic Statement object.

This statement gives you the flexibility of supplying arguments dynamically.

PreparedStatement pstmt = null;


try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
try{
if(pstmt!=null)
pstmt.close();
}catch(Exception e){
}

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.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
PreparedStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
String sql = "UPDATE Employees set age=? WHERE id=?";
stmt = conn.prepareStatement(sql);

//Bind values into the parameters.


stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID

// Let us update age of the record with ID = 102;


int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );

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

 The CallableStatement Objects:


Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object which would be used to execute a call to a database stored procedure.

Suppose, you need to execute the following Oracle stored procedure:

CREATE OR REPLACE PROCEDURE getEmpName


(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;

Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only
uses the IN parameter. The CallableStatement object can use all three.

Here are the definitions of each:

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:

CallableStatement cstmt = null;


try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);

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.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
String sql = "{call getEmpName (?, ?)}";
stmt = conn.prepareCall(sql);

//Bind IN parameter first, then bind OUT parameter


int empID = 102;
stmt.setInt(1, empID);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);

//Use execute method to run stored procedure.


System.out.println("Executing stored procedure..." );
stmt.execute();

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

getErrorCode( ) Gets the error number associated with the exception.

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.

Prints the current exception, or throwable, and its backtrace to a


printStackTrace( )
standard error stream.

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.
}

 JDBC - Data Types:


The following table summarizes the default JDBC data type that the Java data type is
converted to when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.

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.

SQL JDBC/Java setXXX getXXX updateXXX


VARCHAR java.lang.String setString getString updateString
CHAR java.lang.String setString getString updateString
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal updateBigDecimal
INTEGER int setInt getInt updateInt
BIGINT long setLong getLong updateLong
REAL float setFloat getFloat updateFloat
FLOAT float setFloat getFloat updateFloat
DOUBLE double setDouble getDouble updateDouble
DATE java.sql.Date setDate getDate updateDate
TIME java.sql.Time setTime getTime updateTime
TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp updateTimestamp
CLOB java.sql.Clob setClob getClob updateClob
ARRAY java.sql.Array setARRAY getARRAY updateARRAY

Selvakumar.B
DAY-11

Selvakumar.B

You might also like