Core Java
Core Java
Introduction: What is Java? * Java is a platform independent, * True object Oriented Programming Language * Developed by James Gosling and Patrick Nagughton of Sun Microsystems, USA in 1991. * It was the first Programming Language, which was not Dependent on any particular hardware/software. * It was initially named as oak and later renamed as java in 1995. Platform neutral: The motto of Java is "Write Once Run Anywhere" when a program is compiled, it is translated into machine code that are specific to the processor. In the Java Development Environment, there are two parts. - A Java Compiler - A Java Interpreter The java compiler generates bytecodes (A set of instruction that resembles machine code but are not specific to any processor) instead of machine code. The java interpreter executes the Java Program. (Bytecodes)
Java Source Program -> JVM (Bytecode) -> Java Interpreter JVM - Java Virtual Machine. Developing a Java Program: The Sun's Java Development Kit (JDK) provides all features to write a Java program. Java Programs are classified into two types 1. Applications. 2. Applets. Applications: Java applications are simple standalone programs that can run using the Java Interpreter from the command prompt. Applets: An applet is a dynamic and interactive program that can run inside a webpage displayed by a Java-capable browser such as Netscape Navigator. Java Application Program: It has two parts: 1. A class definition that encloses the entire program. 2. A method called main that contains the body Java Source file extension - .java Java Compiler Java Interpreter - javac - java
Java compiler generates bytecode file with the extension of class. The bytecode is run using the Java Interpreter. Towrite the java program: 1. notepad 2. editor notepad: Startrunnotepad (type)ok Startprogramsaccessoriesnotepad * Editor: Startrun->cmd(type)ok c:\edit (press enter key) set path: to create a batch file(to type a editor) set path=%path%;c:\jdk1.3\bin; save: file name.bat Datatypes Datatype specify the type of value to be stored in the variable. A variable is a location in memory that can hold a value. Integer Datatype Size Byte 1byte Range -128 to 127
class var { int a=10;//reference static int n=10; public static void main(String ar[]) { byte b= 127; //constant short s=32767; int i=236563246; long l=467765322; float f=345.567f; double d=345.6326;
char c='v'; String st="vina "+"csc"; boolean bo; System.out.println("Integer Types:"); System.out.println(b + "\t" + s +"\t" + i + "\t" + l); System.out.println("Float Types:"); System.out.println(f+"\t"+d); System.out.println("Char Types:"); System.out.println(c+st); bo = b > s ; System.out.println("Boolean:\n\t"+bo); } }
Variables Java has three kinds of variables: 1.Local Variables: Local variables are declared and used inside methods. 2.Instance Variables: Instance variables are created when the objects are instantiated and therefore they are associated with objects.
3. Class Variables Class variables are global to a class and belong to the entire set of objects that class creates.
How to get Input at Run time ----------------------------------------1. Command line argument 2. Stream classes import java.io.*; DataInputStream -- directly console BufferedReader -- Temporary (Buffer) InputStreamReader -- buffer to console To throws the exception. IOException Input -----System. in -- to get input from keyboard 1. DataInputStream obj = new DataInputStream (System. in)
2. InputStreamReader obj=new InputStreamReader(System. in); 2. BufferedReader obj1=new BufferedReader (obj); 3. BufferReader ob=new BufferedReader (new InputStreamReader (System. in)); To read input from console -------------------------------Using readLine () method Conversion ----------------All inputs in java are stored in String format. Therefore, we can convert one Type into another using parses method. To Convert String to int, float, double, byte Integer.parseInt Float.parseFloat Double.parseDouble Byte.parseByte import java.io.*; class intro { int p=10;//instance variable static int q=20;//class var public static void main(String ar[])throws IOException {
intro i=new intro(); System.out.println("instance p = " +i.p +"class q= " +q); int a; float b; String s; DataInputStream d=new DataInputStream(System.in); System.out.println("enter the int,float,string val"); a=Integer.parseInt(d.readLine()); b=Float.parseFloat(d.readLine()); s=d.readLine(); System.out.println(" int val : "+a); System.out.println(" float val: "+b); System.out.println(" String : "+s); } } //command line arguments import java.io.*; class cline { public static void main(String ar[])throws IOException { int no; String name; float sal; //DataInputStream d=new DataInputStream(System.in); no=Integer.parseInt(ar[0]); name=ar[1]; sal=Float.parseFloat(ar[2]); System.out.println(+no); System.out.println(name); System.out.println(+sal); } }
Procedural Constructs: 1. Selection - if, switch, ternary operator (? :) 2. Repetition - while, for, do_while 3. Sequence - continue, break FACT: import java.io.*; class fact { public static void main(String ar[])throws IOException { int n,f,i; DataInputStream d=new DataInputStream(System.in); n=Integer.parseInt(d.readLine()); f=n; for(i=1;i<=n;i++) { if (n!=1) { n=n*(f-1); f--; }
/* CONTINUE */ import java.io.*; class conti { public static void main(String ar[])throws IOException { int i,n; DataInputStream ss=new DataInputStream(System.in); System.out.println("enter the n value"); n=Integer.parseInt(ss.readLine()); for(i=1;i<n;i++) { if(i%2!=0) continue; System.out.println(+i); } System.out.println("END"); } }
WHILE: import java.io.*; //import java.lang.String; class whil { public static void main(String ar[])throws IOException { int i=0; DataInputStream d=new DataInputStream(System.in); System.out.println("enter n val"); int n=Integer.parseInt(d.readLine()); if(n==10) { while(i<=10) { System.out.println(+i); i++; } } else if(n==20) { System.out.println("enter num(1,2,3) val"); int a=Integer.parseInt(d.readLine()); //int hh=d.readLine(); switch(a) { case 1: System.out.println("alpha"); alpha break; case 2: System.out.println("hexa");
break; case 3: System.out.println("binary"); break; default: System.out.println("wrong input"); break; } } else { System.out.println("n val is not equal"); } } }
SWITCH CASE: import java.io.*; import java.lang.String.*; class ss { public static void main(String args[])throws IOException { int n,p=0,q=0,ad; int op; String a; InputStreamReader s=new InputStreamReader(System.in); BufferedReader b=new BufferedReader(s); do {
System.out.println(); System.out.println("Enter The Number:"); n=Integer.parseInt(b.readLine()); System.out.println(); System.out.println("1.Factorial \n2.Fibonacee \n3.Sum Of digits \n4.Reverse the Number"); op=Integer.parseInt(b.readLine()); switch(op) { case 1: int count=1; for(int i=n;i>=1;i--) { count=count*i; } System.out.println(); System.out.println("\n The Factorial is:"+count); break; case 2: int f=0; int m=1,d; System.out.println(); System.out.println("The Fibonacee no is:"); System.out.println(+f); System.out.println(+m); int c; c=f+m; System.out.println(+c); for(int j=1;j<=n-3;j++) { d=m+c; m=c; c=d;
System.out.println(+d); } break; case 3: while(n>0) { p=n%10; n=n/10; q=p+q; } System.out.println(); System.out.println("Sum Of digit:"+q); q=0; break; case 4: while(n>0) { p=p*10+n%10; n=n/10; } System.out.println(); System.out.println("Reverse The Number:"+p); p=0; break; default: System.out.println(); System.out.println("Enter the option 1 or 2"); break; } System.out.println(); System.out.println("Do You Want To Continue[y/n]:"); a=b.readLine(); }while(a.equals("y")); }
Classes The main concepts in Object Oriented Programming Language 1. class 2. Inheritance 3. Polymorphism Class A class defines the shape and behaviour of an object. An instance of a class is called an object. An Object is a collection of data members and the related methods that can be treated as single unit. A class contains the definition of attributes and methods. Methods: Methods are functions that operate on instance of class. Creating Object: new Operator: The new operator creates a single instance of a named class and returns a reference to that object.
Ex : Employee emp1 = new Employee(); Constructors: /*constructor: * class name and constructor name must be same. * constructor is invoked when the obj is created. * constructor have no return type not even void. */ CONSTRUCTOR: import java.io.*; class con2 { con2() { System.out.println("This is a default constructor"); } con2(int a,int b) { System.out.println("A value:"+a+"\nB value:"+b); } con2(String na,float m) { System.out.println("String value:"+na+"\nFloat value:"+m); } public static void main(String ar[])throws IOException {
int x,y; float s; String sa; System.out.println(Enter Int,int,Float,Strig); DataInputStream ss=new DataInputStream(System.in); x=Integer.parseInt(ss.readLine()); y=Integer.parseInt(ss.readLine()); s=Float.parseFloat(ss.readLine()); sa=ss.readLine(); con2 c0=new con2(); con2 c1=new con2(x,y); con2 c2=new con2(sa,s); } } //Constructor Using This Key Word this keyword is used to reference of the instance variable import java.io.*; class con3 { float t; int a,b; con3(int p,int q) { this.a=p; this.b=q; System.out.println("the val of a,b "+a+"\t "+b+ "\tadd :"+(a+b)); } int rectarea() { return a*b;
} con3(float f) { this.t=f; } float cir(float t) { return (3.14f*t*t); } public static void main(String ar[])throws IOException { int k,l; float s; System.out.println(Enter int,int float); DataInputStream d=new DataInputStream(System.in); k=Integer.parseInt(d.readLine()); l=Integer.parseInt(d.readLine()); s=Float.parseFloat(d.readLine()); con3 c=new con3(k,l); con3 c1=new con3(s); System.out.println("the val of rectarea" +c.rectarea()); System.out.println("the val of circle"+c1.cir(s)); } } /* Constructor Overloading */ same function name with diff arg class conovr { conovr() //default constructor
{ System.out.println("This is default constructor"); } conovr(int x,int y) { System.out.println("The int is:" +x+ "\t" +y);f } conovr(String m,float n) { System.out.println("The string & float:"+m+ "\t" +n); } public static void main(String ar[]) { conovr co=new conovr(); conovr c1=new conovr(100,200); conovr c2=new conovr(" thuya",123.123f); } }
Finalizer: When an object is no longer referred to by any variable, Java automatically reclaims memory used by that object. This is known as Garbage Collection. Finalizer is a special kind of method, which are called just before the object is garbage collected and its memory is reclaimed. Any cleaning required may be included inside the body of the
finalize() method. This method can be called at any point of time. The Object class defines a default finalizer method, which does nothing. FINALIZER: class con_fina { static String s; con_fina() { System.out.println("This is default constructor"); s="Welcome"; System.out.println("name" +s); } protected void finalize() { System.out.println("I am the finalizer"); s="hai"; System.out.println(" s :" +s); } public static void main(String ar[]) { con_fina c1=new con_fina(); con_fina ss=new con_fina(); ss.finalize(); c1.finalize(); } }
SWAPPING: import java.io.*; class cons { int a,temp; static int b; float g; String n; cons() { System.out.println("This is Default Constructor"); } cons(int c,int d) { this.a=c; cons.b=d; System.out.println("Value Of A & B:"+a+"&"+b); System.out.println("Addition Of A & B:"+(a+b)); System.out.println("Before Swap:"); System.out.println("A:"+a); System.out.println("B:"+b); swap(a,b); } cons(String name,float d) { this.n=name; this.g=d; System.out.println("Name & Float Value:"+n+"&"+g); } void swap(int p,int q) { temp=p;
p=q; q=temp; System.out.println("After Swap:"); System.out.println("A:"+p); System.out.println("B:"+q); } } class swa { public static void main(String a[])throws IOException { int m,n; float c; String na; m=Integer.parseInt(a[0]); n=Integer.parseInt(a[1]); c=Float.parseFloat(a[2]); na=a[3]; cons co=new cons(); cons co1=new cons(m,n); cons co2=new cons(na,c); } } Inner Classes An inner class is a nested class whose instance exists within an instance of its enclosing class and has direct access to the instance members of its enclosing instance. class one {
int no=10; void disp() { System.out.println("this is one class"+no); two t=new two(); t.disp1(); } } class two { void disp1() { System.out.println("this is class two"); } } class three { int a=10,b=2; void end() { one o=new one(); o.disp(); System.out.println("this is third class"); System.out.println("the mod val is :"+a%b); } } class innerclass { public static void main(String ar[]) { three t=new three(); t.end(); } }
Java Class Library A list of the class packages that are part of the Java Class Library are: java.lang Classes that apply to the language itself which includes the Object class,the System class. It also contains the special classes for the primitive datatypes . (Integer,Byte,Float,Character) java.util Utility classes such as Date as well as simple collection classes such as Vector. java.io Input and Output classes for writing to and reading from streams and for handling files. java.applet Classes to implement the applets java.awt (Abstract Windowing Toolkit) - Classes to implement a Graphical User Interface, including classes for Window,Menu,Button,etc. This package also includes classes for processing images. java.net
Classes for networking support, including Socket and URL. ARRAYS * An array is an object that stores a list of items. * We can create a array through the new keyword Two methods can be used to create the array: i) Initialization of the array ii) Usage of the new keyword eg. int arr[ ]=new int[5]; char carr[ ]={'a','b','c'}; The length of the array can be identified by the variable length. To find the length of the variable: array name. length; one dimensional array: // One Dimensional Array import java.io.*; class array { public static void main(String ar[ ])throws IOException {
int a[]=new int[5]; int i,sum=0; DataInputStream d=new DataInputStream(System.in); for(i=0;i<5;i++) { a[i]=Integer.parseInt(d.readLine()); //a[i]=Integer.parseInt(ar[i]); } for(i=0;i<5;i++) { System.out.println("arr val " +a[i]); sum=sum+a[i]; } System.out.println("sum val is" +sum); } }
/* Two Dimensional Array Using Interger */ class Twodarray { public static void main(String args[]) { int arr[][]=new int[2][]; int i,j,r ; arr[0]=new int[3]; arr[1]=new int[5]; System.out.println("Length of arr = " +arr.length); System.out.println("Length of arr[0] = " +arr[0].length); System.out.println("Lenght of arr[1] = " +arr[1].length);
Strings
A combination of characters is a String. Strings are instances of the class String. Import java.lang.String.*; Methods(function) Length() Returns number of characters in a string. CharAt() Returns the character at a given location is a string Equals()/ equalsIgnoreCase() Check the equality of strings indexOf() Returns the index where the argument starts lastIndexOf() Returns the last index where the argument starts Substring() Returns a new string containing the specified character set concat() Joins two strings
replace() Returns a new string with the replacements made. toLowerCase()/ toUpperCase() Returns a new string with the case of all letters changed trim() Returns a new string with the whitespace characters removed from each end.
STRING PROGRAM: class Stringdemo { public static void main(String args[]) { String s1="computer"; String s2="india"; String s3="INDIA"; String s4=" welcome "; System.out.println(" Length of s1 : " + s1.length()); System.out.println(" Length of hello : " + "hello".length()); System.out.println(" s1.charAt(4) : " + s1.charAt(4)); System.out.println(" s2.equals(s3) : " + s2.equals(s3)); System.out.println("s2.equalsIgnoreCase(s3):"+s2.equalsIgnoreCase(s 3)); System.out.println(" s2.indexOf(i) : " + s2.indexOf("i")); System.out.println(" s2.lastIndexOf(i) : " + s2.lastIndexOf("i")); System.out.println(" s1.substring(3,6) : " + s1.substring(3,6));
System.out.println(" s1.concat(s2) : " + s1.concat(s2)); System.out.println(" s4.replace(j,h) : " + s2.replace('i','I')); System.out.println(" s2.toUpperCase() : " + s2.toUpperCase()); System.out.println(" s3.toLowerCase() : " + s3.toLowerCase()); System.out.println(" s4.trim() : " +s4+"csc"); System.out.println(" s4.trim() : " + "a"+s4.trim()+"csc"); } }
Inheritance
Inheritance is the process of deriving a new class from a base class/old class. The derived class has a larger set of properties than its base class. * The major advantage of inheritance is reusability of code. * Java supports single, multilevel, hierachical inheritance only. * Java supports multiple inheritances through the interface. * The extends keyword is used to inherit a class. 1.Single inheritance: AB A - Base class / super class B - Derived class / sub class
EXAMPLE 1: import java.io.*; import java.lang.String.*; class A { static String s,a,c; int j,k=0,m=1; void display()throws IOException { InputStreamReader o=new InputStreamReader(System.in); BufferedReader b=new BufferedReader(o); System.out.println(); System.out.println("Enter The First String:"); s=b.readLine(); System.out.println(); System.out.println("Enter The Single Character:"); a=b.readLine(); for(j=0;j<s.length();j++) { c=s.substring(j,m); m++; if(c.equals(a)) { k++; } } System.out.println(); System.out.println("No Of Occurence Of "+a+" is "+k); } }
class B extends A { static String s,p; int i; void rep()throws IOException { InputStreamReader o=new InputStreamReader(System.in); BufferedReader b=new BufferedReader(o); display(); System.out.println(); System.out.println("The Replace String Is: "+super.s.replace('a','i')); System.out.println(); System.out.println("Enter The Second String:"); this.s=b.readLine(); if((this.s).equals(super.s)) { System.out.println(); System.out.println("The Strings Are Equal"); } else { System.out.println(); System.out.println("The Strings Are Not Equal"); } if(this.s.toUpperCase()=="true") { System.out.println("Conversion Of String:"+this.s.toLowerCase()); } else { System.out.println("Conversion Of String:"+this.s.toUpperCase()); } } }
class inherit { public static void main(String args[])throws IOException { InputStreamReader o=new InputStreamReader(System.in); BufferedReader b=new BufferedReader(o); String l; B obj=new B(); obj.rep(); A obj1=new A(); System.out.println(); System.out.println("The Length Of First String:"+obj1.s.length()); System.out.println("The Length Of Second String:"+obj.s.length()); } } /* Single Inheritance */ class A { int a,b; void dis() { System.out.println("A class"+(a+b)); } } class B extends A { int m; void list() { dis(); System.out.println("use a and b"+(a+b+m)); }
} class in { public static void main(String ar[]) { B obj=new B( ); obj.a=10; obj.b=20; obj.m=30; obj.list(); } } 2.Multilevel Inheritance: A new class inherits from another derived class ABC A - Base class B - Intermediate class C - Sub class class x { int a=10; void disp() { System.out.println("this is class x"); System.out.println(" a :"+a); } }
class y extends x { int b=20; void disp1() { System.out.println("this is class y"); System.out.println(" a+b :"+(a+b)); } } class z extends y { int c=30; void disp2() { System.out.println("this is class z"); System.out.println(" a+b+c :"+(a+b+c)); } } class multilevel { public static void main(String ar[]) { z z1=new z(); z1.disp(); z1.disp1(); z1.disp2(); } } 3.hierarchical Inheritance: A
__________ B, C, D A One base class More than one derived class and single base class. import java.io.*; class first { int a,b; void input()throws IOException { DataInputStream d=new DataInputStream(System.in); System.out.println("enter a,b val"); a=Integer.parseInt(d.readLine()); b=Integer.parseInt(d.readLine()); } } class sec extends first { void dis() { System.out.println("the method for derived class"); System.out.println(" a%2 :"+(a%2)); System.out.println("a*b :"+(a*b)); } } class thi extends first { void disp() { System.out.println("the value of a+b : " +(a+b)); }
} class hiera { public static void main(String ar[])throws IOException { sec s=new sec(); s.input(); s.dis(); thi t=new thi(); t.input(); t.disp(); } }
SUPER:
super keyword refers to the base class variable or method.
Rules: ********
1. super keyword is used only within a subclass 2. super() must be the first statement executed inside a subclass constructor 3. The argument in the super () must match the argument in the constructor defined in the superclass.
Types of super:
1. super Variable eg: super.a 2. Super (argument-list) eg: super(a,b) 3. super.method eg: super.fun ( )
/* super variable */ class s { String x="java"; } class p extends s { String x="linux"; void dis() { System.out.println("this is base string : " + super.x); System.out.println(" this is derived : " +x); } } class super_var { public static void main(String ar[]) { p p1=new p(); p1.dis(); } } // super function name class f { void dis(String s) { System.out.println("this is f class string :"+s); }
} class g extends f { void dis(String s) { super.dis(s); System.out.println("this one is derived class string :"+s); } } class super_fun { public static void main(String ar[]) { g g1=new g(); g1.dis("hello"); } }
//super feature (constructor) class mano { int i; mano(int p) { this.i=p; } } class vino extends mano {
int j; vino(int p,int j) { super(p); this.j=j; } } class super_fea { public static void main(String s[]) { vino v=new vino(10,20); System.out.println("this is constructor val i :"+v.i); System.out.println("this is constructor val j :"+v.j); } }
/* class using method_overloading */ Method name are same but different argument. class ca { int a,in; float b; String nam; char ch; void me(int a,float b,String na) { this.a=a; this.nam=na;
this.b=b; } void me(int in,char n) { this.in=in; this.ch=n; } void show() { System.out.println("The val:"+a+ "\t" +nam); } void show1() { System.out.println("The m,ch is :"+in+ "\t" +ch); } } class meth_over { public static void main(String ar[]) { ca ss=new ca(); ss.me(100,12.12f,"ani"); ss.me(200,'a'); ss.show(); ss.show1(); } }
Overriding:
*Already defined method in a super class is redefined with all argument in its sub class, then the redefined method overrides the method in the superclass. This mean the sub class method us active and the super class method is hidden. *If we want to call the method in the super class. The syntax is : super.name of superclass method(); */ program : class A { int a=20; } class B extends A { int a=10; void dis() { System.out.println("val of fisrt class " +super.a); System.out.println("val of 2nd class "+a); } } class sup1 {
public static void main(String ar[]) { B b=new B(); b.dis(); } } method over loading: class Me { int i,j; Me(int m,int n) { i=m; j=n; } void show() { System.out.println("The i & j val:" +i+ "\t" +j); } } class Me1 extends Me { int s; Me1(int m,int n,int k) { super(m,n); s=k; } void show(String s1) // over loading
{ System.out.println("String is: " +s1); } void show() //over riding { super.show(); System.out.println("The k val: " +s); } } class over_rid { public static void main(String ar[]) { Me1 obj=new Me1(10,20,30); obj.show(); obj.show("METHOD OVERRIDING"); } }
Dynamic Method Dispatch(poly) We can access the base class object through the sub class instance. /* Dynamic dispatch method */ class A { void rose() { System.out.println("A rose method"); }
} class B extends A { void rose() { System.out.println("B rose method"); } } class C extends B { void rose() { System.out.println("C rose method"); } } class dyna { public static void main(String ar[]) { A obj=new A(); B obj1=new B(); C obj3=new C(); //obj.rose(); //obj1.rose(); //obj3.rose(); A r; //reference for A class r=obj; r.rose(); r=obj1;
The "final" modifier The word "final" is used to indicate that no further alterations can be made(same as constant type). final class Person final void showData() final int s=100; /* final */ class fin { final int a=10; final void show() { System.out.println("This is final method"); System.out.println("A:"+a); } }
class fin1 extends fin { void fun() { show(); System.out.println("B class"); System.out.println(+a); } void show() {} } class fina { public static void main(String ar[]) { fin1 ss=new fin1(); } }
/* Abstract abstract --> keyword Abstract class and its method have not having source code itself. Abstract class is always a base class and its method can be used different class in different usages. We shouldnt create object for abstract class.
Abstract methods are defined in another classes */ abstract class A { int x=100; abstract void show(); // we can't define in this class void jas() { System.out.println("This is Rose"); } } class abs extends A { void show() { System.out.println("Abstract method:"+(x/10)); } public static void main(String ar[]) { abs fn = new abs(); fn.jas(); fn.show(); // A a = new A(); //can't be instatiated A...is abstract A a = fn; // we can store other class reference to abstract class a.jas();
a.show(); } } Interfaces Java provides an alternate approach known as interface to support the concept of multiple inheritances. Interface is like that class concept. Interface: Interface is a collection of variables and methods. The variables which are declared in interface must have initial value. The method which are declared in the interface shouldnt have the source code. Class: Class consist of collection of variables and methods. The variables and methods are may or maynt have the source code. Implementing Interfaces Interfaces are used as super classes whose properties are inherited by classes. The keyword implements is used to inherit the interface. It is the responsibility of class that implements the interface, to define all the methods present in that interface. classes can implements more than one interface.
Syntax :
interface <name> { <final variables declaration> <methods declaration> } class <classname> implements <interface name>
Eg:
interface first { int x=90; void show(); } interface sec extends first { int y=10; void show(int x); } class inter implements sec { public void show() { System.out.println("first interface:"+x); }
public void show(int ar) { System.out.println("second interface:"+y+"\t"+ar); } public static void main(String sr[]) { sec s= new inter(); s.show(); s.show(200); } } interface first { int x=34; } interface sec { int y=500; void show1(); } class inter1 implements sec,first { public void show1() { System.out.println("second interface:"+y); } public static void main(String sr[]) { inter1 s = new inter1();
Packages Package is a collection of interfaces and class. Package contains a set of classes in order to ensure that class names are unique. The import keyword is used to access the classes in that package. Syntax:(class) Package pack-name; Steps to create a Package: 1. Create a Folder in the name of a Package.(poovi) 2. to create a programs(classes) 3. Change to that folder and create a java program.(relive the poovi folder) 4.Include the package < folder name> statement as the first line in that java program. Syntax:(main program) Import <package name>; package poovi;
c:\poovi
p1 package poovi; p2
c:\poovi\p1.java /* save: c:\poovi\pack\p1.java */ package poovi.pack; -->pack sub directory package poovi.pack; import java.io.*; public class p1 { int a,b; public void dis()throws IOException { DataInputStream d=new DataInputStream(System.in); a=Integer.parseInt(d.readLine()); b=Integer.parseInt(d.readLine()); if(a==b) { System.out.println(" a,b val's are equal"); } else { System.out.println("a , b val's are not equal"); } } } /* save: c:\poovi\pack\p1.java */
package poovi.pack; interface f1 { public int a=10; public void show(); } public class p2 implements f1 { public void show() { System.out.println("hello"); System.out.println("this is interface"+a); } } main program: import poovi.pack*; c:\ pack .java
import poovi.pack.*; import java.io.*; class pack { public static void main(String ar[])throws IOException { p1 p=new p1(); p .dis(); p2 k=new p2(); k.show(); } }
Exceptions In Exception is an abnormal condition which occurs during the execution of a program with the help of its well-defined exception handling mechanism.. Exceptions are erroneous events like division by zero, opening of a file which does not exists,etc. Java handles Exception using five keywords. try, catch ,finally, throws and throw The Object class has subclass called Throwable to handle Exceptions and errors. Object -> Throwable -> Error -> Exception -> Runtime Exception -> IOException Pre-Defined Exception ClassNotFoundException ArithmeticException ArrayIndexOutOfBoundsException NumberFormatException Default Exception handling
When a program throws an exception, it comes to a stop. This exception should be caught by an exception handler and dealt with immediately. In case of provision of an Exception handler, the handling is done by handler. Suppose there are no handlers, the Java Runtime System provides default handlers. This displays a string which describes the Exception and the Point. try and catch The code sequence, which is to be guarded, should be placed inside the try block. The catch clause should immediately follow the try block. The catch clause can have statements explaining the cause of the exception generated. Syntax try { <statements> }catch(Exception ) { <statements> } class excep { int i=10; void view() { try { System.out.println(i+10);
}catch(ArithmeticException e) { System.out.println("some error"); } } public static void main(String ar[]) { System.out.println("this is rose"); excep e=new excep(); e.view(); System.out.println("After Excep"); } }
throws Without using the try block we can handle the throws class. Only find out the errors, cant access the after exception statements.
Syntax <method> throws <Exception name> program: class throws { public static void main(Strings ar[])throws ArithmeticException
{ int num=0; System.out.println(num+num/0); //System.out.println(hai); } } finally When an exception is generated in a program, sometimes it may be necessary to perform certain activities before termination. In such cases, the try block apart from the catch clause, also has finally block within such activities can be performed. This block is executed after the execution of statements within the try/catch block. Syntax finally { <statements> }
program finally class finally1 { public static void main(String ar[]) { try { int a=Integer.parseInt(ar[0]); int b=Integer.parseInt(ar[1]); System.out.println("modulus"+a%b);
} catch(ArithmeticException e) { System.out.println("error in denominator"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("error in index value"); } catch(NumberFormatException n) { System.out.println("data type error"); } finally { System.out.println("finally block"); } } }
throw The throw statement is used to explicitly throw an exception. First a handle on an instance of Throwable must be got via a parameter into a catch clause or by creating one using the new operator. import java.io.*; class poo { public static void main(String ar[])throws IOException {
DataInputStream d=new DataInputStream(System.in); int a=Integer.parseInt(d.readLine()); System.out.println("this is a val: "+a); throw new NullPointerException("hello"); } }
User-Defined Exception Customized exceptions are necessary to handle abnormal condition of applications created by the user. The user-defined exception can be created by deriving a class from the Exception class. Syntax class <name> extends Exception
// MyExeption is a User-defined Exception import java.lang.Exception; class myex extends Exception { myex(String m) { super(m); } } class usrex
{ public static void main(String a[]) { int x=3,y=1000; try { double z=x/y; if(z<0.01) { throw new myex("number is too small"); } else { throw new myex("number is too high"); } } catch(myex e) { System.out.println("caught my exception"); System.out.println(e.getMessage()); } finally { System.out.println("welcome"); } } }
FILE 1File is a collection of data stored in a particular area on the disk. 2File is used to read and write operations on the file. 2A file program involves either or both of the following kinds of data communication. 1.Data transfer b/w the console unit and the program. 2.Data transfer b/w the program and a disk file.
I/p: Keyboardconsole Consolefile Fileclass O/p: Classfile Fileconsole Consoledisplay File is class of the java.io package that references an actual disk file. File obj=new File(path,file-name);
File Obj=new File(filename); Methods getName() Returns the name of the file getPath() Returns the directory, name of file getAbsolutePath() Returns the name of the parent directory getParent() Returns the directory only getModified() if it is modified or not isHidden() Returns if the file hidden or not canWrite() Returns if the file is writable or not canRead() Returns if the file is readable or not exist() Returns true if the file is exist or not false isFile() Returns if it is file isDirectory() Returns if it is directory length() Find the length of the string Example for above methods: import java.io.*; class fdetail { public static void main(String s[]) { //File ob=new File("c:/ani/abs.java"); File ob=new File(s[0]); if(ob.exists()) { System.out.println(ob.getName()); System.out.println(ob.getPath());
System.out.println(ob.getParent()); System.out.println(ob.getAbsolutePath()); System.out.println(ob.canRead()?"Readble":"not Readble"); System.out.println(ob.canWrite()?"Writable":"not Writable"); System.out.println(ob.isHidden()?"Hidden":"not Hidden"); System.out.println(ob.lastModified()); System.out.println(ob.isFile()); System.out.println(ob.isDirectory()); System.out.println(+f1.length()); } else System.out.println("File not Found"); } } } com: javac fdetail.java run: java fdetail anu.txt
/* mkdir() --> to Create a Directory */ import java.io.*; class mkd { public static void main(String s[]) { File ob=new File(s[0]); if(ob.mkdir()) System.out.println("created"); else System.out.println("Already exist"); }
Example : import java.io.*; class dirdemo { public static void main(String s1[]) { File ob=new File(s1[0]); String start=s1[1]; String end=s1[2]; if(ob.isDirectory()) { String s[] = ob.list(); for(int i=0;i<s.length;i++) if(s[i].endsWith(end)) if (s[i].startsWith(start)) System.out.println(s[i]+"\t"); } else System.out.println("Not a Directroy"); } }
com: javac dirdemo.java run: java dirdemo pack p java p1.java p2.java pack.java packdirectory pfile name represent javaextension Streams A Stream is a path of communication between the source and destination. Stream are divided into 4 abstract classes 1. Input stream 2. Output stream 3. Reader 4. Writer The I/o and o/p are designed byte stream Reader and Writer are designed for characters stream Byte stream classes and the character stream classes Form separate hierarchy Byte Stream: 1. The byte stream classes provide a rich environment for handling byte oriented I/O.
2. A byte stream can be used with any type of object including binary data. File InputStream Class helps in reading data from the actual disk file. FileInputStream o=new FileInputstream(string name); FileInputStream o=new FileInputstream(File-obj); Methods Int read() Returns and integer representation of the next available byte of I/p, -1 is return when the end of the file is 0ncountered. available()Returns the number of bytes that can be read from the file input stream. close()Closes the file input stream and releases any system resources associated with the stream. Skip(long value) skip from specified value import java.io.*; class Fdemo { public static void main(String ar[])throws Exception { int t,i; File ob=new File(ar[0]);
if(ob.exists()) { FileInputStream in=new FileInputStream(ob); t=in.available(); System.out.println("Available:"+ t); for(i=0;i<200;i++) System.out.print((char)in.read()); System.out.println("\nAvailable:"+ in.available()); in.skip(400); System.out.println("Available:"+ ( t=in.available()) ); while(in.read()!=-1) System.out.print((char)in.read()); in.close(); } else System.out.println("File not Found"); } } run: java fdemo fr.java FileOutputStream class helps to create a file and write data into it using the methods of the OutputStream class. FileOutputStream ob=new FileOutputStream(filename); Methods
write()
// FileOutputStream import java.io.*; class fwrite { public static void main(String s[])throws Exception { String st="This File Write Program"; int i,c; FileOutputStream out=new FileOutputStream(s[0]); for(i=65;i<91;i++) out.write(i); out.write('\n'); do { c=System.in.read(); out.write(c); }while(c!='#'); out.close(); out=new FileOutputStream(s[1]); byte b[]=st.getBytes(); out.write(b,0,9); out.write('\n'); out.write(b);
out.close(); } } Run: Java fwrite a1.txt a2.txt Hai # type a1.txt type a2.txt
Buffered Byte Stream: It is based on the byte oriented stream The buffered byte stream classes are buffered I/p and o/p stream. BufferedInputStream Buffered inputstream class allows you to wrap any inputstream into a buffered stream.this class implements the fileinputstream class. To read the data from file using the Bufferedrinputstream. BufferedOutputStream Buffered output stream is similar to any outputstream. Bufferedoutputstream is used to write the data to file.
The data are written into a internal buffer, otherwise the buffer reaches its capacity , the buffer output stream is closed or the buffer outputstream is explicitly flushed. Default buffer size : 512 bytes
Methods write() stream. flush() Writes the specified byte to the buffered output Flushes the buffered output stream.
// Bufferedinputstream & Bufferedoutputstream import java.io.*; class FileIOdemo { public static void main(String args[]) throws IOException { int ch,fsize; File f=new File(args[0]); //FileOutputStream f=new FileOutputStream(f,true) BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f,true)); System.out.println("Enter a text : "); do {
ch=System.in.read(); bos.write(ch); }while((char)ch != '*'); bos.flush(); bos.close(); BufferedInputStream FileInputStream(f)); fsize=bis.available(); System.out.println("\n Contents of file : " + f.getName() + "\n"); while( (ch = bis.read()) != -1 ) { System.out.print((char)ch); } bis.close(); } } Run: java fileiodemo kani.txt Hai eni * contents of file : kani.txt hai eni Filereader: The filereader class creates a reader that you can use to read the contents of a file. Filewriter:
bis=new
BufferedInputStream(new
/* FileReader & FileWriter */ import java.io.*; class fwr { public static void main(String ar[])throws IOException { int c; File f=new File(ar[0]); FileWriter fw=new FileWriter(f); System.out.println("enter the data"); do { c=System.in.read(); fw.write(c); } while(c!='$'); fw.flush(); FileReader fr=new FileReader(f); while( (c=fr.read())!=-1) { System.out.print( (char)c); } fr.close();
read only: import java.io.*; class fread { public static void main(String s[])throws Exception { int c; //File f=new File(fwr.java); //FileReader r=new FileReader(f); File f=new File(s[0]); FileReader re; if(f.exists()) { re = new FileReader(f); System.out.println(f.getName()); System.out.println(f.length()); while( (c=re.read())!=-1) System.out.print( (char)c); re.close(); } else System.out.println("File not Found"); }
target-start); s.getchars(1,2,a,5); import java.io.*; class fwrite1 { public static void main(String st[])throws Exception { int i; FileWriter wr=new FileWriter(st[0],true); String s = "Welcome this is File Writer Program"; char a[] = new char[50]; s.getChars(0,s.length(),a,0); for( i=0;i<a.length;i++) wr.write(a[i]); wr.close(); FileReader re=new FileReader(st[0]); while( (i=re.read())!=-1) System.out.print( (char)i); re.close(); } } run: java fwrite1 anu
welcome type anu welcom CHARARRAY WRITER & CHARARRAYREADER: CHARARRAY WRITER: Char array writer is an implementation of an o/p stream that uses on array as the destination. /* Chararrayreader & Chararraywriter */ import java.io.*; class chwrite { public static void main(String s[])throws IOException { String st="This is 65656 ?"; System.out.println(st.length()); char a[]=new char[40]; st.getChars(0,15,a,0); System.out.println(a); CharArrayWriter cw=new CharArrayWriter(); cw.write(a); System.out.println(cw); char a1[]=cw.toCharArray(); System.out.println(a1); for(int i=0;i<a1.length;i++) System.out.print( a1[i] );
} } run: java chwrite 15 this is 65656 ? this is 65656 ? this is 65656 ? this is 65656 ?
StreamTokenizer StreamTokenizer class helps in identifying the patterns in the current file. It is responsible for breaking up the input stream into Tokens(group of characters), which are delimited by a set of characters. They are ,:,*,#....etc., Methods nextToken() Returns the type of the next token. There are four token types: TT_WORD TT_NUMBER TT_EOL TT_EOF import java.io.*; The String field sval contains the that is found. word
The double field nval contains the value of the number. An End-Of-Line is found. An End-Of-File is reached.
class token { public static void main(String args[]) throws IOException { int token,wcount=0; FileReader fr=new FileReader(args[0]); StreamTokenizer st=new StreamTokenizer(fr); while( (token=st.nextToken())!= StreamTokenizer.TT_EOF ) { if(token == st.TT_WORD) { System.out.println(" Word found : " + st.sval); wcount++; } else if(token == st.TT_NUMBER) System.out.println(" Number found : " + st.nval); else System.out.println("Special Char:"+ (char) token); } System.out.println(" No. of words found : " + wcount); } } Run: java token anu.txt
Vector
A Vector is an array of Object references. Which consist of different type of value can be stored to avoid the wastage of memory spaces. It can The Vector class is defined in java.util Package. Methods addElement()Adds the Object reference at the end of list elementAt() Returns the Object reference for the specified index. we can extract an object from a specific location in that vector, by using the given options. firstElement() lastElement() size() returns the number of elements currently in the vector. capacity() returns the capacity of the vector
import java.util.*; class vect { public static void main(String a[]) { int i; Vector v=new Vector(); System.out.println(v.size()); System.out.println(v.capacity());
v.addElement(new Double(345.5683)); v.addElement(new String("WELCOME")); System.out.println("Size::"+v.size()); System.out.println("Capacity::"+v.capacity()); v.addElement(new Character('G')); System.out.println("----------------------------------------------------"); System.out.println("First Element:"+v.firstElement()); System.out.println("Last Element:"+v.lastElement()); System.out.println("----------------------------------------------------"); for(i=0;i<v.size();i++) System.out.println("\n"+ v.elementAt(i)); } } Run: Java vect Object Serialization Serialization is the process of writing the state of an object to a byte stream. Serialization is also needed to implement Remote Method Invocation(RMI).
Two Streams in java.io -ObjectInputStream ObjectOutputStream are used to read and write objects.
and
The object are written to the stream with the writeObject method of ObjectOutputStream. The readObject method of ObjectInputStream is used to read objects from file. An object is serializable only if it's class implements the Serializable interface. The Serializable is an empty interface. That is, it doesn't contain any method declarations; it's purpose is simply to identify classes whose objects are serializable. public interface Serializable { } import java.io.*; class serial implements Serializable { private String ename; private int empno; private String job; private float salary; public void getData() throws Exception { BufferedReader br=new InputStreamReader(System.in));
BufferedReader(new
System.out.print("Enter name : "); ename=br.readLine(); System.out.print("Enter Empno : "); empno=Integer.parseInt(br.readLine()); System.out.print("Enter job : "); job=br.readLine(); System.out.print("Enter salary : "); salary=Float.parseFloat(br.readLine()); } public void showData() { System.out.println("Name : " + ename); System.out.println("Empno : " + empno); System.out.println("Job : " + job); System.out.println("Salary : " + salary); } public static void main(String args[]) throws Exception { FileOutputStream fos=new FileOutputStream(args[0]); ObjectOutputStream oos=new ObjectOutputStream(fos); serial sd=new serial(); sd.getData(); oos.writeObject(sd); oos.close();
FileInputStream fis=new FileInputStream(args[0]); ObjectInputStream ois=new ObjectInputStream(fis); serial sdfile; // Casting is the process of converting one datatype to another. sdfile = (serial) ois.readObject(); sdfile.showData(); ois.close(); } } Run: Java serial new