You are on page 1of 38

Introduction to Java

Introduction:
Java is an Objected Oriented Programming. As seen in C++ java has all the
compositions of C++ with some additional advances changes. Java was developed for internet
programming through html by Sun Microsystems CEO James Gosling.

Characteristics of Java:
The OOP concept in java is same as C++ with changes in technique and style.
It has object and class
It has Data Abstraction and Encapsulation
It has Inheritance and Polymorphism
It has Dynamic Binding (constructor)
It has Message Communication from one object to other and through applet application
in html.

Java Features:
Platform independent and portable because source code is converted to byte code.
Robust and secure because manages memory well.
Distributed data can be share online through internet and intranet.
Multithread and interactive; can run more than one program or block at a time.
Java Virtual Machine (JVM) help to manage the memory resource effectively and thus
reducing the startup time of loading the class and sharing data among classes.

Body of Java:
class room //Sub class and Base class
{ float area (float l, float b) //Method or function default is friend
{return l*b;}
double area (double l, double b)
{return l*b;}
}
class display // Main class
{public static void main (String[] args)
{
System.out.println("Friends");
}
}
Java has two files source file which has the code, and class file. The source file need hot
have the same name as class file when there is no public class in the source code file. When
complied java creates separate class file for each class from the source code file, the class be
super class, sub class, or main class. However if the source code file has public class the source
code file should be saved in the name of public class. It the sub class and main class are public
then the source code file should be saved in the name main class. Source file and class files are
case sensitive

Browsers: Hot Java, Netscape Navigator, and Internet Explorer.

1
Introduction to Java
Java and C++
Java does not support operator overloading
Java does not support template class.
Java does not support multiple inheritances; it is achieved through interface.
Java does not support global variable.
Java has no pointers.
Java does not support independent function all function must be inside the class. In java
functions are referred as Method.
The main program is also inside a separate class. It is called main class.
The main class must have same name as the file name with .java as file extension.
Java can be developed as stand alone product but it is extensively and exclusively used to
develop internet based software applications.
Java does not use destructor instead finalize( ) function is called to destroy object.

Packages to develop java product:


Package is collection class and methods. The following packages help to develop java
applications.
Language Support Product: to support basic java features.
Utilities Package: to support data and time functions.
Input/Output Package: to support I/O activities.
Network Package: to support online activity through internet.
AWT Package: to support platform independent graphical user interface.
Applet Package: to support java applets.

Data Types:
Character, Integer, float, and double.
Boolean True of false default false.
Array, Class, Interface.

Floating point default is double precision to convert single precision use f or F as suffix to
the float point value. When double variable is assigned to float variable, the double variable
value must be suffixed with f or F to store in float variable as single precision. It can also be
converted using type cast (float)x;

Array:
One dimensional Array Declaration
Method 1:
Step1: int x [ ]; This is an array set to null
Step2: x = new int[10]; This an array allocated with 10 elements.
Method 2:
int x = new int[10]; Array of size 10.

int x[3]={11,2,43}; is invalid;


int y[ ] ={3,5,12}; is valid
Rules of Array: It checks for boundary unlike C or C++

2
Introduction to Java

Array size can be found using array_variable.length function.


One array can be assigned to another array of same or higher order a=b;

Two dimensional Array Declaration


Method 1:
Step1: int y [ ][ ]; This is an array set to null
Step2: y = new int[3][3]; This an array allocated with 9 elements.

Method 2:
int y[ ][ ] = new int[3][3]; 3x3 Array.

The two dimensional array in Java is different from other programming tool. Java two
one dimensional arrays are arranged in that order. The advantage of have two one dimensional
arrays to form two dimensional array is shown in the following example.

int z[ ] [ ] = new int[4] [ ];


z[0] = new int[1]; First row has only one column
z[1] = new int[2]; Second row has two column
z[2] = new int[3]; Third row has three column
z[3] = new int[4]; Fourth row has four column.
Therefore total number of elements are 10
Here array z is arranged as follows which is known as uneven or irregular array. This is
rarely used in the programming technique but situation may arise to use such type of declaration.
0
00
000
0000

Scope of Variables:
Instance variable created for each instance of object. Each object has separate memory
address to store the data.
Class variable are global to all the objects created from that class. It has only one memory
location, which is for class alone.
Local variable within the braces in the main and in methods.

Constant:
A symbolic constant value is defined using the keyword final. It cannot be defined inside
the method. It can be used as data member in the class.
final int x=100;

Type casting:
This method is adopted only when to assign higher order variable to lower order variable.
Casting higher order data to lower order data may result in loss of data.
int x=10; float y;
x = (int)y;

3
Introduction to Java
Automatic conversion is possible when the lower order variable is assigned to higher order
variable in such case data is not lost and type casting is not required.
y = x;

Java Operators:
1. Arithmetic operators +, -,*,/, and % - % can be used for real number also.
2. Relational operators <, >, <=, >=, = =, and !=.
3. Logical operators &&, ||, and !
4. Assignment Operators. =
5. Shorthand operator x += 1 is same x=x+1
6. Increment and Decrement operator ++ and
7. Conditional Operator: exp1?exp2:exp3;
8. Bitwise operator: to manipulate data at bit level. &, |, ^ ~(once complement), <<,>>,
>>>(right shift with zero fill)
9. Instanceof operator To find the instance of an object.
A a = new A( );
if (a instanceof student) statement
10. Dot operator to access data members in the class.

Initialization:
Float must be initialized with suffix f or F to avoid compiler error.
Ex: float x =23.45 will be error float x=23.45F is right way to initialize.

Arithmetic expressions
Evaluation of Expressions
Precedence of Operators

Control Structures:
If, if else, else if.
Switch
for and while

Note: unreachable error message can be over come using if control structure.

Jumping Loop:
break, continue, return
In programming languages like C, and C++ jumping in and out or loop is achieved
through break and continue statements. But these jump statements are not specific and it works
only for the block of that control structure. In other word a break or continue cannot be
redirected to other inner block or outer block. This may be overcome through goto statement.
Whereas in Java break or continue can be specifically redirected. Since break and
continue statements can be labeled. Which work similar to goto statement. Java does not support
goto statement. Break or continue statement can be with or without label. If it is without label
statement is applied for that block or else it is redirected to label.

4
Introduction to Java
Class and Objects:
All the algorithm or program must be inside a class as method or data.
Even main must be inside a class which is called main class.
Class defined as public should be saved in that file name.
Class not defined as public. The file may be saved as main class name or first sub class
name. It is always preferred to save as main class name.
All other classes are called sub class.
Methods are defined only inside the class.
Method without argument must be empty not even void.
Method cannot have default argument value.
Method can have final argument with out assigning value to the argument.
Constructor has same name, no return type, and declared any where in the class.
Object can be created only by constructor when constructor is defined.
Method finalize( ) work just like destructor but it should he explicitly created in the class
as protected member and called through object like regular method. This is seldom used
because java takes care of memory management of objects.
Static data members use class itself as instance; the static members are referred directly
through classname.member.
All members and its class are friend by default. The friend members and class can be
used only within that package. It is inherited and accessed outside the class.
Public classes and members can be accessed from any package. It is inherited and
accessed outside the class.
Protected members can be accessed by class and derived of same package and derived of
other packages but not by class of other packages. It can be accessed outside the class
and it is inherited.
Private protected is visible only in the derived of the packages.
Private data member can be accessed only by its class within the class and it cannot be
inherited. Where private method can be accessed outside the class and it is cannot be
inherited.
Each variable must have its own access modifier, that access modifier cannot be grouped
to variables like in c++.
The keyword final can be used to make the final data, final method, and final class. The
final data work just like declaring a variable as constant. Whereas final method will not
allow the derived class to override the base class method, similarly the final class will not
allow to inherit further. They are independent.
The opposite to final is abstract this make the derived class and overriding a must.
The class must also be defined as abstract to define abstract method
The base class must have only the body (declaration style) of the method with abstract
keyword.
Abstract class will not allow to create object, object members should be referred only
through derived object class.

