Documente Academic
Documente Profesional
Documente Cultură
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
Just like class, interface, package & Frame we can also add Java
Exception
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.
Types
1) default
without parameter
2)parameterized
class Student{}
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
}
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
class Animal
{
public Animal()
{
System.out.println("Default Constructor of Animal 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;
}
@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
//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
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());
}
}
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
==
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
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() {
}
-------------------------------
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
Interface ElectronicDevice
remote() – is common
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
System.out.println(obj.sum(12.1f, 10.2f));
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;
}
}
}
}
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.
System.out.println("Enter Number2:\t");
j = sc.nextInt();
try
{
ans=i/j;
}
catch(Exception ex)
{
System.out.println("Exception Occurs:\t"+ex.toString());
}
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
Demo2
NullPointerException
Demo3
CheckedException Demo
Deo4
NumberFormatException
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
}
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
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);
}
}
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
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
javac java
.java------------------------.class---------------------------native
machine language
bytecode
ways
1)
Hadling an Exception (unchecked exception)
2)
Declaring Exception (checked exception)
throws -
throw
The Java throw keyword is used to explicitly throw an 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;
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;
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
{}
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");
}
}
}
---------------------------------------------------
Throwable
-----------------------------------------------------
Assertion - used just to chk your assumptions
javac Test.java
2 erros
now 3 warnings
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
==================================================
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
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
lblMsg.setFont(myFont);
}
else
{
lblMsg.setText("Inavlid User Plz Try Again");
lblMsg.setForeground(Color.red);
}
}
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt)
{
sub();
}
====================================================
//String Fruits[]={"Mango","Pear","Orange","Apple","Grapes"};
//JComboBox cb=new JComboBox(Fruits);
==============================================================
Programming In Java
Chapter 1
Inner classes & Type Casting
A Class defined inside another class is called as inner class.
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
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);
}
}
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());
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
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;
}
----------------------------------------------------------------------
package mygenerics;
import java.util.ArrayList;
import java.util.Iterator;
class Student
{
int rollNo;
String 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.
3) HashTable
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;
@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;
}
}
list.add(s4);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("Size of collection:\t"+list.size());
System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}
Collections.sort(list);
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;
list.add(s4);
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("Size of collection:\t"+list.size());
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());
System.out.println(stud.rollno+"\t|"+stud.name+"\t\t|"+stud.age);
}
}
}
Chapter 5
Thread
Thread
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;
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");
}
-------------------------------------------------------------------------
---
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
-------------------------------------------------------------------------
----------
Buffer - its a temporary storage location for incoming & outgoing data
cpu, printer
flush()
-------------------------------------------------------------------------
--------------
String - immutable, Once assigned cant be changes
StringTokenizer
-------------------------------------------------------------------------
------------
package chap8_2;
import java.util.StringTokenizer;
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;
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
images
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
flush()
c:\sama\a.txt
c:\\sama\\a.txt
c:/sama/a.txt
write - Serialization
Object------------------------------->file
<-------------------------------
read - deserialization
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
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 {
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
byte decimal
00001000=8
00001111=15
00010000=16
00100000=32
01000000=64
10000001=129
11111111=255
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.
String text=System.console().readLine();
System.out.println("Text is: "+text);
import java.io.File;
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.createNewFile());
System.out.println(file.delete());
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.isDirectory());
System.out.println(file.list());
System.out.println(file.lastModified());
} catch(Exception ex){
-----------------------------------
import java.io.File;
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.
-------------------------------
public class ByteWriteToFile {
try {
if (!myFile.exists()) {
myFile.createNewFile();
opStream.write(byteContent);
opStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
} catch(Exception ex){
}
-------------------------------------
public class WriteToFile {
try {
String strContent = "This example shows how to write string
content to a file";
if (!myFile.exists()) {
myFile.createNewFile();
bufferedWriter.write(strContent);
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
} catch(Exception ex){
}
-----------------------------------------
?To avoid resource leaks, programmer must close a stream when it is no
longer needed
6down voteaccepted
•
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
java.nio.file.Path
import java.nio.file.Path;
import java.nio.file.Paths;
package com.example;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
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");
// 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
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
Files.createFile(path);
Files.createDirectory(path);
Files.createDirectories(Paths.get("d:\sama\a\b\f");
---------------------------------------------------------------
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;
sc = new Scanner(System.in);
try {
Files.createSymbolicLink(linkfile, targetfile);
} catch (Exception ex) {
System.out.println("Exception : " + ex.getMessage());
}
if (Files.exists(p) == true) {
System.out.println(p.toString() + " already exists...");
return;
}
Files.createFile(p);
System.out.println(p.toString() + " created...");
}
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...");
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);
}
}
Path p1 = Paths.get(fname);
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());
}
}
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;
}
}
}
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();
}
}
}
---------------------------------------------------------------
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;
}
}
Chapter 9
JDBC
Intro To JDBC
Java Database Connectivity
Frontend Backend
To design User Interface To store & Manupulate data
package Database
classes table
String varchar
instance record/row
primary key
Inheritance relataions
Java App-------------------------------------->Sql Database
<--------------------------------------
jdbcodbcbridge driver
Java----Jdbc API-------------------------------------------ODBC driver---
------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