Oop Notes Final
Oop Notes Final
LECTURE NOTES
I. INTRODUCTION TO JAVA
What is Java
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc
History of Java
James Gosling, Patrick Naughton and Mike Sheridan initiated the Java
language project in 1991. Team of sun engineers designed for small,
embedded systems in electronic appliances like set-top boxes. Initially it was
called "Greentalk" later it was called Oak .
Object means a real word entity such as pen, chair, table etc. Object-
Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and
maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
If any language fallows the OOPS concepts that language we call it as object
oriented language
To create a simple java program, you need to create a class that contains
main method. Let's understand the requirement first.
Notepad − On Windows machine, you can use any simple text editor
like Notepad (Recommended for this tutorial), TextPad.
Netbeans − A Java IDE that is open-source and free which can be
downloaded from Eclipse − A Java IDE developed by the eclipse open-
source community and can be downloaded from
What is JVM
It is:
What it does
Loads code
Verifies code
Executes code
Provides runtime environment
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
Java complier translates the java source code into byte code or intermediate
code ,not the executable file .JVM take the byte code and convert into
executable code corresponding to Operating system
class classname
type methodname1(parameter-list)
{ // body of method }
type methodname2(parameter-list)
{ // body of method }
{ // body of method } }
The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and
variables defined within a class are called members of the class. In most
classes, the instance variables are acted upon and accessed by the methods
defined for that class
Simple Class
Class Sample
void get()
{ // body
} }
Object in Java
Object is the physical as well as logical entity whereas class is the logical
entity only.
Object Definitions:
1. class Sample{
2. public static void main(String args[]){
3. System.out.println("How are you ");
4. }
5. }
Java Identifiers
All Java components require names. Names used for classes, variables, and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as
follows −
There are eight primitive data types supported by Java. Primitive data types
are predefined by the language and named by a keyword. Let us now look
into the eight primitive data types in detail.
byte
short
long
float
double
boolean
char
Java Literals
String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes.
Examples of string literals are −
Example
"Hello World" "two\nlines" "\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For
example − char a = '\u0001'; String a = "\u0001";
Java language supports few special escape sequences for String and char
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t Tab
\\ Backslash
1. class Sample{
2. public static void main(String[] args){
3. int i=50;
4. int j=60;
5. int k=a+b;
6. System.out.println(k);
7. } }
1. class Sample{
2. public static void main(String[] args){
3. int j=10;
4. float k=a;
5. System.out.println(i);
6. System.out.println(j);
7. }}
Unicode System
Unicode is a universal international standard character encoding that is
capable of representing most of the world's written languages.
Java Tokens are the smallest individual building block or smallest unit of a
Java program, it is used by the Java compiler for constructing expressions
and statements. Java program is collection different types of tokens,
comments, and white spaces.
Java Supports Five Types of Tokens:
Variable
local variable
instance variable
static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is
called instance variable . It is not declared as static.
3) Static variable
Operators in java
There are many types of operators in java which are given below:
Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java If-else Statement
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition
is true. The following is the syntax
1. if(condition){
2. //code to be executed
3. }
IF-else Statement
The if-else statement in java tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Syntax:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Syntax:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Example:
The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
The simple for loop is same as C/C++. We can initialize variable, check
condition and increment/decrement value.
Syntax:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Example:
The Java while loop is used to iterate a part of the program several times. If
the number of iteration is not fixed, it is recommended to use while loop.
Syntax:
1. while(condition){
2. //code to be executed
3. }
The Java do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use do-while loop.The Java do-while loop
is executed at least once because condition is checked after loop body.
Syntax: do{ /code to be executed
}while(condition);
int j=1;
do{ System.out.println(j);
j++;
}while(j<=10);
} }
The Java break is used to break loop or switch statement. It breaks the
current flow of the program at specified condition. In case of inner loop, it
breaks only inner loop.
Example:
Example:
Array in java
1. arrayname=new datatype[size];
Example
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
1. class Testarray{
2. public static void main(String args[]){
3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10; a[1]=20; a[2]=70; a[3]=40; a[4]=50;
5. for(int i=0;i<a.length;i++)//length is the property of array
6. System.out.println(a[i]);
7. }}
We can declare, instantiate and initialize the java array together by:
1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}
In such case, data is stored in row and column based index (also known as
matrix form).
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
1. class Ex{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14. } }
Java Comments
The java comments are statements that are not executed by the compiler
and interpreter. The comments can be used to provide information or
explanation about the variable, method, class or any statement. It can also
be used to hide program code for specific time.
Syntax:
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */
Example:
Syntax:
1. /**
2. This
3. is
4. documentation
5. comment
6. */
VI CONSTRUCTORS
Constructor is special member function ,it has the same name as class
name. It is called when an instance of object is created and memory is
allocated for the object.
class Sample{
Sample()
{
System.out.println("Sample is created");
}
public static void main(String args[])
{
Sample b=new Sample();
} }
There are many differences between constructors and methods. They are
given below.
The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class.
The static keyword belongs to the class than instance of the class.
The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
The static variable gets memory only once in class area at the time of
class loading.
If you apply static keyword with any method, it is known as static method.
2.
3. class Stud{
4. int rollno;
5. String name;
6. static String college = "BEC";
7.
8. static void change(){
9. college = "JBIEIT";
10. }
11. Stud(int r, String n){
12. rollno = r;
13. name = n;
14. }
15.
16. void display (){System.out.println(rollno+" "+name+" "+college
);}
17. public static void main(String args[]){
18. Stud.change();
19. Stud s1 = new Stud (11,"Kiran");
20. Stud s2 = new Stud (22,"Arjun");
21. Stud s3 = new Stud (33,"srinu");
22. s1.display();
23. s2.display();
24. s3.display();
25. }
26. }
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display(); }}
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this keyword
while invoking the method
1. class B{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. B b=new B();
12. b.n();
13. }}
The this() constructor call can be used to invoke the current class
constructor. It is used to reuse the constructor. In other words, it is used for
constructor chaining.
Calling default constructor from parameterized constructor:
1. class B{
2. B(){System.out.println("hello ");}
3. B(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class Sample{
9. public static void main(String args[]){
10. B a=new B(10);
11. }}
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "
+fee);}
15. }
16. class SamplTest{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
We can pass the this keyword in the constructor also. It is useful if we have
to use one object in multiple classes. Let's see the example:
1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
We can return this keyword as an statement from the method. In such case,
return type of the method must be the class type (non-primitive). Let's see
the example:
1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement
from the method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }
UNIT -II
VII. Inheritance
class base
{
.....
.....
}
class derive extends base
{
.....
.....
}
class Person {
void teach() {
System.out.println("Teaching subjects");
} }
class CheckForInheritance {
public static void main(String args[]) {
Person s1 = new Students();
s1.teach();
s1.listen();
}
}
In this type of inheritance, a derived class gets created from another derived
class and can have any number of levels.
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class homeTution extends Student {
void explains() {
System.out.println("Does homework");
}
}
class CheckForInheritance {
public static void main(String argu[]) {
homeTution h = new himeTution();
h.explains();
d.teach();
d.listen();
}
}
In this type of inheritance, there are more than 1 derived classes which get
created from one single base class.
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class Principal extends Teacher {
void evaluate() {
System.out.println("Evaluating");
}
}
class CheckForInheritance {
public static void main(String argu[]) {
Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error
}
}
Let us imagine a situation where there are three classes: A, B and C. The C
class inherits A and B classes. In case, class A and class B have a method
with same name and type and as a programmer, you have to call that
method from child class's (C) object, there-there will be ambiguity as which
method will be called either of A or of B class.
VIII Polymorphism
//method overriding
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[]) {
child c1 = new child();
c1.work();
} }
Advantage of method overriding
One major advantage of method overriding is that a class can give its own
specific execution to an inherited method without having the modification in
the parent class (base class).
We can use super keyword to access the data member or field of parent
class. It is used if parent class and child class have same fields.
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
The super keyword can also be used to invoke the parent class constructor.
Let's see a simple example:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
In this example, we have created two methods that differs in data type. The
first add method receives two integer arguments and second add method
receives two double arguments.
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
IX ABSTRACTION
Abstraction in Java
Another way, it shows only important things to the user and hides the
internal details for example sending sms, you just type the text and send the
message. You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead of how it does it.
1. abstract class A{ }
abstract method
A method that is declared as abstract and does not have implementation is
known as abstract method.
In this example, Bike the abstract class that contains only one abstract
method run. It implementation is provided by the Honda class.
There are mainly three reasons to use interface. They are given below.
In this example, Printable interface has only one method, its implementation
is provided in the A class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Differences between abstract class and interface that are given below.
1. interface A{
2. void a(); void b();
3. void c(); void d();
4. }
5. abstract class B implements A{
6. public void c(){System.out.println("I am c");}
7. }
8. class M extends B{
9. public void a(){System.out.println("I am a");}
10. public void b(){System.out.println("I am b");}
11. public void d(){System.out.println("I am d");}
12. }
13. class Test5{
14. public static void main(String args[]){
15. A a=new M();
16. a.a();
17. a.b();
18. a.c();
19. a.d();
20. }}
X PACKAGE
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in
case of windows) etc. If you want to keep the package within the same
directory, you can use . (dot).
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
2) Using packagename.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will
be accessible. Now there is no need to import. But you need to use fully
qualified name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util
and java.sql packages contain Date class.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
6.
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
There are two types of modifiers in java: access modifiers and non-access
modifiers.
1. private
2. default
3. protected
4. public
Understanding all java access modifiers
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant
pool first. If the string already exists in the pool, a reference to the pooled
instance is returned. If string doesn't exist in the pool, a new string instance
is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
2) By new keyword
Java trim() method is used to eliminates white spaces before and after a
string.
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
1. class Teststringcomparison1{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
1. class Teststringcomparison3{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same insta
nce)
7. System.out.println(s1==s3);//false(because s3 refers to instance cre
ated in nonpool)
8. }
9. }
3) String compare by compareTo() method
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
1. class Teststringcomparison4{
2. public static void main(String args[]){
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
Java string concatenation operator (+) is used to add strings. For Example:
1. class TestStringConcatenation1{
2. public static void main(String args[]){
3. String s="Sachin"+" Tendulkar";
4. System.out.println(s);//Sachin Tendulkar
5. }
6. }
The String concat() method concatenates the specified string to the end of
current string. Syntax:
1. public String concat(String another)
1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. } }
Substring in Java
You can get substring from the given string object by one of the two
methods:
In case of string:
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2));//he
StringTokenizer in Java
Constructor Description
String nextToken(String
returns the next token based on the delimeter.
delim)
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
1. import java.util.*;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7. // printing next token
8. System.out.println("Next token is : " + st.nextToken(","));
9. }
10. }
Java I/O (Input and Output) is used to process the input and produce the
output.
Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
In java, 3 streams are created for us automatically. All these streams are
attached with console.
Byte Streams Java byte streams are used to perform input and output of 8-
bit bytes. Though there are many classes related to byte streams but the
most frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an
input file into an output file:
import java.io.*;
{
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
} }
Character Streams Java Byte streams are used to perform input and output
of 8-bit bytes, whereas Java Character streams are used to perform input
and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that
FileReader reads two bytes at a time and FileWriter writes two bytes at a
time.
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close(); } } } }
import java.io.*;
try {
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
1. import java.io.*;
2. public class BufferedInputStreamExample{
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. BufferedInputStream bin=new BufferedInputStream(fin);
7. int i;
8. while((i=bin.read())!=-1){
9. System.out.print((char)i);
10. }
11. bin.close();
12. fin.close();
13. }catch(Exception e){System.out.println(e);}
14. }
15. }
UNIT III
Types of Exception
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says there
are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
3) Error
Java try-catch
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
Case 1
Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){System.out.println(e);}
8. finally{System.out.println("finally block is always executed");}
9. System.out.println("rest of the code...");
10. }
11. }
Case 3
Let's see the java finally example where exception occurs and handled.
1. throw exception;
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
} }
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
} }
If you are creating your own Exception that is known as custom exception or
user-defined exception. Java custom exceptions are used to customize the
exception according to user need.
1. class TestCustomException1{
2.
3. static void validate(int age)throws InvalidAgeException{
4. if(age<18)
5. throw new InvalidAgeException("not valid");
6. else
7. System.out.println("welcome to vote");
8. }
9.
10. public static void main(String args[]){
11. try{
12. validate(13);
13. }catch(Exception m){System.out.println("Exception occured:
"+m);}
14.
15. System.out.println("rest of the code..."); }}
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements
Runnable interface.
public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.
The join() method waits for a thread to die. In other words, it causes the
currently running threads to stop executing until the thread it joins with
completes its task.
Syntax:
public void join()throws InterruptedException
15. }}
ThreadGroup in Java
File: ThreadGroupDemo.java
Synchronization in Java
Types of Synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
wait()
notify()
notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception.
Method Description
2) notify() method
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
UNIT IV
Java Applet
Advantage of Applet
Drawback of Applet
Do You Know
Hierarchy of Applet
Displaying Graphics in Applet
1. import java.applet.Applet;
2. import java.awt.*;
3.
4. public class GraphicsDemo extends Applet{
5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcome",50, 50);
9. g.drawLine(20,30,20,300);
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14. g.setColor(Color.pink);
15. g.fillOval(170,200,30,30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18.
19. }
20. }
EventHandling in Applet
As we perform event handling in AWT or Swing, we can perform it in applet
also. Let's see the simple example of event handling in applet that prints a
message by click on the button.
1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method
because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
The button class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed.
1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new Button("Click Here");
6. b.setBounds(50,100,80,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:
actionPerformed() method
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ActionListenerExample {
4. public static void main(String[] args) {
5. Frame f=new Frame("ActionListener Example");
6. final TextField tf=new TextField();
7. tf.setBounds(50,50, 150,20);
8. Button b=new Button("Click Here");
9. b.setBounds(50,100,60,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(ActionEvent e){
13. tf.setText("Welcome to Javatpoint.");
14. }
15. });
16. f.add(b);f.add(tf);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }
Output:
UNIT V
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular
manner. LayoutManager is an interface that is implemented by all the
classes of layout managers. There are following classes that represents the
layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
Fields
Modifier and Type Field Description
It is used to
hold the
double[] columnWeights overrides to
the column
weights.
It is used to
hold the
overrides to
int[] columnWidths
the column
minimum
width.
It is used to
maintains
the
protected association
Hashtable<Component,GridBagConstraints comptable between a
> component
and its
gridbag
constraints.
It is used to
hold a
gridbag
defaultConstraint constraints
protected GridBagConstraints
s instance
containing
the default
values.
It is used to
hold the
layout
protected GridBagLayoutInfo layoutInfo
information
for the
gridbag.
No longer in
use just for
protected static int MAXGRIDSIZE backward
compatibilit
y
It is smallest
protected static int MINSIZE grid that can
be laid out
by the grid
bag layout.
It is
preferred
grid size
protected static int PREFERREDSIZE that can be
laid out by
the grid bag
layout.
It is used to
hold the
overrides to
int[] rowHeights
the row
minimum
heights.
It is used to
hold the
double[] rowWeights overrides to
the row
weights.
Useful Methods
Modifier and Type Method Description
It adds specified
component to
addLayoutComponent(Component the layout, using
void
comp, Object constraints) the specified
constraints
object.
It has no effect,
since this layout
addLayoutComponent(String name, manager does
void
Component comp) not use a per-
component
string.
This method is
AdjustForGravity(GridBagConstraints for backwards
protected void
constraints, Rectangle r) compatibility
only
This method is
obsolete and
protected void ArrangeGrid(Container parent) supplied for
backwards
compatibility
It is for getting
the constraints
GridBagConstraints getConstraints(Component comp)
for the specified
component.
It returns the
getLayoutAlignmentX(Container
float alignment along
parent)
the x axis.
It returns the
getLayoutAlignmentY(Container
float alignment along
parent)
the y axis.
It determines
column widths
int[][] getLayoutDimensions() and row heights
for the layout
grid.
This method is
obsolete and
protected GetLayoutInfo(Container parent, int
supplied for
GridBagLayoutInfo sizeflag)
backwards
compatibility.
It determines the
origin of the
layout area, in
Point getLayoutOrigin() the graphics
coordinate space
of the target
container.
It determines the
weights of the
double[][] getLayoutWeights() layout grid's
columns and
rows.
This method is
obsolete and
protected GetMinSize(Container parent, supplied for
Dimension GridBagLayoutInfo info) backwards
compatibility
only
Example
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }
Output:
Java Swing Tutorial
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used
to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
There are many differences between java awt and swing that are given
below.
Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed. It inherits AbstractButton class.
Java JRadioButton
1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Java GridBagLayout
Fields
Modifier and Type Field Description
It is used to
hold the
overrides to
int[] columnWidths
the column
minimum
width.
It is used to
maintains
the
protected association
Hashtable<Component,GridBagConstraints comptable between a
> component
and its
gridbag
constraints.
It is used to
hold a
gridbag
defaultConstraint constraints
protected GridBagConstraints
s instance
containing
the default
values.
It is used to
hold the
layout
protected GridBagLayoutInfo layoutInfo
information
for the
gridbag.
No longer in
use just for
protected static int MAXGRIDSIZE backward
compatibilit
y
It is smallest
grid that can
protected static int MINSIZE be laid out
by the grid
bag layout.
It is
preferred
grid size
protected static int PREFERREDSIZE that can be
laid out by
the grid bag
layout.
It is used to
hold the
overrides to
int[] rowHeights
the row
minimum
heights.
It is used to
hold the
double[] rowWeights overrides to
the row
weights.
Useful Methods
Modifier and Type Method Description
It adds specified
component to
addLayoutComponent(Component the layout, using
void
comp, Object constraints) the specified
constraints
object.
It has no effect,
since this layout
addLayoutComponent(String name, manager does
void
Component comp) not use a per-
component
string.
It adjusts the x,
y, width, and
height fields to
the correct
adjustForGravity(GridBagConstraints
protected void values
constraints, Rectangle r)
depending on
the constraint
geometry and
pads.
This method is
AdjustForGravity(GridBagConstraints for backwards
protected void
constraints, Rectangle r) compatibility
only
This method is
obsolete and
protected void ArrangeGrid(Container parent) supplied for
backwards
compatibility
It is for getting
the constraints
GridBagConstraints getConstraints(Component comp)
for the specified
component.
It returns the
getLayoutAlignmentX(Container
float alignment along
parent)
the x axis.
It returns the
getLayoutAlignmentY(Container
float alignment along
parent)
the y axis.
It determines
column widths
int[][] getLayoutDimensions() and row heights
for the layout
grid.
This method is
obsolete and
protected getLayoutInfo(Container parent, int
supplied for
GridBagLayoutInfo sizeflag)
backwards
compatibility.
This method is
obsolete and
protected GetLayoutInfo(Container parent, int
supplied for
GridBagLayoutInfo sizeflag)
backwards
compatibility.
It determines the
origin of the
layout area, in
Point getLayoutOrigin() the graphics
coordinate space
of the target
container.
It determines the
weights of the
double[][] getLayoutWeights() layout grid's
columns and
rows.
This method is
obsolete and
protected GetMinSize(Container parent, supplied for
Dimension GridBagLayoutInfo info) backwards
compatibility
only
Example
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }
Output:
Java JTree
The JTree class is used to display the tree structured data or hierarchical
data. JTree is a complex component. It has a 'root node' at the top most
which is a parent for all nodes in the tree. It inherits JComponent class.
1. import javax.swing.*;
2. import javax.swing.tree.DefaultMutableTreeNode;
3. public class TreeExample {
4. JFrame f;
5. TreeExample(){
6. f=new JFrame();
7. DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style"
);
8. DefaultMutableTreeNode color=new DefaultMutableTreeNode("color"
);
9. DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
10. style.add(color);
11. style.add(font);
12. DefaultMutableTreeNode red=new DefaultMutableTreeNode("r
ed");
13. DefaultMutableTreeNode blue=new DefaultMutableTreeNode("
blue");
14. DefaultMutableTreeNode black=new DefaultMutableTreeNode
("black");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode
("green");
16. color.add(red); color.add(blue); color.add(black); color.add(gre
en);
17. JTree jt=new JTree(style);
18. f.add(jt);
19. f.setSize(200,200);
20. f.setVisible(true);
21. }
22. public static void main(String[] args) {
23. new TreeExample();
24. }}
Output: