Sunteți pe pagina 1din 68

Introdunction To Java

1) Overview of Java 2) Operators 3) Conditional & loops constructs 4)


Arrays, Enums & String
5) Inheritance & Polymorphism 6) Handlig Errors 7) Design User Interface
8) Handling Events

NetBeans ToolBook
Project Window Ctrl + 1
Files Ctrl + 2
Favorites Ctrl + 3
Output Ctrl + 4
Services Ctrl + 5
Action Items Ctrl + 6
Navigator Ctrl + 7

Properties Ctrl + Shift + 7(can access palette & properties)

Run File Shift + F6

Just like class, interface, package & Frame we can also add Java
Exception

How To Enable assertions


Right click on project - properties - run -ea in VM options text box

Adding properties file


Rt click on Source Pakanges - New - Other - New File - Empty File - Name
it as MessageBundle.properties - Finish

Adding Jar files

Rt click on propject - properties - Libraries node - Add JAR/floder -


browse to locate an existing sqljdbc4-2.0.jar-select it - open

Run/execute SQL Server 2012 script if already exists - dbl click -


provide SQL Server loging credentias - id = sa or . password - pass@123 -
click on connect - click anywhere inside query window from Microsoft SQL
Server Management STudio Window

Or

Can use Derby database - which is inbuild inside net beans - but here we
will not full pledge functionality as that of the SQL Server Studio
. It just as a utility

Constructor
Constructors are special types of methods whose name is same as that of
the class name.
U dont have to call the constructor.
They will automatically gets invoked whenever we creat an instance.
Purpose - to initialize member variables
Constructor does not have return type, in case if we specify return type
java will trat it as method.

After creating a class we will get a default constructor automatically


which is invisible
But when write our constructor u will loose the default constructor
class Test{
psvm(...)
{
Test t = new Test();
}
}

Types
1) default
without parameter
2)parameterized

Constructor will never get inherit

super keyword is used to invoke parent class constructor or methods

public class Test


{
public static void main(String[] args)
{
//while creating an instance construtor will get automatically
invoked
Test t = new Test();
}
public Test()
{
System.out.println("Invoking default constructor");
}
}
------------------------------------------------------------------------
public class Test
{
int i,j;
public static void main(String[] args)
{
Test t = new Test();
t.disp();
}
public Test()
{
i=j=10;
System.out.println("Invoking default constructor");
}
public void disp()
{
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}
---------------------------------------------------------------------
this - refers to current class
super - refers to parent class

e.g of constructor overloading


public class Test
{
int i,j;
public static void main(String[] args)
{
//invoking default constructor
Test t = new Test();
t.disp();
System.out.println("--------------------");
//invoking parameterized constructor
Test t1 = new Test(55,88);
t1.disp();
}
//default constructor
public Test()
{
i=j=10;
System.out.println("Invoking default constructor");
}
//parameterized constructor
public Test(int i, int j) //i,j are local varaible
{
this.i = i; //this.i & his.j refers to instance variable
this.j = j;
//j=j; //value will get assign to local j only
}
public void disp()
{
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}
-----------------------------------------------------------------------
public class Test
{
public static void main(String[] args)
{
Parent p = new Parent();
System.out.println("--------------------");
Child c = new Child();
}
}
class Parent
{
public Parent()
{
System.out.println("Default constructor of parent class");
}
}
class Child extends Parent
{
public Child()
{
//by default every constructor is having super() statement at
very first line
//which is invisble, which invokes parent class default
constructor first
//constructor will never get inherit
//super();
System.out.println("default constructor of child class");
}
}
-------------------------------------------------------------------------
------------
public class Test
{
public static void main(String[] args)
{
Parent p = new Parent("Samradnyi");
System.out.println("--------------------");
Child c = new Child();
}
}
class Parent
{
public Parent(String name)
{
System.out.println("Default constructor of parent class");
System.out.println("Welcome: "+name);
}
}
class Child extends Parent
{
public Child()
{
//super();
//as we dont have defualt constructor we will get compile time
error
//so we needs to forcefully call the parameterised constructor
//as per the reuirement of prg
super("sama");
System.out.println("default constructor of child class");
}
}
-------------------------------------------------------------------------
---+++++++++++++++
constructor

1) Are special types of function whose name is as that of class name

2) Whenever we create a class we will get a default constructor, Once u


write your own constructor you will loose default constructor

class Student{}

Student obj = new Student();

3) main purpose of constructor is to initialize memeber variables

4) u dont have to call the constructor, they will automatically gets


invoked whenever we create an instance of a class

Student obj; object


Student o=new Student(); instance
Parent p = new Child(); p is a refernce variable of Parent but
during runtime it points Child class

new Student(); anynoumous object- when u want to use object


only one time

Child c = new Parent(); Not possible


Cat c = new Animal(); Not possible- as Every cat is a animal but
every animal is not a cat(it can be dog, cow....)

5) Constuctor never gets inherit


But whenever we create an insatnce of child class, parent class
constructor gets invoked first, because of super keyword
super - refers to parent class
this -refers to current class

If we use super related to constrotor then it must be on very first line

And if its related to method or varaible then it can be anywhere inside


method

6) U can have n number of constructor - Constructor overloading

7)Types of constructor
a) Default - without parameter
b) parameterised - with parameter

8) constructor does not have return type. If we specify return type java
will treat it as ordinary fuction.(.net - error)

===============================

eg1
Constructor overloading

public class MyApp


{
public static void main(String[] args)
{
Test obj1= new Test();
Test obj = new Test("Sama");

}
class Test
{
public Test(String str)
{
System.out.println("--------------------------------------");
System.out.println("Calling parameterised constructor");
System.out.println("Welcome " + str);
}
public Test()
{
System.out.println("-----------------------------------------");
System.out.println("Calling Default constructor");
}

================================================

e.g.2

public class Test


{
public static void main(String[] args)
{
//Animal a =new Animal();
System.out.println("---------------------------");
Cat c = new Cat();
System.out.println("----------------------------");
}

class Animal
{
public Animal()
{
System.out.println("Default Constructor of Animal Class");
}
}

class Cat extends Animal


{
public Cat()
{
//super(); //its not visible but because of this it fitsrt call
parent class default
//constructor only
//In parent class if default constructor is
not available then we get
//compile time error in such scenario we must
forcefully call avaiable constrcutor using super()

System.out.println("Default constructor of Cat Class");


}

}
__________________________

package javaapplication14;
public class Test {
//Function Overloading
public static void main(String[] args) {
Test t=new Test();

System.out.println(t.sum(20, 30));
System.out.println(t.sum(20, 30,40));
System.out.println(t.sum(20, 30,40,50));
}
int sum(int i,int j){
return i+j;
}
float sum(float i,float j){
return i+j;
}
float sum(int i,float j){
return i+j;
}
float sum(float i,int j){
return i+j;
}
int sum(int i,int j,int k){
return i+j+k;
}
int sum(int i,int j,int k,int l){
return i+j+k+l;
}
}
----------------------------------------
package com.net;
public class Test1
{public static void main(String[] args) {
Test1.sum();
System.out.println("-------------------------------");
Test1.sum(1,2,3,4,5);
System.out.println("-------------------------------");
Test1.sum(10,20,30,40,50,60,70,80,90,100);
System.out.println("-------------------------------");}
//can pass 0 to n arguments
public static void sum(int... nums)
{
int ans=0;
for(int n : nums)
{
ans+=n;
}
System.out.println("Sum of Argumenst is:\t"+ans);
}
}
/*
varargs/variable arguments
public void sum(int x, int... nums); ok must have to pass at least 1 int
public void sum(int... nums,float f); not allowed- variable arguments
must at the end
public void sum(int... nums,float... f);
not allowed - again confusion how many are int & how many are float
*/
-------------------------------------------------------------------------
--------------------
package com.net;
public class Test2
{
int empId;
String empName;

public Test2(int empId, String empName)


{
this.empId = empId;
this.empName = empName;
}
public static void main(String[] args)
{
Test2 obj = new Test2(1111, "Sama");
System.out.println(obj);
System.out.println("--------------------------");
//automatically invokes toString if overridden method is
available
System.out.println("Hello "+obj);
//noo need to call it
//System.out.println(obj.toString());
System.out.println("--------------------------");
System.out.println(obj.getClass());
System.out.println("--------------------------");
System.out.println(obj.getClass().getName());

}
@Override
public String toString()
{
return "Employee Id:\t"+empId+"\nEmployee Name:\t"+empName;
}

}
======================================================

prior to java7
in switch we can pass only int (4 bytes)
we can short,char,byte but during execution these data types implicitly
gets convert to int
2 2 1

In java 7 we can pass String data type also

//Array is a grp of element having same data type they share a common
name
//but diff index value & they gets stored continuously in the memory

//index always starts with 0


//and ends with length -1
/*Types
Single dimensional
Elements are either arranged in the rows or columns
Multidimensional
2D,3D,4D....32D
Array is of reference type*/

public class MyArray


{
public static void main(String[] args)
{
int arr[] = new int[3];
int cnt=0;
arr[0]=10;
arr[1]=20;
arr[2]=30;
//tratitional for loop

for (int i = 0; i < arr.length; i++)


{
System.out.println("arr["+i+"] = " + arr[i]);
}
System.out.println("Arry using enhanced for loop");
//enhanced for loop
for(int x : arr)
{
System.out.println("arr["+cnt+"] = " + x);
cnt++;
}
}
}
---------------------------------------
public class MyArray
{
public static void main(String[] args)
{
String str ="Samradnyi";
char[] arr = str.toCharArray();
for(char ch : arr)
{
System.out.print(ch+" ");
}
}
}
---------------------------------------------
palindrome
madam,nayan,dad,malayalam,mom,malam

public class MyArray


{
public static void main(String[] args)
{
int start=0,end,flag=1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter String To Check:\t");
String str =sc.next();
end=str.length()-1;
for(;start<=end;start++,end--)
{
if(str.charAt(start)!=str.charAt(end))
{
flag = 0;
break;
}
}
if(flag==1)
{
System.out.println(str + " is palindrome");
}
else
{
System.out.println(str + " is not palindrome");
}
}
}
Command line Arguments
import java.util.Scanner;

public class Array {

public static void main(String[] args) {


int i=0;
for (int j = 0; j <args.length-1; j++) {

System.out.println("args["+j+"] = "+args[j]);
}
}
}
1. Execute Through the net Beans
2. Execute through cmd
Compile as usualy java “Array 123 Avinash 12.3 x”
Projects->Properties->Run->Arguments
-------------------------------------------------------------------------
---
Enum
Is a set of named integer consatnt
String name;
name = can assign any value
But if you want to enter only fixed set of values we can declare those
values inside enum. So it won’t allow u to enter any value other than
enum values
Days - Sun,Mon,Tues,Wen.....Sat
0 1 2 3 8
In short can list predefined values inside enum
It is special type of class which have constructor, methods & instance
variables
enum City
{
Mumbai,
Delhi,
Chennai,
Pune
}
Enum can either declare inside class or outside the class
We can’t create enum instance with the new keyword, it will automatically
gets created whenever we will create constant of enum
Demo1
enum City
{
Mumbai,
Delhi,
Chennai,
Pune
};
class TestEnum
{
public static void main(String[] args)
{
for(City myCity : City.values())
{
System.out.println(myCity);
}
}
}
----------------------------------------------
enum City
{
Mumbai(100),
Delhi(50),
Chennai(400),
Pune(888);

int i;
City(int x)
{
i=x;
}
int getNumber()
{
return i;
}
};
public class TestEnum
{
public static void main(String[] args)
{
City cts = City.Pune;
System.out.println(cts.getNumber());
City cts1 = City.Delhi;
System.out.println(cts1.getNumber());
}
}

is a refernce type variable


String -
Immutable - once assigned can’t change the value
StringBuffer
Mutable, It is thread
StringBuilder
Mutable, is not thread safe

public class TestEnum


{
public static void main(String[] args)
{
String str=new String("Samradnyi");
System.out.println("str contents:\t" + str);
System.out.println("Hash Code of str:\t"+str.hashCode());
str+=" Swamini";
System.out.println("str contents:\t" + str);
System.out.println("Hash Code of str:\t"+str.hashCode());
}
}

String s1="Sama";
This gets stored inside String constant pool (JVM has special type of
memory to store String literals)
String s2="Sama";
Now s1 & s2 will point to the same memory, no separate memory will get
allocate

String s3 = new String("Samradnyi");


This gets stored inside heap,
String s4 = new String("Samradnyi");
even though contents of s3 & s4 are same separate memory will get
allocate

==
will check whether 2 objects are pointing to the same memory
location are not
Normally is used with numbers as a comparision operator
.equals
will check whether the contents of 2 objects are same or not

class TestEnum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Id:\t");
String id=sc.next();
System.out.print("Enter Password:\t");
String pwd=sc.next();
if(id.equals("sama")&&pwd.equals("sama@123"))
{
System.out.println("Welcome "+id);
}
else
{
System.out.println("Invalid User Plz Try Again");
}
}
}
-------------------------------------
class TestEnum
{
public static void main(String[] args)
{
String s1=new String("sama");
String s2=new String("sama");
String s3=s1;
String s4=new String("SAMA");
if(s1.equals(s2))
{
System.out.println("Contents for s1 & s2 are same");
}
if(s1!=s2)
{
System.out.println("String s1 and s2 are not pointing to the
same memory location");
}

if(s1.equalsIgnoreCase(s4))
{
System.out.println("s1 & s4 are same regardless of case
sensitivity");
}
}
}
--------------------------------------------------------
class TestEnum
{
public static void main(String[] args)
{
String s1=new String("Computer");
System.out.println(s1);
System.out.println(s1.toUpperCase());
System.out.println(s1.toLowerCase());
System.out.println(s1.indexOf('C'));
System.out.println(s1.indexOf("put"));
System.out.println("extract from 3rd position
:\t"+s1.substring(3));
System.out.println("3rd to 6th position:\t"+s1.substring(3,6));
}
}
-------------------------------------------------------------------------
-----
StringBuffer
class myStringBuffer
{
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Count Down Starts");
System.out.println(str + " is stored at "+str.hashCode());
for (int i = 10; i >0; i--)
{
str.append("\n"+i);
}
System.out.println(str);
System.out.println(" is stored at "+str.hashCode());
}
}

------------------------------------------------------------------------
public class pyramid
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j,k,sp=40;
System.out.print("Enter Lines To Print:\t");
int n = sc.nextInt();
for (i = 1; i <= n; i++)
{
for (j = 1; j <= sp; j++)
{
System.out.print(" ");
}
for (k = 1; k <=i; k++)
{
//System.out.print("* ");
//System.out.print(i + " ");
System.out.print(k + " ");
}
sp--;
System.out.println();
}
}
}

-------------------------------------------------------------------------
-----------------------------
Chap 5
Implementing Inheritance and polymorphism
+-Inheritance - creating new classes on the basis of existing one
It save time,efforts & space
Types
Single, Multilevel, Hierarchical,multiple.
Java does not support Multiple Inheritance
A B
xyz() xyz()

C extends A,B
xyz() - A
xyz() - B

cObj.xyz(); ?????? ambiguity

single
Animal - Cat
Multilevel
Gradfather-Father-Son-grand son-great grand son
Hierachial
Employee
MD Manager Engineer Officer
Jr Manager

//parent class
public class Employee
{
int empId;
String empName;
float salary;
public Employee() {
}

public Employee(int empId, String empName, float salary) {


this.empId = empId;
this.empName = empName;
this.salary = salary;
}
public void displayEmp()
{
System.out.println("Emp Id :\t"+empId);
System.out.println("Emp Name :\t"+empName);
System.out.println("Emp Salary :\t"+salary);
}
public static void main(String[] args)
{
Employee emp = new Employee(111, "Sama", 40000);
emp.displayEmp();
System.out.println("--------------------");
Manager m = new Manager("HR", 222, "Samu", 60000);
m.displayEmp();
}
}
//creating child class of Employee
class Manager extends Employee
{
//Apart from inherited variables child class has its own varaible
String dept;

public Manager(String dept, int empId, String empName, float salary)


{
//invoking parent class constructor using super keyword
super(empId, empName, salary);
this.dept = dept;
}
@Override
public void displayEmp()
{
//calling parent class method
super.displayEmp();
//print only variables child class
System.out.println("Emp Department:\t"+dept);
}
}
--------------------------------------------------------
Abstract class
Up till now we discussed concrete class- means a class where all methods
are defined
Abstract class - At lest one method should be abstract. (method without
definition or implemetation)
interface - all methods are abstract

Exactly where we have to implement abstract class concept

First u should know what is overriding - redefining parent class function


in child class as per the requirement of child class
But there are certain situations where child class does not require
definition
e.g
calculating area / volume for diff-diff shapes, as formula is diff for
all child do not require definition from parent class

//must have to specify abstract keyword


abstract class Shape
{
//abstract method
//we must have to define in child class otherwise child class
//will also become abstrcact class
//abstract keyword is compulsary while defining abstract method
public abstract void calArea();
//non abstract method
public void dispShape()
{
System.out.print("Drawing : ");
}
}
class Circle extends Shape
{
@Override
public void calArea()
{
System.out.println("Calculating Area for Circle");
System.out.println("pi*r*r");
}
@Override
public void dispShape()
{
super.dispShape();
System.out.println("Circle");
}
}
class Rectangle extends Shape
{
@Override
public void calArea()
{
System.out.println("Calculating Area for Rectangle");
System.out.println("length*breadth");
}
@Override
public void dispShape()
{
super.dispShape();
System.out.println("Rectangle");
}
}
class Test
{
public static void main(String[] args)
{
Circle c = new Circle();
c.dispShape();
c.calArea();
System.out.println("-------------------------------");
Rectangle r = new Rectangle();
r.dispShape();
r.calArea();
}
}

-------------------------------
If the classess are related to each other then go for abstract class
and if classes are not related to each other then go for interface
(cond- they should have common functionality)
Shape - Abstract class
Height,width, radious,pi etc &
calArea(),calVolume(),calPerimeter() - common for all shapes

Circle Triangle Rectangle Square


Rhombus

Interface ElectronicDevice
remote() – is common

class TV class AC class Projector class


CDPlayer
remote() remote() remote() remote()

e.g of interface
diff bet abstract class and interface
pg 110

1) Static polymorphism
Function overloading- One function behaves differently in diff
situations
signatures
1) Number of arguments must be diff
int sum(int i,int j)
int sum(int i,int j,int k)
2) If number of arguments are same then their data type must be
diff
long sum(long i,long j)
flaot sum(float i,float j)
3) If number of arguments and their data types are same then their
sequence must be diff
float sum(int i,float j)
float sum(float i,int j)
2) Dynamic Polymrophism
Function Overriding - redefining parent class function in child
class
Means changing the function behaviour(definition) of parent class
in child class as per your requirement
So while redefining you should take care of following 6 points
Access_Specifier Access_Modifier Return_Type Function_Name(Arguments)
Throws Exception
1 2 3
4 5 6
public static void
main (String[] str) throws Exception

1) Should not be less restrictive, can be more restrictive


Means in parent class if function is public we cant specify
protected or private (cant assign weaker access privilege)
2) Cant override static & final functions
3) Return type must be same
4) Function name must be same
5) Number of arguments and their data types & sequence must be same
6) Exception can be None, Same Exception as that of the parent class, or
Child classes of Exception class which is used in parent class

Function overloading demo

public class Chapter5 {


public static void main(String[] args)
{
Chapter5 obj = new Chapter5();
int ans = obj.sum(10, 20);
System.out.println("10 + 20 = "+ans);

System.out.println(obj.sum(12.1f, 10.2f));

System.out.println(obj.sum(11, 22, 33));

System.out.println(obj.sum(12L, 12L));
}
int sum(int i,int j)
{
System.out.println("Sum with 2 intgeres");
return i+j;
}
int sum(int i,int j,int k)
{
System.out.println("Sum with 3 intgeres");
return i+j+k;
}
long sum(long i,long j)
{
System.out.println("Sum with 2 long");
return i+j;
}
float sum(float i,float j)
{
System.out.println("Sum with 2 floats");
return i+j;
}
float sum(int i,float j)
{
System.out.println("Sum with intgere & float");
return i+j;
}
float sum(float i,int j)
{
System.out.println("Sum with float & intgere");
return i+j;
}
}

function overriding demo

public class TestOverriding


{
public static void main(String[] args)
{
Child c = new Child();
c.show();
System.out.println("--------------------------");
Parent p =new Parent();
p.show();

}
}
class Parent
{
public void show()
{
System.out.println("Your are inside parent class's show function");
}
}
class Child extends Parent
{
@Override
public void show()
{
System.out.println("Overriding Parent class function in child
class");
super.show();
}
}

-------------------------------------------------------------------------
--

Chapter 6
Exception Handling
Errors
1) Compile time error (Syntax error)
prg will not get compile
e.g " problem, missing ;, wrong syntax, use of keyword as a varible
name int for;
2) Runtime error (Exception)
prg will get compile
But will not get execute
e.g divide by 0, overflow, prg runs out of the memory
2) Logical Error
prg will get compile
prg will get exceute
But the output is wrong/unexpected/ means in short our logic is
wrong
Due to runtime error your program will get terminated abruptly and just
to avoid abrupt termination of your program u needs to handle it and this
is called as exception handling
Compilation(translate to machine language which is platform independant)
– whole source code gets considered, if error is on last line then also
code will not get compile
Interpretation- code gets interprete(translate to native machine
language-which is platform dependant) line by line so if error is on last
line prg will get execute upto second last line & after that prg will get
terminate.

public class Chapter6 {


public static void main(String[] args)
{
int i,j,ans=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number1:\t");
i = sc.nextInt();

System.out.println("Enter Number2:\t");
j = sc.nextInt();
try
{
ans=i/j;
}
catch(Exception ex)
{
System.out.println("Exception Occurs:\t"+ex.toString());
}

System.out.println(i + " / " + j + " = " + ans );


System.out.println("End of the program");
}
}
import java.util.InputMismatchException;
import java.util.Scanner;

public class Divsion {


public static void main(String[] args) {
int result,i,j;
result=i=j=0;
try
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter the number1");
i=sc.nextInt();
System.out.println("Enter the number2");
j=sc.nextInt();
result=i/j;
}
catch(InputMismatchException ex)
{
System.out.println("Exception Occured:\t"+ex.toString());
}
catch(ArithmeticException ex)
{
System.out.println("Exception Occured:\t"+ex.toString());
}
catch(Exception ex)
{
System.out.println("Exception Occured:\t"+ex.toString());
}
System.out.println(i+" / "+j+" = " +result);
System.out.println("End of the main");

Exception

Checked Unchecked
compile time run time
u must have to declare or handle Handling is not compulsory, if
everything is proper
otherwise your prg will not get compile your prg will get compile as
well as execute

Declare means Handle means


throws throw try catch
other than all the classes under RunTimeException
& Error will RunTime & Error come under unchecked

Demo2
NullPointerException

public class Test1


{
public static void main(String[] args)
{
Student s=null;
//s = new Student();
s.show();
}
}
class Student
{
public void show()
{
System.out.println("Exceuting show function");
}
}

Demo3
CheckedException Demo

public class Test1


{
public static void main(String[] args) throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int i,s;
System.out.println("Enter Number1");
i =Integer.parseInt(br.readLine());
s=i*i;
System.out.println(i + " Squre is " + s);
}
}

Deo4
NumberFormatException

public class Test1


{
public static void main(String[] args) throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
int i=0,s=0;
System.out.println("Enter Number1");
//for Integer.parseInt() we must have to pass number as a string
//otherwise we will get NumberFormatException - this comes under
RunTimeError
try
{
i =Integer.parseInt(br.readLine());
}
catch(NumberFormatException ex)
{
System.out.println("Exception Occurs:\t"+ex.toString());
}
s=i*i;
System.out.println(i + " Squre is " + s);
}
}

We can have multiple catch blocks. First u needs to handle specific


purpose exception and then general purpose exception (otherwise u will
get a compile time error)

Exception - general
ArrayIndexOutOfBounds specific purpose

try
{
code to monitor
}
catch(Exception ex)
{
code to handle
}
....... multiple catch blocks
finally
{
irrespective of exception whether it is raised or not, this block
will get execute
can complete the pending task
Resources closing
at the end of try catch block finally block will get execute
}

public class FinallyDemo


{
public static void main(String[] args)
{
int arr[] = new int[]{1,2,3,4};
int len = arr.length;
try
{
//in both the cases finally block will get exceute
//for (int i = 0; i <=len; i++) //exception
for (int i = 0; i <len; i++) //no exception
{
System.out.println("arr["+i+"] = " + arr[i]);
}
}
catch(Exception ex)
{
System.out.println("Exception Occured:\t"+ex);
}
finally
{
System.out.println("Inside Finally block");
}
}
}

throw - transfers the control to nearest catch block that handles the
type of exception being thrown. If no appropriate catch block exists the
prg terminates

public class Chapter7


{
public void display()
{
throw new RuntimeException();
}
public static void main(String[] args)
{
Chapter7 obj = new Chapter7();
try
{
obj.display();
}
catch(Exception ex)
{
System.out.println("Exception Thrown:\t"+ex);
}
}
}

throw keyword can also be used inside a catch block to rethrow an


exception

public class RethrowDemo


{

public static void compute()


{
try
{
throw new RuntimeException();
}
catch(RuntimeException e)
{
System.out.println("Exception Occured in compute()" + e);
throw e;
}
}
public static void main(String[] args)
{
try
{
RethrowDemo.compute();
}
catch(RuntimeException e)
{
System.out.println("Exception Occured in main:\t" + e);
}
}
}

throws keyword is used by a method to specify the types of exceptions


that the method can throw

public class ThrowsDemo


{
//called function
//throws to the calling function
public void compute() throws RuntimeException
{
throw new RuntimeException();
}
//calling function
public static void main(String[] args)
{
ThrowsDemo t = new ThrowsDemo();
try
{
t.compute();
}
catch(RuntimeException e)
{
System.out.println("Exception Occured in main:\t" + e);
}
}
}

try with resources introduced in java 7


try can have parameters just like a method
try(resource1 ; resource2, resource3....)

closing of resources is in reverse order


resouce3 resource2 resource1

public class Test


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

int i=0,s=0;
System.out.print("Enter Number1:\t");
//we dont have to write finally block
//resource will automatically gets closed in reverse order
try(InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);)
{
i =Integer.parseInt(br.readLine());
}
catch(NumberFormatException ex)
{
System.out.println("Exception Occurs:\t"+ex.toString());
}
/*finally
{
ir.close();
br.close();
}*/
s=i*i;
System.out.println(i + " Squre is " + s);
}
}

user defined exception


class AgeCheckException extends Exception
{
public AgeCheckException()
{
System.out.println("Invalid Age");
}
}

public class Test


{

public void ageCheck(int age) throws AgeCheckException


{
if(age<18 || age>120)
{
throw new AgeCheckException();
}
else
{
System.out.println("Welcome You Are eligible for Voting");
}
}
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
int age=0;
Test t = new Test();
System.out.print("Enter Your Age:\t");
try
{
age = sc.nextInt();
t.ageCheck(age);
}
catch(AgeCheckException ex)
{
System.out.println("Exception Occured " + ex);
}
}
}

assertions
assert keyword is introduced in java 4
before that we can use assert as an identifier
int assert=10;
assertion can enabled during development & later can disabled during
execution
Just to check your assumption we have to assertion

To enable
-ea
To Disable
-da

1)try..catch (handling an exception)


UNCHECKED
RuntimeException, Error

2)throws (declaring an exception)


Checked
Without declaring or handling exception your prg will not get
compile
Exception