5
Introduction to Java
Program 8.18 to understand visibility control of members
class visibility
{ private int pvt=10;
//protected private int pvtprt=20;
int frd; //default is friend
protected int prt;
public int pub;

void displaypvt()
{System.out.println("The private value is :"+pvt);
}
void display(String t, int a)
{System.out.println("The "+t+ " value is :"+a);
}

class visibilitycontrol
{public static void main(String...args)
{int x;
visibility v = new visibility();
v.displaypvt();
x=v.frd=20; //chain assingment
v.display("friend",x);
x=v.prt=30; //chain assingment
v.display("protected", x);
x=v.pub=40; //chain assingment
v.display("public", x);
}
}

Program 8.1 and 8.2 Understanding class, objects, and constructor


class rectangle
{ private //: not required in java it makes only next statement as part of access modifier
int x, y;
private
rectangle() //default constructor
{ System.out.println("friends"); }
rectangle(int a, int b)
{x=a;y=b; }
int area() //void not allowed like in C++
{ rectangle a = new rectangle(); //private constructor invoked
return x*y;
}
}

6
Introduction to Java
class RectArea //main class
{
public static void main(String args[])
{ int area;
System.out.println("welcome");
//rectangle a = new rectangle(); //Invokes default contructor
rectangle b = new rectangle(5,5); //Invokes constructor with two argument
area=b.area();
System.out.println("Area is "+area);
//a=b;
//area=a.area();
//System.out.println("Area is "+area);

}
}

Program 8.8 Overloading Methods and constructors


class rectangle
{ private //: not required in java it makes only next statement as part of access modifier
int x, y;
rectangle() //default constructor
{ System.out.println("friends"); }
rectangle(int a, int b) //constructor with two argument
{x=a;y=b;
}
int area() //
{ return x*y; }
int area(int l, int b)//Method overloading
{return l*b;
}
}
public class Overload //main class
{
public static void main(String args[])
{ int area;
System.out.println("welcome");
rectangle a = new rectangle(); //Invokes default contructor
rectangle b = new rectangle(5,5); //Invokes constructor with two argument
area=b.area();
System.out.println("Area is "+area);
area=a.area(11,12);
System.out.println("Area is "+area);

}
}

7
Introduction to Java
Program 8.9 Understanding static members
public class staticmembers
{ static int sa;
int a;
staticmembers (){}

void addn() //Do not use void as argument in method


{ ++sa; ++a;
System.out.println("Static value in non static method= "+sa);
System.out.println("Non static value = "+a);
}
static void adds()
{ ++sa;
System.out.println("Static method = "+sa);
//System.out.println("Sum of Non static = "+ sa); cannot read non static data in
static method
}
}
class total
{
public static void main (String...args)
{
staticmembers t=new staticmembers();
t.addn();
t.adds();
staticmembers.adds();
staticmembers s=new staticmembers();
s.addn();
staticmembers.adds();
}
}

Program 8.10 Understanding nesting of methods


class nesting
{ private int pvt=10;
private void displaypvt()
{System.out.println("The private value is :"+pvt); }
void display()
{displaypvt(); }
}
public class nestingmethods
{public static void main(String...args)
{nesting n = new nesting ();
n.display();
}
}

8
Introduction to Java

Inheritance:
Base is inherited by using key word extends
The inherited base class is not restricted as private, protected, or public as in C++
All members and its class are friend by default. The friend members and class can be
used only within that package. It is inherited and accessed outside the class.
Public classes and members can be accessed from any package. It is inherited and
accessed outside the class.
Protected members can be accessed by class and derived of same package and derived of
other packages but not by class of other packages. It can be accessed outside the class
and it is inherited.
Private protected is visible only in the derived of all the packages.
Private data member can be accessed only by its class within the class and it cannot be
inherited. Whereas private method can be accessed outside the class and it is cannot be
inherited.
Constructor is not inherited.
The base class is called super class in inheritance.
The constructor value to base class is passed through the derived class by calling the
method super in the derived class or sub class constructor.
Method super can be used only in sub class that is derived class.
Method super must be the first statement in the sub class.
Method super must have the same argument as in the base class.
Even when there is more than one constructor to a base class only one constructor of the
derived can be initiated through the method super in the derived class constructor.
Only Multilevel and hierarchical inheritance can be performed using keyword extends.
Multiple inheritances is developed using interface.

Program 8.11 Inheritance & constructor and super method to pass value to base class
class OneD
{double l;
OneD(int a)
{l=a; }
double length()
{return l; }
}
class TwoD extends OneD
{double b;
TwoD(int x, int y)
{ super(x);
l=x; b=y;
}
double area()
{return (l*b); }
}

9
Introduction to Java
class ThreeD extends TwoD
{double h;
ThreeD(int x, int y, int z)
{ super(x,y);
l=x; b=y;h=z;
}
double volume()
{return (l*b*h); }
}

public class inheritance // main class


{
public static void main(String args[])
{ OneD OD = new OneD(5);
System.out.println("The length of the box is " +OD.length());

TwoD TD = new TwoD(5,5);


System.out.println("The Area of the box is " +TD.area());

ThreeD ED = new ThreeD(5,5,5);


System.out.println("The Volume of the box is " +ED.volume());
}
}

Program 8.12 and 8.13 overriding and final variable, method, class
class base
{ void display(int a)
{System.out.println("Base or super class value is "+a);
}
}

class derivedA extends base


{ void display(float a) //does not override base class method
{System.out.println("Derived A or sub class float value is "+a);
}

final void display(int a) //override base class method


{System.out.println("Derived A or sub class value is "+a);
}
}

final class derivedB extends derivedA


{ void display(float a) //does not override base class method
{System.out.println("Derived B or sub class float value is "+a);
}

10
Introduction to Java
//The below method is not possible because it was made final in the base class
//void display(int a)
//{System.out.println("Derived B or sub class value is "+a);
//}
}

public class override


{ //final static int x=10;
public static void main(String...str)
{final int x=10;
base b = new base();
b.display(x);
derivedA da = new derivedA();
da.display(20.0f);
da.display(30);
derivedB db = new derivedB();
db.display(20.0f);
db.display(30);

}
}

Program 8.16 Abstract method and class


abstract class base
{ void display(int a)
{System.out.println("Base or super non abstract method value is "+a);
}
abstract void displayabs(int b);
}

class derivedA extends base


{ final void displayabs(int a) //must override base class method because it was abstract
{System.out.println("Derived A or sub class value is "+a);
}
}

public class abstractmethod


{ public static void main(String...str)
{final int x=10;
derivedA da = new derivedA();
da.display(10);
da.displayabs(20);

}
}

11
Introduction to Java

Program 8.17 Method with variable argument-It must be last argument in the method
class vararg
{void display(Object...args)
{for(Object O:args)
{System.out.println("The object value is :"+O);
}
}

void display(int a, String...args)


{for(String s:args)
{System.out.println("The string value is :"+s);
}
System.out.println("The value is :"+a);
}

void display(int a, int...args)


{for(int s:args)
{System.out.println("The integer value is :"+s);
}
System.out.println("The value is :"+a);
}

/*
void display(int...args)
{for(int s:args) //for(Object s:args) will also work
{System.out.println("The integer value is :"+s);
}

} */
}

public class vararguments


{ static int x[]={2,4,6,8};
public static void main(String...args)
{vararg v = new vararg();
v.display("apple", 1, 11.23,33.53f, 'z');
v.display(1, "apple", "is", "fruit");
v.display(1,2,3,4,5,6); //executes display(int a, int..arg) will not invoke object var arg

for(Object s:x) //for(Object s:args) will also work


{System.out.println("The integer value is :"+s);
}
}
}

12
Introduction to Java
9.5 Strings
It has two class String class and StringBuffer class. The capacity of String class is same
as the length of the string value. The capacity of StringBuffer class is length of string value and
16 additional bytes which is default size of StringBuffer.

Program 9.5 Method to Handle Strings and StringBuffer


public class stringmethod
{ static void strings() //space is also part of string
{ String s1 = new String (" APPLE COMPUTERS ");
String s2 = new String (" apple computers ");
System.out.println("S1 Length = " + s1.length());
System.out.println("Lowercase = " + s1.toLowerCase());
System.out.println("Uppercase = "+s2.toUpperCase());
System.out.println("Trim = " +s1.trim());
System.out.println("Replace = "+s1.replace('P','B'));
System.out.println("Equals = "+s1.equals(s2)); //true or false
System.out.println("Ignore Case = "+s1.equalsIgnoreCase(s2));
System.out.println("Char At 6 = "+s1.charAt(6)); //Read Character at 6th position
System.out.println("SubString1 = "+s1.substring(7)); //Read all from 7th character
System.out.println("SubString2 = "+s1.substring(0,6)); //Read 0 to 6th character
System.out.println("Compare To = "+s1.compareTo(s2));//Compare return integer
System.out.println("Index 1 = "+s1.indexOf('P'));//First occurrence of P
System.out.println("Index 2 = "+s1.indexOf('P',5));//First occurrence of P after
5th character
System.out.println("Concat = "+s1.concat(s2)); //Add two strings
float x=1234.3445f; String s;
s= String.valueOf(x); //Converts float to string.
System.out.println("Float as String = "+s.substring(0,7));
}
static void stringbuffer()
{ StringBuffer strb = new StringBuffer("Ele "); //Default size 16
//StringBuffer strbf="null"; Buffer must be created with memory allocation
System.out.println("String Buffer Class");
System.out.println("Length "+ strb.length());
System.out.println("Capacity "+ strb.capacity()); //Size of string buffer
System.out.println("Append "+ strb.append("Comm")); //Add to string
System.out.println("append "+ strb.append(" Engg"));
strb.setCharAt(0,'S'); //Replace character S at 0th position.
System.out.println("Set Char At 0 " +strb);
System.out.println("Char At 2 " + strb.charAt(2));//Find character at 2nd position
System.out.println("Insert 3 c " + strb.insert(3,'c')); //Insert at 3rd position
System.out.println("Insert 0, BE " +strb.insert(0,"BE "));//Insert at the beginning
System.out.println("Reverse String "+ strb.reverse()); //Reverse the string
strb.setLength(5); //Set or change the length
System.out.println("Set Length "+strb);
}

13
Introduction to Java

public static void main(String args[])


{strings();
System.out.println("--------------------------");
stringbuffer();

String s1="Einstein ";


String s2= new String ("College");
System.out.println(s1 + " " + s2 + 34);
s1 = s1 + s2 + " Of Engineering " + 1;
System.out.println(s1);

}
}

Program 9.6 Understanding vector class


It can store any data type of any size.
It is easy to delete or add objects to the class
Unlike array size varies to the number element size is dynamic

import java.util.*;

public class vectorclass


{public static void main(String args[])
{ Vector list = new Vector();
String str[]={"Einstein", "Raman", "Newton"};

for(String s:str)
{list.addElement(s); }

int sa = list.size();
String strc[]= new String[sa];
list.copyInto(strc);//All elements in the list should be string values

for(String sc:strc)
{System.out.println(sc); }

list.insertElementAt("Babbage",2); list.insertElementAt(627012,2);

int i[]={11,22,33};
for(Object o:i)
list.addElement(o);

list.addElement(100); list.addElement(11.34);
list.addElement(22.56f); list.addElement('a'); list.addElement("All");

14
Introduction to Java

list.removeElement(100); //data type should match


list.removeElementAt(1); //removes the 2nd element Raman
//list.removeAllElements();

int size = list.size();


Object stro[]= new Object[size];
list.copyInto(stro);//Values in the list can be any type

for(Object so:stro)
{System.out.println(so); }

for(int c=0; c<size; c++)


{System.out.println("The Element is " + list.elementAt(c)); }
}
}

Interface:
Multiple inheritances is developed using key word interface.
Interface variables (data member) are final and static by default. Only these variables can
be declared.
Variables must be initialized within interface.
Only body of methods is defined in the interface.
The interface is included in the class using the keyword implements.
All the methods of the interface must be defined in the class when implementing
interface. Something similar to abstract method, when the abstract class extends with
abstract method the abstract method must be override.
More than one interface can be included to a class. Thus multiple inheritances are
achieved.
Then the class must define all or required method inside that class. If the class use the
same name as method in the interface the interface method is implemented, or if the name
is different from the interface included then it method of that class alone not a method
from interface.
Interface cannot have private or protected members.
The members must be public when implementing the interface in a class.
Object can be created from interface just like from class, but class object must be
assigned to the interface object before calling the member from interface object.
Class can be created by extending the base and also including the interface this is similar
to hybrid inheritance in C++.

10.2 Understanding Simple Interface


interface area
{float r=3.14f;
//int z; it is not possible in interface must be initialized
float square(float x, float y);
float circle(float x);

15
Introduction to Java
}

class TwoD implements area


{float s,c,l,b,r; //r will have higher precedence

public float square(float x, float y)


{l=x;b=y;
return(s=x*y); }
public float circle(float x)
{ //r = 2*r; illeagal because r is final by default in interface
r=area.r; //variable r in class is assigned from interface variable
return(c=r*x*x); //r read from class variable
}
void display()
{System.out.println("Square "+s);
System.out.println("Circle "+c);
}
}
class simpleinterface
{public static void main(String...str)
{TwoD TD = new TwoD();
TD.square(10.0f, 20.0f);
System.out.println("Length "+TD.l+ " Breadth "+ TD.b);
TD.circle(10f);
TD.display();
}
}

10.2 Extending Interface


interface length
{float r=3.14f;
//int z; it is not possible in interface must be initialized
float ruler(float x);
}
interface area extends length
{ float r=6.141f; //override interface length r
float square(float x);
float ruler(float x);//will have no impact
}

class base implements area


{ public float ruler(float x)
{return x; }
public float square(float x)
{ return 2*r*x; }
}

16
Introduction to Java
class extendinterface
{public static void main(String...str)
{base b = new base();
float f;
f=b.square(10.0f);
System.out.println("Square "+f);
f=b.ruler(20f);
System.out.println("Ruler "+f);
}
}

Multiple inheritances through interface


interface area
{float pi=3.14f;
float square(float x, float y);
float circle(float x);
}

interface volume //extends area


{//float pi=3.14f; will cause ambiguity when implementing
float cube();
float square(float x, float y); //only one method will be implemented
float cylinder(float h);
float circle(float x, float y); //overload method can be implemented
}
class TwoD implements volume,area //Multiple inheritance
{float s,c,l,b,cu,cy,r, cya;
public float square(float x, float y)
{ l=x;b=y;
return(s=x*y);
}
public float circle(float x)
{ return(c=pi*x*x); }

public float circle(float x, float y)


{ return(cya=2*pi*x*y); }

public float cube()


{return (cu=l*l*b); }

public float cylinder(float h)


{return (cy=pi*r*r*h); }

void display()
{System.out.println("Square "+s);
System.out.println("Circle "+c);

17
Introduction to Java
System.out.println("Cube "+cu);
System.out.println("Cylinder "+cy);
System.out.println("Surface area Cylinder "+cya);
}
}
class multipleinheritance
{public static void main(String...str)
{TwoD TD = new TwoD();
TD.square(10.0f, 20.0f);
TD.circle(10f);
TD.circle(10f,29.5f);
TD.cube();
TD.cylinder(10.0f);
TD.display();
}
}

10.5 Hybrid extending a class and implementing interface


interface area
{float pi=3.14f;
float square(float x, float y);
float circle(float x);
}

class volume
{float cube(float x)
{return(x*x*x);
};
}

class mix extends volume implements area


{float s,c,l,b,cy;

float cylinder(float r, float h)


{return (cy=pi*r*r*h);
}

public float square(float x, float y)


{ return(s=x*y);
}
public float circle(float x)
{return(c=pi*x*x);
}

void display()
{System.out.println("Square "+s);

18
Introduction to Java
System.out.println("Circle "+c);
System.out.println("Cylinder "+cy);
}

}
class hybridinheritance
{public static void main(String...str)
{mix hy = new mix();
float c;
hy.square(10.0f, 20.0f);
hy.circle(10f);
c=hy.cube(5f);
hy.cylinder(10f,10f);
System.out.println("Cube "+c);
hy.display();
}
}

Package:
Package is a collection of class. Ex: java.lang.Math java is package which is inside
another package called lang which has class called Math. Each package will have its own
classes. Through those classes methods are accessed, just like regular class as seen
earlier. Example; Math.sqrt(x); Math.sin(x), etc.
Package works like a folder storing different files and sub folders. Similarly a package
can have class or sub package which may its own class.
The keyword package package_name should be used before beginning the class. This
will create the package; if the package already exists it will store the class in that
package.
Each class should be stored as separate file with package name at the beginning
(test.java).
At least one class should be public class; the file should be saved in the name of public
class. Package can be hidden by making it as default class, default class can be accessed
only by the members of same package.
Package can have base class and derived file as single file, but only one class must be
public class preferably derived class so that base can be accessed through derived class.
A derived class can be created in a separate file by including the base class package at
top.
Only public method can be accessed from a class object when placed in a package. No
other methods such as protected or default can be accessed through object when placed in
package.

Scope and Visibility of Package and its class:


Private member can be accessed only within that class and not inherited.
Public member can accessed from any class and any package and inherited.
Default member can be accessed from any class from same package and inherited.

19
Introduction to Java

Protected member can be accessed from any class from the same package and from
derived class of different package; but not from separate class of different package.
Private protected is only visible in the derived class of any package.

This class saved as pkg1classA.class in package pkg1:


package pkg1;
public class pkg1classA
{ int def =100; private int pvt =200;
protected int prt=300; public int pub=400;
public void displayA()
{System.out.println("Default "+def); System.out.println("Private "+pvt);
System.out.println("Protected "+prt); System.out.println("Public "+pub);
}
}

This derived class saved as pkg1extendsA.class in package pkg1:


Except private member all other members can be accessed using inheritance if both classes
reside in same package.

package pkg1;
public class pkg1extendsA extends pkg1classA
{ public void displayExtendA()
{System.out.println("Default "+def);
//System.out.println("Private "+pvt); Cannot access private outside its class
System.out.println("Protected "+prt); //private protected also visible because inherited
System.out.println("Public "+pub);
}
}

This class saved as pkg1classB.class in package pkg1:


Except private and private protected member all other members can be accessed using object
creation if both classes reside in same package.

package pkg1;
public class pkg1classB
{ pkg1classA a = new pkg1classA();
public void displaypkg1B()
{System.out.println("Default "+a.def);
//System.out.println("Private "+a.pvt); Cannot access private outside its class
System.out.println("Protected "+a.prt); //private protected not visible because cannot
System.out.println("Public "+a.pub);
}
}

This class saved as pkg2classB.class in package pkg2:


Only public members can be accessed from other package using object creation

20
Introduction to Java

package pkg2;
public class pkg2classB
{ pkg1.pkg1classA a = new pkg1.pkg1classA();
public void displaypkg2B()
{//System.out.println("Default "+a.def); Cannot access default outside its package
//System.out.println("Private "+a.pvt); Cannot access private outside its class
//System.out.println("Protected "+a.prt); Cannot access default outside its package
System.out.println("Public "+a.pub);
}
}

This class saved as pkg2extendsA.class in package pkg2:


Private Protected, Protected and public members can be accessed from other package using
inheritance

package pkg2;
public class pkg2extendsA extends pkg1.pkg1classA
{ public void displayExtendApkg2()
{//System.out.println("Default "+def); cannot access from another package
//System.out.println("Private "+pvt); Cannot access private outside its class
System.out.println("Protected "+prt); //private protected also visible because inherited
System.out.println("Public "+pub);
}
}

11.7 Using Packages:


import pkg1.*;
import pkg2.*;
class pkg1pkg2
{ public static void main(String...s)
{pkg1.pkg1classA pkg1A = new pkg1.pkg1classA();
pkg1A.displayA();

pkg1.pkg1extendsA pkg1EA = new pkg1.pkg1extendsA();


pkg1EA.displayExtendA();

pkg1.pkg1classB pkg1B = new pkg1.pkg1classB();


pkg1B.displaypkg1B();

pkg2.pkg2extendsA pkg2EA = new pkg2.pkg2extendsA();


pkg2EA.displayExtendApkg2();

pkg2.pkg2classB pkg2B = new pkg2.pkg2classB();


pkg2B.displaypkg2B();
}

21
Introduction to Java
}

Multithreading:
Operating systems like windows XP, UNIX, Linux, Macintosh, etc can execute or run
more than one program or application at a time this is called Multitasking or Multithreading in
Java. A single processor shares the processing time; which is not possible to visualize during
execution of these application. Thread is a small program.

Method I:
1. Create a class by extending the built-in class Thread
2. Create a method run( ).
3. Create object from Mythread class and call the start( ) method.

Method II:
1. Create a class by implementing the built-in interface Runnable.
2. Create a method run( ).
3. Create object from the above class
4. Create object from the Thread class passing object as argument and call the start( ) method.

Points to be remembered when implementing Multithreading:


1. The method run should be created to implement multithreading.
2. The method start will invoke the code written inside the run method.
3. To run more than one program the step 1 and 2 should be created again.
4. A running program can be stopped with stop method.
5. A running program may be suspended or blocked with sleep, suspended, or wait method.
6. Method yield will give way to execute another program.
7. Method sleep should be placed inside the try block followed by the catch block, because it
raises an exception after sleep period is completed.
8. Exceptions in thread are Exception, ThreadDeath, InterruptedException, and
IllegalArgumentException.
9. Before starting more than one program priority can be given or set to each program in
method setPriority(1 to 10). One (MIN_PRIORITY) being the lowest, five
(NORM_PRIORITY) is default, and 10 (MAX_PRIORITY) being highest. The priority can
be set by integer values or using those three terms.
10. The priority set to a thread can be found from the method getPriority( ).
11. When same thread is called at two different points a deadlock may occur. The deadlock can
be overcome by creating a method with keyword synchronized.

12.6 Thread from extending Thread class:


class ThreadA extends Thread
{public void run()
{for (int i=0; i<10; ++i)
{if (i==1)
yield();

22
Introduction to Java
System.out.println("Thread A " +i);
}
System.out.println("Exit Thread A ");
}
}
class ThreadB extends Thread
{public void run()
{ for (int i=0; i<10; ++i)
{System.out.println("Thread B " +i);
if (i==3)
stop();
}
System.out.println("Exit Thread B ");
}
}
class ThreadC extends Thread
{public synchronized void run()
{for (int i=0; i<10; ++i)
{System.out.println("Thread C " +i);
if (i==6)
try{sleep(1000);}
catch(Exception e)
{System.out.println("Slept");}
}
System.out.println("Exit Thread C ");
}
}
class example2
{ public static void main(String args[])
{ThreadA A = new ThreadA();
ThreadB B = new ThreadB();
ThreadC C = new ThreadC();

System.out.println("Start Thread A"); A.start();


System.out.println("Start Thread B"); B.start();
System.out.println("Start Thread C"); C.start();
System.out.println("End of Main ");
}
}

12.8-12.10 Thread from interface Runnable:


class ThreadA implements Runnable //Step 1
{public void run() //Step 2
{for (int i=0; i<10; ++i)
System.out.println("Thread A " +i);
System.out.println("Exit Thread A ");

23
Introduction to Java
}
}
class ThreadB extends Thread
{public void run()
{for (int i=0; i<10; ++i)
System.out.println("Thread B " +i);
System.out.println("Exit Thread B ");
}
}
class example4
{ public static void main(String args[])
{ThreadA ARun = new ThreadA(); //Step 3
Thread A = new Thread(ARun); //Step 4
ThreadB B = new ThreadB();

B.setPriority(Thread.MIN_PRIORITY);
A.setPriority(B.getPriority()+1);
System.out.println("Start Thread A");
A.start();
System.out.println("Start Thread B");
B.start();

System.out.println("End of Main ");


}
}

Exception Handling:
Errors are three types, syntax error, run-time error, and logical error. Syntax error can be
easily fixed because a program cannot be executed without fixing syntax errors. The run-time
error will not happen always, this error will trigger only at an instance. For example x=y/z; will
continue to execute without any error unless the value of z is zero. Logical error is like
answering the question incorrectly, example x=a+b*c+d is not same as x=(a+b)*(c+d); compiler
will not give any error until the programmer finds it and fix it .

Try block should be followed by catch block.


Each try block should have its own catch block.
There can be more than one catch block for a try block, this called multiple catch
statement, but it will catch only one catch block at a time
The generic catch is called by calling keyword Exception as argument in the catch it
normally placed as last catch block when used with other exception.
The finally block will be executed irrespective of the exception raised or not raised. This
must be the last block after the catch block.
A try block can have just a finally block without catch block.
Built in exception are automatically thrown when an exception is raised.
A specific exception can be thrown by throwing that exception throw new exception.

24
Introduction to Java

User-defined exceptions must be thrown exclusively; unlike built-in exception this will
not raise exception automatically.

Most commonly used of Exceptions:


ArithmeticException - divide by zero
ArrayIndexOutOfBoundsException - exceeding array boundary
ArrayStoreException - invalid data in an array
FileNotFoundException - non existence of file
IOException - I/O failures read or write to a file etc
NullPointerException - Referring a null object
NumberFormatException - conversion between string and number
OutOfMemoryException - not enough memory

Exmple1:
class anexception
{void display()
{int x=2,z=0;
int a[]={2,4,6,8};
for(int e=0; e<5;++e)
{z=a[e]/x;
System.out.println("finally " + z);
}
}
}

public class finallymethod


{public static void main(String s[])
{int x=0,z=0;
int a[]={2,4,6,8};
try
{ for(int e=0; e<4;++e)
{z=a[e]/x;
System.out.println("finally " + z);
}
}
catch(ArithmeticException e)
{System.out.println(e);}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
catch(Exception e)
{System.out.println(e);}
finally
{System.out.println("finally " + z);
}

25
Introduction to Java

anexception ae = new anexception();


try{ae.display();
}
catch(ArithmeticException e)
{System.out.println(e);}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
catch(Exception e)
{System.out.println(e);}
finally
{System.out.println("finally through method");
}
}
}

Example2:
class error
{
public static void main(String args[])
{ int a=0,y=5,z=0;

try{ if(z==0)
throw new ArithmeticException();
else
a=y/z;
}
catch (ArithmeticException x)
{System.out.println("AE " +x);}
catch (ArrayStoreException x)
{System.out.println("ASE " +x);}
catch (Exception e)
{System.out.println("Error " +e);}
finally
{System.out.println("Finally")};
}
}

Example3:
class exception
{ public static void main (String...s)
{int x=20,y=0;
try
{y=x/y;
}
finally

26
Introduction to Java
{System.out.println("finally" +y);
}
}
}

Example4:
class MyException extends Exception
{private int detail;
MyException(int a)
{detail=a;
}
public String toString()
{return "Userdefined Exception " + detail;
}
}
class MyExceptionA extends Exception
{private int detail;
MyExceptionA(String m)
{ super(m);

}
}

public class errorhandling


{public static void main(String []args)
{int x=2,y=40,z=0;
try{if (z==0)
throw new MyExceptionA("Error");
}
catch (MyExceptionA e)
{System.out.println(e);
}
try{if (z==0)
throw new MyException(z);
}
catch (MyException e)
{System.out.println(e);
}
try{
x=y/z;
}
catch (ArrayIndexOutOfBoundsException e)
{System.out.println(e);
}
finally{System.out.println("Finally");
System.out.println(x=y+z);

27
Introduction to Java
}

}
}

Managing Input/Output Files in Java

Java has developed stream classes to handle input and output operation of files as well as
from keyboard, mouse, disk, memory, network, etc. The stream classes are classified into two
groups.
1. Byte stream classes to handle I/O on bytes.
2. Character stream classes to handle I/O on characters.

Bytes stream classes:


Input Stream classes
To handle input on bytes several methods are developed in InputStream class which is the
abstract class. These methods are defined in DataInputStream and FileInputStream which extend
the InputStream class.
1. Reads a byte from input stream - method read( )
2. Reads array of bytes - method read(byte b[])
3. Reads m bytes into b starting from nth byte - method read(byte b[], int n, int m)
4. Finds number of bytes in the input - method available( )
5. To skip n bytes from the input - method skip(n)
6. To go to the beginning of the stream - method reset( )
7. To close the stream - method close( )
DataInputStream also implements the method contains in the DataInput interface. The
methods in DataInput interface are.
1. readShort( ) 5. readDouble( )
2. readInt( ) 6. readLine( )
3. readLong( ) 7. readChar( )
4. readFloat( ) 8. readBoolean( )

Output Stream classes


To handle output on bytes several methods are developed in OutputStream class which is
the abstract class. These methods are called through DataOutputStream and FileOutputStream
which extend the InputStream class.
1. Writes a byte from input stream - method write( )
2. Writes array of bytes - method write(byte b[])
3. Writes m bytes into b starting from nth byte - write(byte b[], int n, int m)
4. To flush the output stream - method flush( )
5. To close the stream - method close( )
DataOutputStream also implements the method contains in the DataOutput interface. The
methods in DataOutput interface are.
1. writeShort( ) 5. writeDouble( )
2. writeInt( ) 6. writeLine( )
3. writeLong( ) 7. writeChar( )

28
Introduction to Java
4. writeFloat( ) 8. writeBoolean( )

Character Stream classes:


Input and Output Stream classes
The methods have the same name as in the bytes input stream except each method
in the character streams are placed in separate class.

Character Stream Class Byte Stream Class


Reader InputStream
FileReader FileInputStream
FilterReader FilterInputStream
StringReader StringBufferInputStream
Writer OutputStream
FilterWriter FilterOutputStream
FileWriter FileOutputStream
CharArrayReader ByteArrayInputStream
CharArrayWriter ByterArrayOutputStream

PipedReader PipedInputStream
PipedWriter PipedOutputStream

Note: Some stream classes and their methods should be placed inside the try block.

The class Stream Tokenizer breaks the text to meaningful pieces called tokens. The
StreamTokenizer class is similar to StringTokenizer class which breaks string into tokens.

Exception Classes in File Handling:


1. EOFException
2. FileNotFoundException
3. InterruptedIOException
4. IOException

Interactive Input and Output


Interactive IO can performed using DataInputStream classes. To perform keyboard
activity the objects of DataInputStream and StringTokenizer classes. The System class contains
three objects namely System.in, System.out and System.err. These objects are used for input
from keyboard, output to the screen, and display error messages. System class is stored in
java.lang package which is import automatically during compilation.

29
Introduction to Java
Two or more files can be converted to single file using SequenceInputStream class. And
also Graphical Input and Output can be performed by importing java.awt package and extending
class Frame.

Basic IO from keyboard Example 1:


import java.io.*;
import java.util.*; //Tokenizer class
public class basicIO
{public static void main(String...s) throws IOException
{DataInputStream din = new DataInputStream(System.in); //Keyboard action
StringTokenizer st;

System.out.println("Enter Reg No");


st = new StringTokenizer(din.readLine());
int reg = Integer.parseInt(st.nextToken());

System.out.println("Name ");
st = new StringTokenizer(din.readLine());
String name = String.valueOf(st.nextToken());

System.out.println("Cut Off Mark");


st = new StringTokenizer(din.readLine());
float mark = Float.valueOf(st.nextToken());

System.out.println("Total ");
st = new StringTokenizer(din.readLine());
double total = Double.valueOf(st.nextToken());

System.out.println("Register No " + reg);


System.out.println("Name " + name);
System.out.println("Cut Off Mark " + mark);
System.out.println("Total " + (mark+total));

}
}

30
Introduction to Java
Write and Read to and from file Example 2:
import java.io.*;
import java.util.*; //Tokenizer class
class interactive
{public static void main(String...s) throws IOException
{File interact = new File ("interact.txt");
DataInputStream din = new DataInputStream(System.in); //Keyboard action
StringTokenizer st;

FileOutputStream fos = new FileOutputStream(interact);


DataOutputStream dos = new DataOutputStream(fos);

System.out.println("Enter Reg No");


st = new StringTokenizer(din.readLine());
int reg = Integer.parseInt(st.nextToken());

System.out.println("Name ");
st = new StringTokenizer(din.readLine());
String name = String.valueOf(st.nextToken());

System.out.println("Cut Off Mark");


st = new StringTokenizer(din.readLine());
float mark = Float.valueOf(st.nextToken());

System.out.println("Total ");
st = new StringTokenizer(din.readLine());
double total = Double.valueOf(st.nextToken());

dos.writeInt(reg);
dos.writeUTF(name); //String value
dos.writeFloat(mark);
dos.writeDouble(mark+total);

din.close(); dos.close(); fos.close();

FileInputStream fin = new FileInputStream(interact);


DataInputStream dis = new DataInputStream(fin);

System.out.println(dis.readInt());
System.out.println(dis.readUTF());
System.out.println(dis.readFloat());
System.out.println(dis.readDouble());
fin.close(); dis.close();

}
}

31
Introduction to Java
Read and Write to and from file by bytes Example 3:
import java.io.*;

class BytesIO
{public static void main(String...s)
{File in = new File ("in.txt");
File out = new File ("out.txt");
FileInputStream ins = null;
FileOutputStream outs = null;

try{ins = new FileInputStream(in); //must be in the try block


outs = new FileOutputStream(out); //must be in the try block
int x;
byte b;
System.out.println(x=ins.available());//finds number of character
ins.skip(0);//moves the cursor to afer first character
while ((b=(byte)ins.read())!=-1)
{outs.write(b); //do not convert to char to write to a file
System.out.print((char)b); //convert to char to display on monitor
}
}

catch(IOException e)
{System.out.println(e);
System.exit(-1);
}

finally
{try{ins.close();
outs.close();
}
catch(Exception e){}
}
}
}

32
Introduction to Java
Read and Write to and from file by character Example 4:
import java.io.*;

class CharacterIO
{public static void main(String...s)
{File in = new File ("in.txt");
File out = new File ("outc.txt");
FileReader ins = null;
FileWriter outs = null;

try{ins = new FileReader(in); //must be in the try block


outs = new FileWriter(out);
//System.out.println(ins.available()); for bytes only
ins.skip(0);//It moves the cursor to first position
int c;

while ((c=ins.read())!=-1)
{outs.write(c); //do not convert to char to write to a file
System.out.print((char)c); //do not convert to char to display on monitor
}
}

catch(IOException e)
{System.out.println(e);
System.exit(-1);
}
finally
{try{ins.close();
outs.close();
}
catch(Exception e){}
}
}
}

33
Introduction to Java
Read from file and display on monitor by bytes Example 5:
import java.io.*;
class FileToMonitor
{public static void main(String...s)
{File in = new File ("in.txt");
FileInputStream ins = null;
try{ins = new FileInputStream(in); //must be in the try block or throws
byte b;

while ((b=(byte)ins.read())!=-1)
{System.out.print((char)b);
}
}
catch(IOException e)
{System.exit(-1);
}
finally
{try{ins.close(); //must be in the try block
System.out.println();
}
catch(Exception e){}
}
}
}

Read from file and display on monitor by character Example 6:


import java.io.*;
class FileToMonitorChar
{public static void main(String...s)
{File in = new File ("mtfc.txt");
FileReader ins = null;
try{ins = new FileReader(in); //must be in the try block
int c;
while ((c=ins.read())!=-1)
{System.out.print((char)(c));
}
}
catch(IOException e)
{System.exit(-1); }
finally
{try{ins.close(); System.out.println();
}
catch(Exception e){}
}
}
}

34
Introduction to Java

Monitor to File Example 7:


import java.io.*;

class MonitorToFile
{public static void main(String...s)
{File out = new File ("mtf.txt");
FileOutputStream outs = null;
byte c[]={'a','b','c', '\n','d','e'};
try{outs = new FileOutputStream(out); //must be in the try block
outs.write(c);
}
catch(IOException e)
{System.exit(-1);
}
finally
{try{outs.close();

}
catch(Exception e){}
}
}
}

Random file access Example 8:


import java.io.*;
class RandomFile
{public static void main(String...s) throws IOException
{RandomAccessFile random = new RandomAccessFile ("random.txt", "rw");

random.writeInt(9800);
random.writeDouble(2213.76);
random.writeBoolean(false);
random.writeChar('R');

random.seek(0);
System.out.println(random.readInt());
System.out.println(random.readDouble());
System.out.println(random.readBoolean());
System.out.println(random.readChar());

random.seek(random.length()); //goes to the 4th item


random.writeBoolean(true);
//System.out.println(random.length());
random.seek(0); //go to 4th item false
System.out.println(random.readInt());

35
Introduction to Java
random.seek(4); //go to 4th item false
System.out.println(random.readBoolean());
random.close();

}
}

Primary Data Type Example 9:


import java.io.*;

class PrimaryDataType
{public static void main(String...s) throws IOException
{File primary = new File ("primary.txt");

FileOutputStream fos = new FileOutputStream(primary);


DataOutputStream dos = new DataOutputStream(fos);

dos.writeUTF("Electronics ");
dos.writeLong(9800);
dos.writeDouble(2213.76);
dos.writeBoolean(true);
dos.writeChar('R');
dos.writeUTF("and Communication ");
dos.writeLong(980105);
dos.writeDouble(22.76);
dos.writeBoolean(false);
dos.writeChar('C');

dos.close(); fos.close();

FileInputStream fin = new FileInputStream(primary);


DataInputStream din = new DataInputStream(fin);

for(int i=0; i<din.available(); ++i)


{System.out.print(din.readUTF());
System.out.print(din.readLong());
System.out.print(din.readDouble());
System.out.print(din.readBoolean());
System.out.print(din.readChar());
System.out.println(i);}
din.close(); fin.close();

}
}

36
Introduction to Java
Points to Remember
File name must be same as class name when there is public class.
File must have .java as extension.
javac test.java to compile java program.
java test.java to run java program.
System.out.print function to display output
System.out.println function to display output and goes to next line.
Built in methods must be identified through class. System is a package, out is the class
and println is the method or function.
Variables in the System.out.println can be concacted using + operator; it implicitly
converts all data to string.
Control structure logic has same rule as C and C++.
Identifier includes number, alphabet, _ and $. The first must not be number.
Java does not support unsigned integers. Integer is 4 bytes.
Java does not converts float to int even if the data to be lost like in C++ (pg.42). The
conversion is automatic if smaller type is assigned to larger type (pg.57), in such type
casting not required like in C++. Type cast is used other wise (pg.58).
Char data type with ++/-- can be used to find the next or previous character in java
(pg:48).
Java has boolean as data type like C++ (pg:49).
Java supports string class to instead of character array but character array can also be
used.
Java does not support two variables with same name even in different blocks (pg:56).
Array size is mention only by using memory manipulator new in java, which is similar to
C++, in other word java does allow to create array with static size.
Array length can be found using length method in java.
Java does check for array boundary when it exceeds it generates error.
To initialize array new is not required (pg.63).
Java has new data type called string.
Strings are concataed (appended) with simple + operator instead of strcpy in C, C++.
Java does not support pointer because there is no pointer in java.
Modulus operator % can be used for all numeric data type.
if(!x) is same as if(x==0) but cannot use if(!x) method like in C, C++.
Short Circuit Logical operator
Boolean logical operator
Break, continue, return, goto, try, catch, throw, throws, and finally to control the flow of
execution.
Break, continue can have label like goto (pg.121).
Function is known as Method in Java.
Methods should be inside the class it cannot be defined outside.
Methods are called through the class to which it belong using dot operator.
Method without argument should not have even void as argument.
Method cannot have default value.
Class members are public by default.

37
Introduction to Java

Class declared as public must be separate file.


Base class is public by default in inheritance.
Separate directory or folder must be created for the Package the directory must have the
same name as package. When creating package for the first time another folder is created
with same name as package.
Class declared as public to place in a package.
Doubt: can class be inherited for package. Ex square class
A user defined exception class should be defined. Those exceptions should be called
only through methods (just restricting throw in C++) for all other run-time and error built
exception can be used.

38