Errors
1) Syntax Error - prg will not get Compile
2) Run Time Error - prg will get compile but unable to
exceute/fails to execute
Exception - When something unexpected happens, your prg will
get terminate abruptly
(IF EVERYTHING IS PROPER YUR prg will get exceute also)
so to maintain normal flow of prg & to create reliable
application u needs to handle the exception this is
called as exception handling
3) Logical Error - prg will get compile, execute but output is
wrong/ unexpected

Compilation - whole scr code is compiled


Interpretation- is line by line

javac java
.java------------------------.class---------------------------native
machine language
bytecode

ways
1)
Hadling an Exception (unchecked exception)

try - catch -finally block


At a time only one Exception is occured and at a time only one catch
block is executed.All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must come before catch
for Exception (otherwise will get a compile time error
For each try block there can be zero or more catch blocks, but only one
finally block.
The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to
abort).

2)
Declaring Exception (checked exception)
throws -
throw
The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw


keyword
throw custom exception

No. throw throws


1) Java throw keyword is used to explicitly throw an exception. Java
throws keyword is used to declare an exception.
2) Checked exception cannot be propagated using throw only. Checked
exception can be propagated with 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 exceptions. You can declare multiple
exceptions e.g.

public void method()throws IOException,SQLException.

If the superclass method does not declare an exception


If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can declare
unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass
overridden method can declare same, subclass exception or no exception
but cannot declare parent exception.

Types
1)Checked(compile) - must have to declare(throws) /
handle(try..catch..finally), otherwise your prg will not get compile,
Other than RuntimeException i.e. IOException, SQLException
classes which extends Throwable exception except erros
2)Unchecked(Runtime) - Its not compulsory to handle, if everything is
proper ypur prg will get execute also
but if some there is some sort of error then your prg will get
abruptyly terminate , so to maintain normal flow of prg we
have to hadle it.
All RuntimeException & Error
classes which extends RuntimeException
ArithmeticException /0,NullPointerException
String s=null;
System.out.println(s.length());//NullPointerException
NumberFormatException
String s="abc";
int i=Integer.parseInt(s);
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.

package myException;
public class Test
{
public static void main(String[] args)
{
int i,j,ans=0;
i=10;
j=0;
System.out.println("Trying to divide");
try
{
ans=i/j;
}
catch(Exception Ex)
{
System.out.println("Exception Occurs : \t"+Ex.getMessage());
}
finally
{
System.out.println(i + " / "+ j + " = " +ans);
}
System.out.println("End of the Program");
}
}

// Scanner
//Command Line
//System Property
//BufferedReader - just to increase efficiency of IO operation

package myException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test1


{
public static void main(String[] args) throws IOException
{
int i,j=0,ans;

//InputStreamReader ir=new InputStreamReader(System.in);


//BufferedReader br = new BufferedReader(ir);

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter Number1:\t");
i=Integer.parseInt(br.readLine()); //can handle
NumberFormatException

System.out.print("Enter Number2:\t");
try
{
j=Integer.parseInt(br.readLine());
}
catch(NumberFormatException Ex)
{
System.out.println("Please Enter Numeric value" +
Ex.getMessage());
}

ans=i+j;

System.out.println(i + " + " + j + " = "+ans);


}
}
----------------------------------------------------------
user Defined Exception

Java 7 new Features


try with resourses

try
{}
catch(Exception ex)
{}
finally
{}

java.lang.AutoClosable
class Test implements Autoclosable

java.io.Closable
class Test implements Closable
try(res1;res2;res3)
{
error
}
catch(Exception ex)
{}
finally
{}

Catchcing multiple Exception


try
{}
catch(ArithemeticException ex)
{}
catch(ArrayIndexOutOfBoundsException ex)
{}
catch(Exception ex)
{}
finally
{}

try
{}
catch(ArithemeticException |ArrayIndexOutOfBoundsException | Exception
ex)
{
sout("Error Occurs:\t"+ex.getMessage();
}

Rethrow
again throw to calling method
throw e

--------------------------------------------
Custom Exception

package myException;
public class Test
{
public static void main(String[] args)
{
int age=120;
try
{
Test.validate(age);
}
catch(CheckAge ex)
{
System.out.println("Invalid Age :\t" + ex.getMessage());
}
}
public static void validate(int age) throws CheckAge
{
if((age>0)&&(age<=100))
{
System.out.println("Your Age IS Valid");
}
else
{
throw new CheckAge("Wrong Age, It Must Be Between 0-
100");
}
}
}

class CheckAge extends Exception


{
public CheckAge(String str)
{
super(str);
}
}

---------------------------------------------------
Throwable

-----------------------------------------------------
Assertion - used just to chk your assumptions

assert keyword is used in java 4


before java 4 we can use assert as an identifier.

We can diable assertion during runtime


By default they are disabled
(during development phase chk assumption & execution make it disable)
class Test
{
public static void main(String[] str)
{
int assert=10;
System.out.println("assert = " + assert);
}
}

javac Test.java

2 erros

javac -source 1.3 Test.java

now 3 warnings

Can exceute & will get output

import java.util.Scanner;

class Test
{
public static void main(String[] str)
{
Scanner scanner = new Scanner( System.in );
System.out.print("Enter ur age ");
int value = scanner.nextInt();
try
{
assert value>=18:"Your Age Is Not valid";
}
catch(AssertionError ae)
{
System.out.println(ae.getMessage());
}
System.out.println("value is "+value);
}
}

javac Test.java

java -ea Tests

==================================================
Chapter 7
Designing User Interface
CUI - character is a medium of interaction
GUI - graphics is a medium of interaction, user friendly - with minimum
efforts anyone can easily learn

setMnemonics(int mnemonics) is used to assign shortcut key to the menu


item.

Create an instances of

JMenuBar
menuBar = new JMenuBar();
JMenu
fileMenu = new JMenu("File");
JMenuItem
itemNew = new JMenuItem("New");
Add menuitem in menu
fileMenu.add(itemNew);
Add menu inside menu bar
menuBar.add(fileMenu);
Set menu bar to a frame
setJMenuBar(menuBar);

Swing

public void sub()


{
Font myFont = new Font("Algerian", Font.BOLD, 30);
String id,pwd;
id = txtId.getText();
char arr[] = txtPwd.getPassword();
pwd = new String(arr);
if(id.equals("a")&&pwd.equals("b"))
{
lblMsg.setText("Welcome " + id);
lblMsg.setForeground(Color.BLUE);

lblMsg.setFont(myFont);
}
else
{
lblMsg.setText("Inavlid User Plz Try Again");
lblMsg.setForeground(Color.red);
}
}
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt)
{
sub();
}

private void btnSubmitKeyPressed(java.awt.event.KeyEvent evt)


{
if(evt.getKeyCode()==KeyEvent.VK_ENTER)
sub();
}

private void btnResetActionPerformed(java.awt.event.ActionEvent evt)


{
txtId.setText("");
txtPwd.setText("");
txtId.requestFocus();
}
==========================================
private void jButton1ActionPerformed(java.awt.event.ActionEvent
evt) {
int n1,n2,ans;
n1 =Integer.parseInt(txtN1.getText());
n2 =Integer.parseInt(txtN2.getText());
txtAns.setText((n1+n2)+"");
txtAns.setEnabled(false);
txtAns.setEditable(false);
}
--------------------------------------------------
JOptions

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)


{
int ch = JOptionPane.showConfirmDialog(this, "Are You Sure",
"Exit",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
//if(ch==0)
if(ch==JOptionPane.YES_OPTION)
{
System.exit(0); // stop program
this.dispose();
this.setVisible(false);
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

====================================================
//String Fruits[]={"Mango","Pear","Orange","Apple","Grapes"};
//JComboBox cb=new JComboBox(Fruits);

JFrame - Lalebl,JCombi,Label & Button


Rt click of JCombo-Properties-Model-Add diff fruits
Wrie Button Click event as follows
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String data = "Favourit Fruit Is : "+
cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}

==============================================================

Programming In Java
Chapter 1
Inner classes & Type Casting
A Class defined inside another class is called as inner class.

Helper class - provides a very specific functionality to another class.


(This class should not be accessible to other class)
This can be achieved by declaring helper class inside the class which
uses functionality.
Inner classes increases the encapsulation, in addition it makes the code
readable & maintainable.
class CreditCard
{
private cardno,exipydate, cvv no
}
In order to access private the we have to create anothe class
CreditCardValidator but it mut be an inner class
Types
1) Regular inner class
2) Static inner class
3) Method inner class
4) Anonymous inner class
1) Regular inner class - is a class whose definition appears inside the
definition of another class
//outer class
class Login
{
private String id;
private String password;

public Login(String id, String password) {


this.id = id;
this.password = password;
}
//inner class
//inner class can access private data of outer class
class ValidateLogin
{
public void validate()
{
if(id.equalsIgnoreCase("a")&&(password.equals("b")))
{
System.out.println("Welcome : " + id);
}
else
{
System.out.println("Invalid User Please Try again");
}
}
}
}

public class Test


{
public static void main(String[] args)
{
//Login obj = new Login("A","sama");
Login obj = new Login("A","b");
Login.ValidateLogin vLogin = obj.new ValidateLogin();
vLogin.validate();
}
}

2) Static inner class


3) Method inner class
4) Anonymous inner class
S190007100071

Chapter 2
Regular Expression & Localization
Regular Expression
Pattren p = Pattenr.compile("patter which u wants to match");
Matcher m = p.matcher(string in which u wants to match);
if(m.find())
{
}
a[swert]r
-------------------------------------------------------------
Character classes
.[]
. one character, it can be letter, digit or special character except end
of the line
[ase] either a or s or e
[^ase] apart from a or s or e
a-f any charater bet a to f
| or
-------------------------------------------------------------------------
-------
Predefined chracter class
\d - digit
\w - word (letter, digit, _)
\s - white space character \n,\t,\r,\f,\0xB-vertical tab
\ has a special meaning so to cancel the meaning use \\
Patter p = Pattern.compile("\\d\\d\\d");
output Welcome To "NIIT"
System.out.println("Welcome To \"NIIT\". ");
System.out.println("Welcome To 'NIIT'. ");
-------------------------------------------------------------------------
-------

Quantifiers
* (0 to n) .+
+ (1 to n)
? (1 time) .?
{n} n number of times \d{6}
(ab){n} ab should reapeat n number of times
{m,n}
{m,s}
-------------------------------------------------------------------------
--------
Greedyness
Tries to grab maximum character
? turn off greedyness
-------------------------------------------------------------------------
-----------
Boundry Matchers
^ - begning of the line
$ - end of the line
\b - begning or end of the word
\B - Not begning or end of the word
-------------------------------------------------------------------------
--------
Matching the groups
() is used to indentify parts of string to match
-------------------------------------------------------------------------
---
replaceAll()
matcher.replaceAll("specify char/string by which we wants to replace");
-------------------------------------------------------------------------
---------------

123-ABC
\\d\\d\\d

1-abc
12-dgs

agohfgdh ago hjfh agow hdfjd


ago.*

Chapter 3
Working With Generics

class TestGeneric
{
int i;
public void setValue(int i)
{
this.i=i;
}
public int getValue()
{
return i;
}
}
public class Test
{
public static void main(String[] args)
{
TestGeneric obj = new TestGeneric();
obj.setValue(20);
System.out.println(obj.getValue());
//compile time error - Incompatible float with int
//obj.setValue(20.56F);
}
}

Solution can implement Generic class

class TestGeneric<T>
{
T i;
public void setValue(T i)
{
this.i=i;
}
public T getValue()
{
return i;
}
}
public class Test
{
public static void main(String[] args)
{
TestGeneric<Integer> obj1 = new TestGeneric<Integer>();
obj1.setValue(20);
System.out.println(obj1.getValue());
//can have empty <> agular bracket - compile will automatically assum
the type
//just to reduce the typing can use diamondoperator <>
TestGeneric<String> obj2 = new TestGeneric<>();
obj2.setValue("sama");
System.out.println(obj2.getValue());

TestGeneric<Float> obj3 = new TestGeneric<>();


obj3.setValue(20.66f);
System.out.println(obj3.getValue());
}
}

Generic method
Can have generic method inside non generic class

class Test1Gen
{
public <M> M show(M m)
{
return m;
}
}
public class Test1
{
public static void main(String[] args)
{
Test1Gen obj = new Test1Gen();
System.out.println(obj.show("sama"));
System.out.println(obj.show(100));
System.out.println(obj.show(12.88f));
System.out.println(obj.show(true));
}
}

Chapter 4
Collection - is a framework
Collection of objects
class Student{}
Student obj1...100
Framework -
collection
List Set
duplicate objects are allowed Unique objects
Its an ordered collection unordered collection
Can add elements one by one or
at specific position

ArrayList,LinkedList,Vector HashSet, TreeSet

Hash Set - Insertion is faster as it does not sort the element.


Tree Set - sorted set, Searching is faster, but insertion or addition of
elements is slow as it sorts before addiotion

Array List - Resizable array/ dynamic array - memory will be allocated as


and when required.
Array - is of fixed size

Efficient for searching as well as inserting objects at the end of the


list

LinkedList -

Vector - Same as that of an arraylist & LinkedList but all methods are
thread safe(synchronised)
Concrete class – all methods are defined
Abstract class – at least one method shoud be abstract(means method
withoud definition)
Interface – all methods are abstract

package mygenerics;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Test


{

public static void main(String[] args) {


List<String> s = new ArrayList<>();
//List s = new ArrayList();
s.add("sama");
s.add("c++");
s.add("Java");
//s.add(new Integer(12));
s.add("vaishali");
s.add("Java");

Iterator itr = s.iterator();


while(itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("Before Sorting");
System.out.println(s);
Collections.sort(s);
System.out.println("After Sorting");
System.out.printlns(s);
}

}
----------------------------------------------------------------------
package mygenerics;

import java.util.ArrayList;
import java.util.Iterator;

public class MyGenerics {


public static void main(String[] args)
{
Student s1=new Student(1,"Reena");
Student s2=new Student(2,"Deepa");
Student s3=new Student(3,"Varsha");
Student s4=new Student(4,"Gaurav");
Student s5=new Student(5,"Varun");
Student s6=new Student(6,"Reena");

ArrayList al = new ArrayList();


al.add(s1);
al.add(s2);
al.add(s3);
al.add(s4);
al.add(s5);
al.add(0,s6);

Iterator itr= al.iterator();


while(itr.hasNext())
{
Student s = (Student)itr.next();
System.out.print(s.rollNo+". ");
System.out.println(s.name);
System.out.println("--------------------------");
}

class Student
{
int rollNo;
String name;

public Student(int rollNo, String name) {


this.rollNo = rollNo;
this.name = name;
}

Map Interface =
Is not comes under Collection
But it enables you to create a collection with key-value pair objects
Both the keys and values are objects
Uisng Key object we can access value object
Key objects must be unique where as Value objects can be duplicate.

Aailable inseide util package


HashMap,TreeMap,HashTable
1) HashMap - Stores objects in an unordered form, One null value for a
key & any number of null values for Values
Key Value
1 null n can be null
get(Object key)
put(key,value)

2) TreeMap - Create a collection of objects in the sorted order with


uniqu keys
Sorted collection improves the retrieval process of objects

3) HashTable

Deque Interface (Double ended queue)


Insertion and deletion is from both ends.

ArrayDeque
Resizable array. Methods are not synchronised

Implementing Sorting
Comparable & Comparator

https://www.javatpoint.com/difference-between-comparable-and-comparator

Comparable Comparator
1) Comparable provides a single sorting sequence. In other words, we can
sort the collection on the basis of a single element such as id or name
or price, etc. The Comparator provides multiple sorting sequences. In
other words, we can sort the collection on the basis of multiple elements
such as id, name, and price, etc.
2) Comparable affects the original class, i.e., the actual class is
modified. Comparator doesn't affect the original class, i.e., actual
class is not modified.
3) Comparable provides compareTo() method to sort elements. Comparator
provides compare() method to sort elements.
4) Comparable is found in java.langpackage. A Comparator is found in the
java.utilpackage.
5) We can sort the list elements of Comparable type by
Collections.sort(List)method. We can sort the list elements of
Comparator type by Collections.sort(List, Comparator)method.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

class Student implements Comparable<Student>


{
int rollno;
String name;
int age;

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


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

public int getRollno() {


return rollno;
}
public String getName() {
return name;
}

public int getAge() {


return age;
}

@Override
public int compareTo(Student st) //obj1.compareTo(obj2)
{
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

public class Test {


public static void main(String[] args)
{
List<Student> list = new ArrayList<>();
Student s1 = new Student(111, "sama", 2);
Student s2 = new Student(444, "Darsh", 14);
Student s3 = new Student(222, "Aasha", 22);
Student s4 = new Student(333, "Namita", 35);

list.add(s4);
list.add(s1);
list.add(s2);
list.add(s3);

System.out.println("Size of collection:\t"+list.size());

Iterator itr1 = list.iterator();


System.out.println("RollNo\t|Name\t\t|Age");
while(itr1.hasNext())
{
Student stud = (Student)itr1.next();

System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}

Collections.sort(list);

Iterator itr = list.iterator();


System.out.println("RollNo\t|Name\t\t|Age");
while(itr.hasNext())
{
Student stud = (Student)itr.next();

System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}
}
}
Comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

class NameComparator implements Comparator<Student>


{
public int compare(Student s1,Student s2)
{
return s1.name.compareTo(s2.name);
}
}
/*
class AgeComparator implements Comparator<Student>
{
}
class RollNoComparator implements Comparator<Student>
{
}
*/
class Student
{
int rollno;
String name;
int age;

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


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

public int getRollno() {


return rollno;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}

public class Test {


public static void main(String[] args)
{
List<Student> list = new ArrayList<>();
Student s1 = new Student(111, "sama", 2);
Student s2 = new Student(444, "Darsh", 14);
Student s3 = new Student(222, "Aasha", 22);
Student s4 = new Student(333, "Namita", 35);

list.add(s4);
list.add(s1);
list.add(s2);
list.add(s3);

System.out.println("Size of collection:\t"+list.size());

Iterator itr1 = list.iterator();


System.out.println("RollNo\t|Name\t\t|Age");
while(itr1.hasNext())
{
Student stud = (Student)itr1.next();

System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}

Collections.sort(list,new NameComparator());
//Collections.sort(list,new AgeComparator());
//Collections.sort(list,new RollNoComparator());

Iterator itr = list.iterator();


System.out.println("RollNo\t|Name\t\t|Age");
while(itr.hasNext())
{
Student stud = (Student)itr.next();

System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}
}
}

Chapter 5
Thread
Thread

public class MyThread {


public static void main(String[] args)
{

Thread th = Thread.currentThread();
System.out.println("Name of Current Thread:\t" + th.getName());
System.out.println("Priority of Current
Thread:\t"+th.getPriority());
th.setName("sama");
System.out.println("New Name of Thread:\t"+th.getName());
}
}
-------------------------------------------------
public class Thread1 extends Thread
{
public static void main(String[] args)
{
Thread1 th = new Thread1(); // newly born thread
th.start(); //thread in runnable mode

System.out.println("main() is executing");
for (int i = 1; i <= 5; i++)
{
System.out.println("main thread executing " + i);
}
}
public void run()
{
for (int i = 1; i <= 5; i++)
{
System.out.println("Child thread executing " + i);
}
}
}

-----------------------------------------------------------------
public class Thread2
{
public static void main(String[] args) throws InterruptedException
{
Thread th = Thread.currentThread();
System.out.println("Hello");
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
System.out.println("Thread Is Iterrupted");
}
System.out.println("Hi");
Thread.sleep(3000);
System.out.println("Bye");
}

}
-----------------------------------------------------------
public class Thread3
{
public static void main(String[] args)
{
Test t = new Test();
Thread th = new Thread(t);
th.start();
}
}
class Test implements Runnable
{
@Override
public void run()
{
for (int i = 1; i <=5; i++)
{
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Exception Occurs");
}
System.out.println("i =" + i);
}
}

}
-------------------------------------------------------------------
public class Thread4
{
public static void main(String[] args)
{
Test1 th1 = new Test1();
Test2 th2 = new Test2();
th1.start();
th2.start();
System.out.println("Inside main thread");
}
}
class Test1 extends Thread
{
public void run()
{
for (int i = 0; i <=5; i++)
{
try {
Thread.sleep(1000);
System.out.println("Thread1 :\t"+i);
} catch (InterruptedException ex) {
System.out.println("Exception Occurs");
}
}
}
}
class Test2 extends Thread
{
public void run()
{
for (int i = 10; i >=1; i--)
{
try {
Thread.sleep(1000);
System.out.println("Thread2 :\t"+i);
} catch (InterruptedException ex) {
System.out.println("Exception Occurs");
}

}
}
}
---------------------------------------------------------------------
After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run
once but for second time, it will throw exception.
-----------------------------------------------------------
public class Thread5 extends Thread
{
public static void main(String[] args)
{
Thread5 t1 = new Thread5();
Thread5 t2 = new Thread5();
//t1.start();
//t2.start();
t1.run();
t2.run();
System.out.println("Hi");
System.out.println("Hello");
}
public void run()
{
//System.out.println(Thread.currentThread().getName());
for (int i = 1; i <=5; i++)
{
try {
Thread.sleep(2000);
//System.out.println(Thread.currentThread().getName());
System.out.println( i);
} catch (InterruptedException ex) {
System.out.println("Exception Occurs");
}

}
}

}
no context-switching because here t1 and t2 will be treated as normal
object not thread object.

-----------------------------------------------------------
If you want to make a user thread as Daemon, it must not be started
otherwise it will throw IllegalThreadStateException.
--------------------------------------------------

Thread safe
local - inside method
method parameter
exception hadlers-iside catch block
immutble objects - String , final variables

---------------------------------
shared data is not thread safe
instance variable
static variable

------------------------------------------------------------------

Chapter 6
Synchronization

Chapter 7
Sreams
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TestPr


{
public static void main(String[] args)
{
Properties prop = new Properties();

try {
FileInputStream fis = new
FileInputStream("d:\\reena\\mypr.txt");

prop.load(fis);
} catch (FileNotFoundException ex) {
System.out.println("File Does Not Exixts");
} catch (IOException ex) {
System.out.println("Unable To Read");
}

System.out.println("Batch is " + prop.getProperty("Batch"));


System.out.println("Timing is " + prop.getProperty("Time"));
System.out.println("Faculty is " + prop.getProperty("Faculty"));
}
}

-------------------------------------------------------------------------
---
package chap8_2;
public class Chap8_2 {
public static void main(String[] args)
{
String str = "Reena sama";
System.out.println(str);
System.out.println(str.contains("ee"));
System.out.println(str.replace("ee", "i"));
System.out.println(str.contains("Ri"));
String s=new String(" s a m a ");
System.out.println(s.length());
//removes extra leading & trailing spaces

String newS = s.trim();


System.out.println(newS.length());
}
}

-------------------------------------------------------------------------
----------

PrintStream ---------println() - byte - autoflush

PrintWriter ---------println() - character

Buffer - its a temporary storage location for incoming & outgoing data
cpu, printer

flush()

-------------------------------------------------------------------------
--------------
String - immutable, Once assigned cant be changes

StrinBuffer - muttable, Thread safe (constant resizing buffers leads to


performance issue

StringBuilder - muttable, Not Thread safe

StringBuffer & StringBuilder are more efficient than + concatenation


operator

public static void main(String[] args)


{
String str = new String("sama");
System.out.println(str.hashCode());
str+="vaishali"; //as its immutable
System.out.println(str.hashCode());

StringBuffer s = new StringBuffer("sama");


System.out.println(s.hashCode());
s.append(" vaishali");
System.out.println(s.hashCode());

StringTokenizer
-------------------------------------------------------------------------
------------
package chap8_2;

import java.util.StringTokenizer;

public class TestSplit


{
/* public static void main(String[] args)
{
String names="Gaurav pawar, Abhishek Patel, Sanjay Behera, Varun
Gajare, Nidhi Niranjan";
String[] arr = names.split(", ");

for (int i = 0; i < arr.length; i++)


{
System.out.println("Arr["+i+"] = "+arr[i]);
}
}
} */
public static void main(String[] args)
{
String names="Gaurav pawar, Abhishek Patel, Sanjay Behera, Varun
Gajare, Nidhi Niranjan";
StringTokenizer st = new StringTokenizer(names,", ");

while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

/*
split(", ") - uses , & space together as delimiter value
StringTokenizer uses both , & spaces separately as a delimiter
*/
-------------------------------------------------------------------------
---
package chap8_2;

import java.util.Scanner;

public class TestScanner


{
public static void main(String[] args)
{
String nums="10.1, 10.2, 10.3, 10.4, 10.5" ;
Scanner sc;

sc=new Scanner(nums).useDelimiter(", ");

float ans=0f;
try
{
while(sc.hasNextFloat())
{
//System.out.println(sc.nextFloat());
float f =sc.nextFloat();
ans+=f;
}
System.out.println(ans);

}catch(Exception ex)
{
System.out.println("");
}
}

File IO

File Input/Output

Whenaver we open a file for reading or writing purpose we have to call it


as stream

stream - flow of data


Types

1) Binary Stream - flow of Bytes- - Stream


.exe, .dll, .jar, .war, .ear, .class

images

2) text stream flow of character --Reader/Writer


.txt, .docx,

variable - life is limited to the block in which its declared


Object - life is limited to prg once u ends up prg objects gets destroyed
------------future use?????????????

File IO
Ram------------------------Hards Disk
Temporary Permanet

A- 65
a- 97
0-48
space - 32
Enter -13
Excape - 27
tab -8
End of the File (-1)
Buffer- its a temporary storage location for incoming & outgoing data
.

when buffer gets full it will automatically gets push for further process

But if forcefully wants to send/push data for futher process we have to


use

flush()

c:\sama\a.txt

c:\\sama\\a.txt

c:/sama/a.txt

write - Serialization
Object------------------------------->file
<-------------------------------

read - deserialization

class.method() - if method is static


object.method() - if method is non static

System.out.println()
System.in.Read();
class obj method

class System
{
public static PrintStream out;

class PrintStream
{
println()......
Read()
}

byte decimal
00001000=8
00001111=15
00010000=16
00100000=32
01000000=64
10000001=129
11111111=255

byte hexadecimal decimal ASCII


00110000 0x30 48 '0'
00110001 0x31 49 '1'
.
.
00111001 0x39 57 '9'
.
.
01000001 0x41 65 'A'
01000010 0x42 66 'B'
.
.
01011010 0x5A 90 'Z'

01100001 0x61 97 'a'


.
.
01111010 0x7A 122 'z'

connecting the BufferedReader stream with the InputStreamReader stream


for reading the line by line data from the keyboard.

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);
------------------------------------------------------------------
InputStreamReader - byte by byte/ array
BuffredeReader - Line by Line
Channel - block - its possible to read entire file at time (Introduced in
java 4 nio)
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ByteChannelCopyTest {

public static void main(String[] args) {


if (args.length < 2) {
System.out.println("Usage: ByteChannelCopyTest <original
file> <copy>");
System.exit(-1);
}
try (FileChannel fcIn = new
FileInputStream(args[0]).getChannel();
FileChannel fcOut = new
FileOutputStream(args[1]).getChannel()) {
System.out.println("File size: " + fcIn.size());
// Create a buffer to read into
ByteBuffer buff = ByteBuffer.allocate((int) fcIn.size());
System.out.println("Bytes remaining: " + buff.remaining());
System.out.println ("Bytes read: " + fcIn.read(buff));
buff.position(0);
System.out.println ("Buffer: " + buff);
System.out.println("Bytes remaining: " + buff.remaining());
System.out.println("Wrote: " + fcOut.write(buff) + "
bytes");
} catch (FileNotFoundException f) {
System.out.println("File not found: " + f);
} catch (IOException e) {
System.out.println("IOException: " + e);
}
-------------------------------------------------

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

class BufferedStreamCopyTest {

public static void main(String[] args) {


// Test the arguments - there should be two
if (args.length < 2) {
System.out.println("Usage: java TestNodeStreams file1
file2\nBoth file names are required.");
System.exit(-1);
}
try (BufferedReader bufInput = new BufferedReader(new
FileReader(args[0]));
BufferedWriter bufOutput = new BufferedWriter(new
FileWriter(args[1]))) {
String line = "";
// read the first line
while ((line = bufInput.readLine()) != null) {
// write the line out to the output file
bufOutput.write(line);
bufOutput.newLine();
}
} catch (FileNotFoundException f) {
System.out.println("File not found: " + f);
} catch (IOException e) {
System.out.println("Exception: " + e);
}
}
}
------------------------------------------------------
Serialization

variable - local to block


object - prg , gc

IO - plain text / byte

class student
{
rollno,name,add
Address addr;
}
class Address
{
add1, add2,city, state, country.....
}

Student s1,s2,s3...s100;

serialization
object/instance---------------------------------------------->file
ram HDD
temporary permanent
<--------------------------------------------------
deserialization

byte byte

concrete class - all methods are defined


abstract class - at least one method should be abstract
interface - all methods are absract
marker interface /blank interface - interface without any method
Serializable, Clonable

transient & static are not serialized

byte decimal
00001000=8
00001111=15
00010000=16
00100000=32
01000000=64
10000001=129
11111111=255

byte hexadecimal decimal ASCII


00110000 0x30 48 '0'
00110001 0x31 49 '1'
.
.
00111001 0x39 57 '9'
.
.
01000001 0x41 65 'A'
01000010 0x42 66 'B'
.
.
01011010 0x5A 90 'Z'

01100001 0x61 97 'a'


.
.
01111010 0x7A 122 'z'

connecting the BufferedReader stream with the InputStreamReader stream


for reading the line by line data from the keyboard.

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);

The Java Console class is be used to get input from console. It provides
methods to read text and password.

If you read password using Console class, it will not be displayed to the
user.

The java.io.Console class is attached with system console internally. The


Console class is introduced since 1.5.

Let's see a simple example to read text from console.

String text=System.console().readLine();
System.out.println("Text is: "+text);

import java.io.File;

public class MyFileOperations {

public static void main(String[] a){


try{

File file = new File("fileName");

//Tests whether the application can read the file

System.out.println(file.canRead());

//Tests whether the application can modify the file

System.out.println(file.canWrite());

//Tests whether the application can modify the file

System.out.println(file.createNewFile());

//Deletes the file or directory

System.out.println(file.delete());

//Tests whether the file or directory exists.

System.out.println(file.exists());

//Returns the absolute pathname string.

System.out.println(file.getAbsolutePath());

//Tests whether the file is a directory or not.

System.out.println(file.isDirectory());

//Tests whether the file is a hidden file or not.


System.out.println(file.isHidden());

//Returns an array of strings naming the

//files and directories in the directory.

System.out.println(file.list());
System.out.println(file.lastModified());

} catch(Exception ex){

-----------------------------------
import java.io.File;

public class FileListFromFolder {

public static void main(String a[]){

File file = new File("C:/MyFolder/");

String[] fileList = file.list();

for(String name:fileList){

System.out.println(name);

}
------------------------------
using byte array. You need to read fixed size of content each time, read
multiple times, till end of the file.

BufferedReader to read file content line by line,


By calling readLine() method you can get file content line by line.
readLine() returns one line at each iteration, we have to iterate it till
it returns null.

-------------------------------
public class ByteWriteToFile {

public static void main(String[] args) {


OutputStream opStream = null;

try {

String strContent = "This example shows how to write byte


content to a file";

byte[] byteContent = strContent.getBytes();

File myFile = new File("C:/MyTestFile.txt");

// check if file exist, otherwise create the file before


writing

if (!myFile.exists()) {

myFile.createNewFile();

opStream = new FileOutputStream(myFile);

opStream.write(byteContent);

opStream.flush();

} catch (IOException e) {

e.printStackTrace();

} finally{

try{

if(opStream != null) opStream.close();

} catch(Exception ex){

}
-------------------------------------
public class WriteToFile {

public static void main(String[] args) {

BufferedWriter bufferedWriter = null;

try {
String strContent = "This example shows how to write string
content to a file";

File myFile = new File("C:/MyTestFile.txt");

// check if file exist, otherwise create the file before


writing

if (!myFile.exists()) {

myFile.createNewFile();

Writer writer = new FileWriter(myFile);

bufferedWriter = new BufferedWriter(writer);

bufferedWriter.write(strContent);

} catch (IOException e) {

e.printStackTrace();

} finally{

try{

if(bufferedWriter != null) bufferedWriter.close();

} catch(Exception ex){

}
-----------------------------------------
?To avoid resource leaks, programmer must close a stream when it is no
longer needed

6down voteaccepted

Using a byte array will be faster:



You don't have the bytes to characters decoding step, which is at least a
copy loop, and possibly more depending on the Charset used to do the
decoding.


The byte array will take less space, and hence save CPU cycles in GC /
initialization.
However:

Unless you are searching huge files, the difference is unlikely to be
significant.


The byte array approach could FAIL if the input file is not encoded in an
8 bit character set. And even if it works (as it does for UTF-8 & UTF-16)
there are potential issues with matching characters that span buffer
boundaries.

Chapter 8

NIO

File System, Paths & Files

java.nio.file.Path

Paths - reprents File & directory


(can be
1) absolute(root directory mention-c:,d:e:) &
2) relative

windows root directories are c: or d: or e:


solaris /home
)
(similar to java.io.File)

Helper class Paths

path object is immutable (once assign we cant change)

path - very imp


1)access component
filename,parent dir, root, name count
2)operation
normalize(removes redundant folder),
uri, abslote path,
subpath(dir nearest to root is 0th index),
resolve(to combine 2 paths)
3) compare path
startsWith, endsWith, equal

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathTest {

public static void main(String[] args) {


Path p1 = Paths.get(args[0]);
System.out.format("getFileName: %s%n", p1.getFileName());
System.out.format("getParent: %s%n", p1.getParent());
System.out.format("getNameCount: %d%n", p1.getNameCount());
System.out.format("getRoot: %s%n", p1.getRoot());
System.out.format("isAbsolute: %b%n", p1.isAbsolute());
System.out.format("toAbsolutePath: %s%n", p1.toAbsolutePath());
System.out.format("toURI: %s%n", p1.toUri());
}
}

. represents current directory


.. represents parent directory

package com.example;

import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathOperationsTest {

public static void main(String[] args) {


// Normalize
System.out.println ("Normalize");
Path p1 = Paths.get("/home/student/./bob/file");
Path pN1 = p1.normalize();
Path p2 = Paths.get("/home/student/bob/../sally/file");
Path pN2 = p2.normalize();
System.out.format("Normalized paths: %s%n%s%n", pN1, pN2);
// Subpath
System.out.println ("Subpath");
Path p3 = Paths.get("D:\\Temp\\foo\\bar");
Path p4 = p3.subpath(0, 2);
System.out.println("Count: " + p3.getNameCount());
System.out.println(p3.getName(0));
System.out.println(p4);
// Resolve
System.out.println ("Resolve");
Path p5 = Paths.get("/home/clarence/foo");
Path p6 = p5.resolve("bar");
System.out.println(p6);
Path p7 = Paths.get("foo").resolve("/home/clarence");
System.out.println(p7);
// Relativize
System.out.println ("Relativize");
Path p8 = Paths.get("peter");
Path p9 = Paths.get("clarence");
Path p8Top9 = p8.relativize(p9);
Path p9Top8 = p9.relativize(p8);
System.out.println(p8Top9);
System.out.println(p9Top8);
}
}

symbolic link/ symlink/ soft link

Hard Link

import java.nio.file.*;

class TestSymLnk
{
public static void main(String[] str) throws Exception
{
Path target = Paths.get("d:/a.txt");
Path link = Paths.get("d:/links/c.txt");

// creates hard link


Files.createLink(link, target);

// returns true
Files.exists(link);
}
}
1) only create a.txt in D:
2) create D:\links folder
3)Now chk c.txt inside links folder
4) modify d:\a.txt
5) chk d:\links\c.txt changes automatically gets reflects

exists() - wil chk


1)file exists
2)file does not exists
3)permissions

Path p = Paths.get("a.txt");
!Files.exists(p) diff from Files.notExixts(p)
if file does not exists

!(false) false
true

CUI - directory
GUI - folder

Create File & Directory

Files.createFile(path);
Files.createDirectory(path);
Files.createDirectories(Paths.get("d:\sama\a\b\f");

create directories that do not eists from top to bottom

Delete Files or derectory


Files.delete(path)
NoSuchFileException
DirectoryNotEmptyException ( trying to delete dir which is not
empty)
IOException
Files.deleteifExists(path) (safe)

Copy files & directories


Files.copy(srcpath, destpath, copyOptions)
when directories are copied files inside does not get copy.
copyOptions - Relace, link follow

---------------------------------------------------------------
package javanio;

import java.io.*;
import java.nio.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTMLDocument;

class NewFileIO {

Scanner sc;
private List<String> lines;

void createSymLink() throws IOException {

sc = new Scanner(System.in);

System.out.println("Enter name of link file : ");


String link = sc.next();
System.out.println("Enter name of target file : ");
String target = sc.next();

Path linkfile = Paths.get(link);


Path targetfile = Paths.get(target);

try {
Files.createSymbolicLink(linkfile, targetfile);
} catch (Exception ex) {
System.out.println("Exception : " + ex.getMessage());
}

System.out.println("Link created,Link Details : -");


try
{
System.out.println("Target File of " + linkfile.toString() +
" : " + Files.readSymbolicLink(targetfile));
} catch (Exception ex)
{
System.out.println("Exception : " + ex.getMessage());
}
}

void createFile() throws IOException {


sc = new Scanner(System.in);
System.out.println("Enter name of file that u want to create
: ");
String fname = sc.next();
Path p = Paths.get(fname);

if (Files.exists(p) == true) {
System.out.println(p.toString() + " already exists...");
return;
}

Files.createFile(p);
System.out.println(p.toString() + " created...");
}

void createFolder() throws IOException {


sc = new Scanner(System.in);
System.out.println("Enter name of directory(Folder) that u want
to create : ");
String fname = sc.next();
Path p = Paths.get(fname);

if (Files.exists(p) == true) {
System.out.println(p.toString() + " already exists...");
return;
}

Files.createDirectory(p);
System.out.println(p.toString() + " created...");
}

void deleteFile() {
sc = new Scanner(System.in);
System.out.println("Enter name of file that u want to delete
: ");
String fname = sc.next();
Path p = Paths.get(fname);
if (Files.exists(p, LinkOption.NOFOLLOW_LINKS) == false) {
System.out.println(fname + " does not exists...");
return;
}

try {
Files.delete(p);
System.out.println(fname + " deleted successfully...");

} catch (Exception ex) {


System.out.println("Exception : " + ex.getMessage());
}

void copyFiles() throws IOException {


sc = new Scanner(System.in);
System.out.println("Enter name of source file : ");
String sname = sc.next();
System.out.println("Enter name of target file : ");
String tname = sc.next();

Path p1 = Paths.get(sname);
Path p2 = Paths.get(tname);

if (Files.exists(p1) == false) {
System.out.println("Source file does not exsits.");
} else {
if (Files.exists(p2) == true) {
Files.copy(p1, p2, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File successfully replaced...");
} else {
Files.copy(p1, p2);
System.out.println("File successfully copied...");
}
}

}
void showFolderContent() throws IOException {
sc = new Scanner(System.in);
System.out.println("Enter name of folder : ");
String foldername = sc.next();
Path dirPath = Paths.get(foldername);
if (Files.exists(dirPath) == false) {
System.out.println("Path does not exists...");
} else if (Files.isDirectory(dirPath) == false) {
System.out.println("Path does not is a directory..");
} else {
DirectoryStream<Path> stream =
Files.newDirectoryStream(dirPath);
System.out.println("******************************");
int filectr = 0;
for (Path p : stream) {
if (Files.isDirectory(p) == true) //don't show folder
{
continue;
}
System.out.println(p.getFileName());
filectr++;
}
System.out.println("");
System.out.println("******************************");
System.out.println("Total File(s) : " + filectr);

}
}

void writeData() throws IOException {


sc = new Scanner(System.in);
System.out.println("Enter name of file : ");
String fname = sc.next();

Path p1 = Paths.get(fname);

System.out.println("Enter Your Data and type quit to exit");


System.out.println("**************************************");
List<String> lines = new ArrayList<String>();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();

while (!line.toLowerCase().equals("quit"))
{
lines.add(line);
line = br.readLine();
}
Files.write(p1, lines, Charset.defaultCharset(),
StandardOpenOption.CREATE);

System.out.println("**************************************");
System.out.println("Data Saved....");

}
void readData() throws IOException {
sc = new Scanner(System.in);
System.out.println("Enter name of source file : ");
String fname = sc.next();

Path p1 = Paths.get(fname);
if (Files.exists(p1) == false) {
System.out.println(fname + " does not exists...");
} else {
List<String> lines;
System.out.println("*********************************");
lines = Files.readAllLines(p1, Charset.defaultCharset());

Iterator<String> it = lines.iterator();

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

void showMenu() throws IOException {


sc = new Scanner(System.in);
System.out.println("************************");
System.out.println("1.Create Link");
System.out.println("2.Create Folder");
System.out.println("3.Create File");
System.out.println("4.Delete File ");
System.out.println("5.Copy File ");
System.out.println("6.See Folder's Content ");
System.out.println("7.Write Data");
System.out.println("8.Read Data");
System.out.println("************************");
System.out.print("Enter your choice : ");
int ch = sc.nextInt();

switch (ch) {
case 1:
createSymLink();
break;
case 2:
createFolder();
break;
case 3:
createFile();
break;
case 4:
deleteFile();
break;
case 5:
copyFiles();
break;

case 6:
showFolderContent();
break;
case 7:
writeData();
break;
case 8:
readData();
break;

default:
break;
}

}
}

public class JavaNIO {

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


System.out.println("*******************************");

int contenue = 1;
NewFileIO obj = new NewFileIO();
Scanner sc1 = new Scanner(System.in);

while (contenue == 1) {
obj.showMenu();
System.out.println("*******************************");
System.out.println("Do you want to continue {1|0}");
contenue = sc1.nextInt();
}
}
}

---------------------------------------------------------------

i=i+1; atomic operation

i++; not atomic operartion


2-3 machine cycle
1)allocate temp mem & store i
3)increase & update

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ByteChannelCopyTest {

public static void main(String[] args) {


if (args.length < 2) {
System.out.println("Usage: ByteChannelCopyTest <original
file> <copy>");
System.exit(-1);
}
try (FileChannel fcIn = new
FileInputStream(args[0]).getChannel();
FileChannel fcOut = new
FileOutputStream(args[1]).getChannel()) {
System.out.println("File size: " + fcIn.size());
// Create a buffer to read into
ByteBuffer buff = ByteBuffer.allocate((int) fcIn.size());
System.out.println("Bytes remaining: " + buff.remaining());
System.out.println ("Bytes read: " + fcIn.read(buff));
buff.position(0);
System.out.println ("Buffer: " + buff);
System.out.println("Bytes remaining: " + buff.remaining());
System.out.println("Wrote: " + fcOut.write(buff) + "
bytes");
} catch (FileNotFoundException f) {
System.out.println("File not found: " + f);
} catch (IOException e) {
System.out.println("IOException: " + e);
}

}
}

Chapter 9
JDBC
Intro To JDBC
Java Database Connectivity

Frontend Backend
To design User Interface To store & Manupulate data

Enter ID Tabular format data


Enter Pwd srNo Id Pwd
Submit Reset 1 sa sama
2 aa amit

java/ c#/ PHP oracle,sql server 2012, Mysql, Ms access

Impedence mismatch - as both the technologies are diff, so not able to


talk with each other

package Database
classes table
String varchar
instance record/row
primary key
Inheritance relataions
Java App-------------------------------------->Sql Database
<--------------------------------------

Different Types of driver (4)


1) JDBC-ODBC bridge driver/Type 1 driver
2) Type 2/Native-API Driver
3) Type 3/Network Protocol Driver
4) Type 4/Native Protocol Driver

1) JDBC-ODBC bridge driver/Type 1 driver


Usally used with standalone application
2) Type 2/Native-API Driver
Uses local native libraries, usally used for network based
application, better performance than type1 driver
3) Type 3/Network Protocol Driver
Conatins client & server portion
client - pure java function
server - native java function
(native - method is not from java environment)
4) Type 4/Native Protocol Driver

jdbcodbcbridge driver
Java----Jdbc API-------------------------------------------ODBC driver---
------backend

JDBC API - conatins java.sql & javax.sql, .... pakages.


It has different classes & interfaces
1) DriverManagr -class loads the drivers for database
2) Driver interface- repersents the databse driver
3) Connection interface - establish connection between frontend & backend
4) Statement interface - enables to execute sql statement
a) statement - comple sql statement
select * from students where rollno = 10
b) prepared statement - incomplete
select * from student where rollno = ?
c) callable statement - stored procedure
precompiled
5) ResultSet interface - reprsents information retrieved from database
6) SqlException class -
7) ResultsetMetadata - Meta - information of information, no of
rows,columns, names of the column, data type
6) DatabaseMetadata - No of tables

class - is keyword used to define user defined class


Class - in build class, used to establish a connction bet backend &
frontend

1) load & register required drivers


2) connect to databse
3) create & execute sql statements
4) Handle sqlexception
1) load & register required drivers
a) Class.forName("package.subpackage.subpackage.DriverClassName")
Type4 -
SqlServer - "com.microsoft.sqlserver.jdbc.SQLServerDriver"
oracle -
mysql -
derby -
derby - Netbeans has provided in build database as a utility (means we
will ot get full fledged funtionality of backend)

b) DriverManager.registerDriver()
Driver d = new <drivername>;
DriverManager.registerDriver(d);

2) connect to databse
3) create & execute sql statements
4) Handle sqlexception

Chapter 10
Advanced JDBC

S-ar putea să vă placă și