Java Full Notes Unit 1-6 V2V by Rajan Sir
Java Full Notes Unit 1-6 V2V by Rajan Sir
OUR SERVICES:
Diploma in All Branches, All Subjects
Degree in All Branches, All Subjects
BSCIT / CS
Professional Courses
Even though “goto’ and “const” are no longer used in the JAVA programming language, they
still cannot be used.
1.3.2. Constants
Constants in JAVA are fixed values those are not changed during the Execution of
program JAVA supports several types of Constants those are
Integer Constants
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and
many other things those are as follows
In The Exponential Form of Representation the Real Constant is Represented in the two Parts The
part before appearing e is called mantissa whereas the part following e is called Exponent.
In Real Constant The Mantissa and Exponent Part should be Separated by letter “e”
The Mantissa Part have may have either positive or Negative Sign
Default Sign is Positive
A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within Single
inverted commas.
Like ‘S’ ,’1’ etc are Single Character Constants
String Constants
String is a Sequence of Characters Enclosed between double Quotes These Characters may be digits ,
Alphabets Like “Hello” , “1234” etc.
JAVA Also Supports Backslash Constants. These are used in output methods. E.G. – \n is used for
new line Character These are also Called as escape Sequence or backslash character Constants.
E.G.
\t For Tab ( Five Spaces in one Time )
\b Back Spac
\f form feed
\n line feed
\r carriage reurn
\” double quote
\’ single quote
\\ blackslash
1.3.3. Variable
Variable is name of reserved area allocated in memory.
E.G. – int data = 50; // Here data is variable
String Objects
A string in JAVA is not a primitive data type. It is an object from the system defined class
String.
Following program demonstrate the use of Relational Operator ==, !=, >, <, >= and <=
class RelOptrDemo
{
public static void main(String[] args)
{
int a = 10, b = 15, c = 15;
System.out.println("Relational Operators and returned values");
System.out.println(" a > b = " + (a > b));
1.6. Programs
1) Write a program in java to print your name?
2) Program for creating class students and printing the data for two objects?
3) Write a program in java to demonstrate the arithmetic operators?
4) Write a program in java, to calculate the area and circumference of circle?
5) Write a program in java to calculate the area and perimeter of square?
6) Write a program in java calculate the area and perimeter of rectangle?
7) Write a program in java to demonstrate the math functions?
8) Write a program in java to find the large/small no among the two nos?
End of Unit-I
2.1.2. Constructor
Constructor in JAVA is a special type of method that is used to initialize the object.
JAVA constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as constructor.
A constructor has same name as the class in which it resides.
Constructor in JAVA cannot be abstract, static, final or synchronized.
These modifiers are not allowed for constructor.
2. Parameterized Constructor
A constructor that have parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor.
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[ ])
{
a=20
b=30
sum=50
3) Write a program to accept number from command line and print square root of the
number?
class clsdemo3
{
public static void main(String[] args)
{
int n= Integer.parseInt(args[0]);
double ans;
ans=Math.sqrt(n);
System.out.println("Square root of "+n+"= " +ans);
}
}
>javac clsdemo3.java
>java clsdemo3 25
Square root of 25= 5.0
Type of Array
There are two types of array.
One/ Single Dimensional Array
Two/Multidimensional Array
2.3.1. One/ Single Dimensional Array
The One dimensional array can be represented as
Array a[5]
10 20 70 40 50
0 1 2 3 4
Example
class Testarray
{
public static void main(String args[])
{
int a[ ]=new int[5]; //declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
//traversing array
We can declare, instantiate and initialize the java array together by:
int a[ ]={33,3,4,5}; //declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[ ]={10,20,30,40,50}; //declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length; i++) //length is the property of array
System.out.println(a[i]);
}
}
Output
10
20
30
40
50
2.3.2. Two dimensional Array
In such case, data is stored in row and column based index (also known as matrix form).
Example to instantiate Multidimensional Array in Java
2.4. Strings
Definition- String is a collection of characters.
In java, the string can be defined using two commonly used methods.
1) Using String class
2) Using StringBufferClass
2.4.1. String classes
The syntax of String class is
String string_variable;
Example:-
class stringDemo
{
public static void main(String args[])
{
String s=”Welcome to java programming”;
Syste.out.println(“ ”+s);
}
}
Output
Welcome to java programming
Operation on Strings using String class.
Following are some commonly defined methods by a string class.
Method Description
s1.charAt(position) Return the character present at the index position.
s1.compareTo(s2) If s1<s2 then it returns positive. If s1>s2 then it return negative and if
s1=s2 then it returns zero.
Programs
1) Performs the following string/ string buffer operations, write java program
a) Accept a password from user
b) Check if password is correct then display “Good”, else display “Wrong”.
c) Display the password in reverse order
d) Append password with “Welcome”.
import java.util.*;
class StringBufferDemo
{
public static void main(String[] args)
{
String s="MSBTE-S-21";
Scanner sc=new Scanner(System.in);
System.out.print("Enter the password: ");
String pwd=sc.nextLine();
2) Write a simple java program to find the reverse string and check the weathered the
entered string is palindrome or not?
import java.util.*;
class ReversePalindrome
{
public static void main(String[] args)
{
String s1;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the String: ");
import java.util.*;
class VectorDemo
{
public static void main(String[] args)
{
Vector v1= new Vector(7);
v1.addElement(10);
v1.add(30);
v1.add(50);
v1.add(20);
v1.add(40);
v1.add(10);
v1.add(20);
System.out.println("The elements in the vector are:"+v1);
System.out.println("The orignal size of vector : "+v1.size());
System.out.println("Removing the Third Element ");
v1.remove(2); //3rd element
System.out.println("Removing the Fouth Element ");
v1.remove(3); //4rd element
System.out.println("Now The elements in the vector are:"+v1);
Program 2:- Write a program to add 2 integer, 2 string and 2 float objects to a vector. Remove
element specified by user and display the list.
byte Byte
char Char
double Double
float Float
int Integer
long Long
short Short
void Void
class WrapperDemo
{
public static void main(String[] args)
{
System.out.println("Integer number to string Converstion:");
int i=100;
String s=Integer.toString(i);
System.out.println("int value:"+i);
System.out.println("Equivalent to string:"+s);
System.out.println(" ");
System.out.println("String to Integer Converstion:");
String s1="200";
int n=Integer.parseInt(s1);
System.out.println("String value:"+s1);
System.out.println("Equivalent to int:"+n);
}
}
Output:-
Integer number to string Converstion:
int value:100
Equivalent to string:100
End of Unit-II
Output-
This is student
This is teacher
Class: Person,
name , age
Class: employee,
emp_designation,
emp_salary
class person
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
class single_demo
{
public static void main(String args[])
{
employee e=new employee();
e.accept("ramesh",35);
e.display();
e.accept_emp("lecturer",35000.78f);
e.emp_dis();
class emp
{
int empid;
String ename;
emp(int id, String nm)
{
empid=id; ename=nm;
}
}
class work_profile extends emp
{
String dept;
String job;
work_profile(int id, String nm, String dpt, String j1)
{
super(id,nm);
dept=dpt; job=j1;
}
}
class salary_details extends work_profile
{
int basic_salary;
salary_details(int id, String nm, String dpt, String j1,int bs)
{
super(id,nm,dpt,j1);
Example :
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
class Student
{
int id;
String name;
int age;
//creating two arg constructor
Student(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Program 4. Define a class person with data member as Aadharno, name, Panno
implement concept of constructor overloading. Accept data for 5 object and print it.
import java.io.*;
class Person
{
intAadharno;
String name;
String Panno;
Person(intAadharno, String name, String Panno)
{
this.Aadharno = Aadharno;
this.name = name;
this.Panno = Panno;
}
Person(intAadharno, String name)
Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
Example
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
class Employee
{
String name;
String address;
int number;
Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
All variable and methods can be overridden by default in subclass. In order to prevent
this, the final modifier is used. Final modifier can be used with variable, method or class.
A subclass can call a constructor method defined by its super class by use of the
following form of super:
super(parameter-list);
Here,
parameter-list specifies any parameters needed by the constructor in the super class.
super( ) must always be the first statement executed inside a subclass‟ constructor.
Abstract methods, similar to methods within an interface, are declared without any
implementation. They are declared with the purpose of having the child class provide
implementation. They must be declared within an abstract class.
A class declared abstract may or may not include abstract methods. They are created
with the purpose of being a super class.
Syntax
Abstract classes provide a little more than interfaces. Interfaces do not include fields
and super class methods that get inherited, whereas abstract classes do. This means that an
abstract class is more closely related to a class which extends it, than an interface is to a class
that implements it.
Example
Example
class VariableDemo
{
Output:
Interface:-
Defining Interfaces:-
Interface is also known as kind of a class. Interface also contains methods and variables
but with major difference, the interface consist of only abstract method (i.e. methods are not
defined, these are declared only) and final fields (shared constants).
This means that interface do not specify any code to implement those methods and data
fields contains only constants. Therefore, it is the responsibility of the class that implements an
interface to define the code for implementation of these methods. An interface is defined much
like class.
Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
….
return_type method_nameN(parameter list);
Where,
access is either public or not used.
‘interface’ is the java keyword and “InterfaceName” is nay valid java variables.
Variables- of interface are explicitly declared final and static. This means that the
implementing class cannot change them. They must be initialized with constant value.
Methods- The methods declared in interfaces are abstract, there can be no default
implementation of any method specified within an interface.
Features:
1. Variable of an interface are explicitly declared final and static (as constant) meaning
that the implementing the class cannot change them they must be initialize with a
constant value all the variable are implicitly public of the interface, itself, is declared as
a public
2. Method declaration contains only a list of methods without anybody statement and ends
with a semicolon the method are, essentially, abstract methods there can be default
implementation of any method specified within an interface each class that include an
interface must implement all of the method
Need:
Class Interface
It has instance variable. It has final variable.
It has non abstract method. It has by default abstract method.
We can create object of class. We can„t create object of interface.
Class has the access specifiers like public,
Interface has only public access specifier
private, and protected.
Classes are always extended. Interfaces are always implemented.
The memory is allocated for the classes. We are not allocating the memory for the interfaces.
Interface was introduced for the concept of multiple
Multiple inheritance is not possible with classes
inheritance
interface Example
class Example
{
{
int x =5;
void method1()
void method1();
{
void method2();
Body
}
}
void method2()
{
body
}
}
Extending interfaces:-
Like classes, Interfaces can also be extended. That is an interface can be sub-interfaced
from other interfaces. The new sub-interfaced will inherit all the members of the sub-interfaces in
the manner similar to subclasses.
interface A extends B A
{
body of A.
B
}
We can put all the constant in one interface and the methods in the other. This will enable
us to use the constants in the classes where the methods are not required.
E.g
E.g
interface X
{
int cost=100; X Y
String name=”book”;
}
interface Y Z
{
void display();
}
interface Z extends X , Y
{
Implementing interfaces:-
Interfaces are used as “super classes” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
This is done as follows.
E.g.
class A implements B
{
Body of class A;
}
E.g.
class A extends B implements X,Y, .......
{
Body of class A;
}
Interface A class A D
Implementation extension
Class C class C
(a) (b)
class InterfaceDemo
{
Public static void main(String args[ ])
{
Rectangle r = new Rectangle( );
Circle c = new Circle( );
Area a ; // interface object
a = r;
System.out.println(“Area of Rectangle=” +a.Cal(10,20));
a = c;
System.out.println(“Area of Circle=” +a.Cal(10, 0));
}
}
Output :-
C:\java\jdk1.7.0\bin> javac InterfaceDemo.java
C:\java\jdk1.7.0\bin> java InterfaceDemo
Area of Rectangle=200
Area of Circle=314
interface sports
{
int sport_wt=5;
public void disp();
}
class Test
{
int roll_no;
String name;
int m1,m2;
Test (int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
Notes by: - Rajan Shukla
class Result extends Test implements sports
{
Result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);
}
public void disp( )
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
class Demo
{
public static void main(String args[])
{
Result r= new Result(101,"abc",75,75);
r.disp();
}
}
Interfaces can be used to declare a set of constant that can be used in different classes. This
is similar to creating header files in C++ to contain a large no. of constants. The constant values
will be available to any class that implements the interface. The values can be used in declaration,
or anywhere we can use a final value.
E.g.
interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method_B(int s)
{
Nesting of inheritances:-
Interfaces can be nested similar to a class. An interface can be nested within a class and
another interface.
An interface can be declared inside a class body or interface body is called as nesting of
interfaces. The nested interface cannot be accessed directly. To access nested interface, it must be
referred by the outer interface or class.
interface nested_interface_name;
{
}
}
Interface nested_interface_name:
{
}
}
Que. How to achieve multiple inheritance explain with suitable program?
Multiple inheritances:-
It is a type of inheritance where a derived class may have more than one parent class. It is
not possible in case of java as you cannot have two classes at the parent level Instead there can be
one class and one interface at parent level to achieve multiple interface.
Interface is similar to classes but can contain on final variables and abstract method.
Interfaces can be implemented to a derived class.
Class:salary
disp_sal ( ), HRA
interface Gross
{
double TA=800.0;
double DA=3500;
void gross_sal();
}
class Employee
{
String name;
double basic_sal;
Employee(String n, double b)
{
name=n; basic_sal=b;
}
void display()
{
System.out.println("Name of Employee :"+name);
System.out.println("Basic Salary of Employee :"+basic_sal);
}
}
3.2 Packages-
Java provides a mechanism for partitioning the class namespace into more manageable parts
called package (i.e package are container for a classes). The package is both naming and visibility
controlled mechanism.
We can define classes inside a package that are not accessible by code outside that package.
We can also define class members that are only exposed to members of the same package.
The java API provides a no. of classes grouped into different packages according to their
functionality.
Package
Description (Use of Package)
Name
Language support classes. These are classes that java compiler itself uses and
java.lang therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions.
Input/output support classes. They provide facilities for the input and output of
java.io
data
Set of classes for implementing graphical user interface. They include classes for
java.awt
windows, buttons, lists, menus and so on.
Classes for networking. They include classes for communicating with local
java.net
computers as well as with internet servers.
Naming Conventions:-
2) double x= java.lang.Math.sqrt(a);
lang- package name, math- class name, sqrt- method name
1) Declare a package at the beginning of the file using the following form.
package package_name
e.g.
package pkg; - name of package
package is the java keyword with the name of package. This must be the first
statement in java source file.
2) Define a class which is to be put in the package and declare it public like following way.
Package first_package;
Public class first_class
{
Body of class;
}
5) Compile the source file. This creates .class file is the sub-directory. The .class file
must be located in the package and this directory should be a sub-directory where
classes that will import the package are located.
package pkg;
Here, pkg is the name of the package
e.g : package mypack;
Packages are mirrored by directories. Java uses file system directories to store packages.
The class files of any classes which are declared in a package must be stored in a directory which
has same name as package name. The directory must match with the package name exactly.
A hierarchy can be created by separating package name and sub package name by a
period(.) as pkg1.pkg2.pkg3; which requires a directory structure as pkg1\pkg2\pkg3. The classes
and methods of a package must be public.
Accessing a package:-
Syntax:
import pkg1[.pkg2].(classname|*);
Here, “pkg1” is the name of the top level package. “pkg2” is the name of package
is inside the package1 and so on.
import packagename.*;
Access Modifier
Public Private Protected
Access Location
Same class Yes Yes Yes
Subclass in same package Yes No Yes
Other classes in same package Yes No Yes
Subclass in other packages Yes No Yes
Non subclasses in other packages Yes No No
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h));
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
package Area;
public class Rectangle
{
doublelength,bredth;
public doublerect(float l,float b)
{
length=l;
bredth=b;
return(length*bredth);
}
}
import Area.Rectangle;
class RectArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle( );
double area=r.rect(10,5);
System.out.println(“Area of rectangle= “+area);
}
}
Consider the we have package ‘P’ and suppose class B is to be added to following
package.
Package P;
{
Public class X;
{
//body of X;
}
}
4) Compile B.java file. This will create B.class file and place it in the directory P1.
Now, the package “P2” contains both the classes A and B. So to import both classes use
import P1.*
Class:salary
disp_sal ( ), HRA
Types of errors
Example:
class ExError
{
public static void main(String args[])
{
System.out.println(“Preeti Gajjar”) //Missing semicolon
Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the base class of the
hierarchy.
Immediately below Throwable, are two subclasses that partition exceptions into two distinct branches.
o Exception Class :
One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch.
Ex.NullPointerException is an example of such an exception.
o Error Class
Another branch, Error is used by the Java run-time system(JVM) to indicate errors
having to do with the run-time environment itself(JRE).
Ex.StackOverflowError is an example of such an error.
There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked
exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions
are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
o The try statement allows you to define a block of code to be tested for errors while it is being executed.
o The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
o The try and catch keywords come in pairs:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Example:
class TryCatchEx
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int x = a / b; // Arithmetic exception
System.out.println(“Result=” +c);
}
catch(ArithmeticException e)
{
System.out.println(“Caught an exception:” + e.getMessage());
}
System.out.println(“End of the program”); //This line will execute
Output:
throw keyword:
oWe can make a program to throw an exception explicitly using throw statement.
o throw throwableInstance;
othrow keyword throws a new exception.
oAn object of class that extends throwable can be thrown and caught.
oThrowable ->Exception -> MyException
oThe flow of execution stops immediately after the throw statement ;
oAny subsequent statements are not executed. the nearest enclosing try block is inspected to
see if it has catch statement that matches the type of exception.
o If it matches, control is transferred to that statement
o If it doesn‟t match, then the next enclosing try statement is inspected and so on. If no catch
block is matched than default exception handler halts the program.
o Syntax:
throw new thowable_instance;
o Example:
throw new ArithmeticException ();
throw new MyException();
Here ,new is used to construct an instance of MyException().
All java‟s runtime exception s have at least two constructors:
1) One with no parameter
2) One that takes a string parameter.
In that the argument specifies a string that describe the exception. this string is displayed when
object as used as an argument to print() or println() .
It can also obtained by a call to getMessage(),a method defined by Throwable class.
Example:
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":
throws keywords
o The Java throws keyword is used to declare an exception.
o It gives an information to the programmer that there may occur an exception.
o So, it is better for the programmer to provide the exception handling code so that the normal flow of
the program can be maintained.
o Exception Handling is mainly used to handle the checked exceptions.
o If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that
he is not checking the code before it being used.
o Syntax:
return_type method_name() throws exception_class_name{
//method code
}
o Example:
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error");//checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
}
}
Output:
exception handled
normal flow...
finally clause
It can be used to handle an exception that is not caught by any of the previous catch statements.
It can be used to handle any exception generated within a try block.
It may be added immediately after try block or after the last catch block.
finally block is guaranteed to execute if no any exception is thrown.
Use:
1. closing file , record set
2. closing the connection with database
3. releasing system resources
4. releasing fonts
5. Terminating network connections, printer connection etc.
6.
We can use finally in this two way.
Syntax:1
try
{
…………..
}
finally
{
……………...
}
Syntax:2
try
{
………..
}
catch(…….)
{
…………….
}
catch (…….)
{
………..
}
finally
{
Page 9
Unit No: 04
……………
}
Example:
class finallyEx {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e) {
System.out.println("Something went wrong.");
}
finally {
System.out.println("The 'try catch' is finished.");
}
}
}
Output:
Something went wrong.
The 'try catch' is finished.
Uses of exceptions
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Example:
{
rollno = a ;
}
public String toString()
{
return “MyException[” + rollno + “] is less than zero”;
}
}
class Student
{
Static void sum(int a, int b) throws std
{
if(a<0)
{
throw new std(a); //throws user defined exception object
}
else
{
System.out.println(a+b);
}
}
public static void main(String[] args)
{
try
{
sum(-10,10);
}
catch(std me)
{
System.out.println(me);
}
}
}
Output:
Page 11
Unit No: 04
Concept of Multithreading
Multithreading is a conceptual programming paradigm where a program (or process) is divided
into two or more subprograms(or process),which can be implemented at the same time in parallel.
Threads in java are subprograms of main application program and share the same memory space.
Multithreading is similar to dividing a task into subtasks and assigning them to different people
for execution independently and simultaneously, to achieve a singledesire.
We use multithreading than multiprocessing because threads use a shared memory area.
It is mostly used in games, animation, etc.
Page 12
Unit No: 04
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Concept of thread
A thread is executed along with its several operations within a single process as shown in figure below:
Single Process
Operation 1
Thread 1
Operation 2
…….
Operation N
A multithreaded programs contain two or more threads that can run concurrently.
Threads share the same data and code.
Page 13
Unit No: 04
MultiThreading Concept
Thread 1 Thread 2
Operation 1
Operation 1
Operation 2 Operation 2
…….
…….
Operation N
Operation N
Creating thread
To execute a thread, it is first created and then start() method is invoked on the thread. Then thread would
execute and run method would be invoked.
Page 14
Unit No: 04
Page 15
Unit No: 04
During the life time of a thread ,there are many states it can enter, They are:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
A thread is always in one of these five states. It can move from one state to another via a variety of ways.
Page 16
Unit No: 04
3) Running state
The processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread.
A running thread may change its state to another state in one of the following situations.
1) When It has been suspended using suspend( ) method.
2) It has been made to sleep( ).
3) When it has been told to wait until some events occurs.
4) Blocked state/ Waiting
• A thread is waiting for another thread to perform a task. The thread is still alive.
• A blocked thread is considered “not runnable” but not dead and so fully qualified to run again.
5) Dead state/ Terminated
• Every thread has a life cycle. A running thread ends its life when it has completed executing its
run ( ) method.
• It is natural death. However we can kill it by sending the stop message.
• A thread can be killed as soon it is born or while it is running or even when it is in “blocked”
condition.
Thread class’s methods:
Page 17
Unit No: 04
Thread priority
Every thread in java has its own priority.
Thread priority are used by thread scheduler to decide when each thread should be allowed to run.
In Java, thread priority ranges between:
o MIN-PRIORITY( a contant of 1 )
o MAX-PRIORITY( a contant of 10 )
o NORM-PRIORITY (a contant of 5) , it is default.
Example:
Page 18
Unit No: 04
When we create a thread start() method performs some internal process and then calls run() method.
The start() method does not start another thread of control but run() is not really “main” method of new
thread.
All uncaught exceptions are handled by code outside the run() method before the thread terminates.
It is possible for a program to write a new default exception handler.
The default exception handler is the uncaughtException method of the Thread group class.
Whenever uncaught exception occurs in thread’s run method, we get a default exception dump which gets
printed on System.err stream.
Example:
class MyThread extends Thread{
public void run(){
System.out.println("Throwing in " +"MyThread");
throw new RuntimeException();
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
try {
Thread.sleep(1000);
} catch (Exception x) {
System.out.println("Caught it" + x);
}
System.out.println("Exiting main");
}
}
Output:
Throwing in MyThread
Exception in thread "Thread-0" java.lang.RuntimeException
at testapp.MyThread.run(Main.java:19)
Exiting main
Page 19
Topic 5
Java Applets & Graphics Programming
Total Marks- 20
Specific Objectives:
The students will be able to write interactive applets and make use of graphics in
programming.
They will also learn to change the background and the foreground color and to use the
different fonts.
Contents:
5.1 Introduction to applets Applet, Applet life cycle (skeleton), Applet tag, Adding Applet
To HTML file, passing parameter to applet, embedding <applet>tags in java code, adding
controls to applets.
5.2 Graphics Programming Graphics classes, lines, rectangles, ellipse, circle, arcs,
polygons, color & fonts, setColor(), getColor(), setForeGround(), setBackGround(), font
class, variable defined by font class: name, pointSize, size, style, font methods: getFamily(),
getFont(), getFontname(), getSize(), getStyle(), getAllFonts() &
getavailablefontfamilyname() of the graphics environment class.
5.1.Introduction to applets
Applet Basics-
Basically, an applet is dynamic and interactive java program that inside the web
page or applets are small java programs that are primarily used in internet computing. The
java application programs run on command prompt using java interpreter whereas
the java applets can be transported over the internet form one computer to another and run
using the appletviewer or any web browser that supports java.
An applet is like application program which can perform arithmetic
operations, display graphics, play sounds accept user input, create animation and
play interactive games. To run an applet, it must be included in HTML tags for web page.
Web browser is a program to view web page.
Every applet is implemented by creating sub class of Applet class.
Following diagram shows the inheritance hierarchy of Applet class.
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Fig. Chain of classes inherited by Applet class in java
5.1.1 Differentiate between applet and application (4 points). [W-14, S-15, W-15 ]
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language
Applet enters the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. start() can also
be called if the applet is already in idle state. start() may be called more than once.
start() method may be overridden to create a thread to control the applet.
APPLET Tag:
The APPLET tag is used to start an applet from both an HTML document and
from an applet viewer.
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]>
[< PARAM NAME = AttributeName1 VALUE = AttributeValue>]
[<PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
CODE is a required attribute that give the name of the file containing your applet‟s
compiled class file which will be run by web browser or appletviewer.
ALT: Alternate Text. The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.
NAME is an optional attribute used to specifies a name for the applet instance.
WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the
applet display area.
VSPACE AND HSPACE attributes are optional, VSPACE specifies the space, in
pixels, about and below the applet. HSPACE VSPACE specifies the space, in
pixels, on each side of the applet
PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with the
get Parameter()method.
Example
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM…> tag
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
Graphics can be drawn with the help of java. java applets are written to
draw lines, figures of different shapes, images and text in different styles even
with the colours in display.
Every applet has its own area of the screen known as canvas, where it creates the
display in the area specified the size of applet‘s space is decided by the attributes of
<APPLET...> tag.
A java applet draws graphical image inside its space using the coordinate system
shown in following fig., which shows java‘s coordinate system has the origin (0, 0) in
the upper-left corner, positive x values are to be right, and positive y values are to the
bottom. The values of coordinates x and y are in pixels.
X
(0, 0)
1. Write a java applet code and save it with as a class name declared in a program by
extension as a .java.
e.g. from above java code file we can save as a Welcome.java
3. After successfully compiling java file, it will create the .class file, e.g
Welcome.class. then we have to write applet code to add this class into applet.
4. Applet code
<html>
<Applet code= ― Welcome.class‖ width= 500 height=500>
</applet>
</html>
5. Save this file with Welcome.html in ‗bin‘ library folder.
The Graphics class of java includes methods for drawing different types
of shapes, from simple lines to polygons to text in a variety of fonts.
Method Description
clearRect( ) Erases a rectangular area of the canvas
copyArea( ) Copies a rectangular area of the canvas to another area
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line
drawOval( ) Draws a hollow oval
drawPolygon( ) Draws a hollow polygon
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled arc
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing color
setFont( ) Seta fonts.
Displaying String:
drawString() method is used to display the string in an applet window
Syntax:
void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example:
g.drawString(―WELCOME‖, 10, 10);
5.2.3.1. drawLine( )
The drawLine ( ) method is used to draw line which takes two pair
of
coordinates (x1,y1) and (x2, y2) as arguments and draws a line between
them. The graphics object g is passed to paint( ) method.
The syntax is
g.drawLine(x1,y1,x2,y2);
e.g. g.drawLine(20,20,80,80);
Syntax: void drawRect(int top, int left, int width, int height)
This method takes four arguments, the first two represents the x and y
co- ordinates of the top left corner of the rectangle and the remaining two represent the
width and height of rectangle.
Example: g.drawRect(10,10,60,50);
Q. Design an Applet program which displays a rectangle filled with red color
and message as “Hello Third year Students” in blue color. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
Syntax: void drawOval( int top, int left, int width, int height)
Example: g.drawOval(10,10,50,50);
Syntax- void fillOval(int top, int left, int width, int height):
Example g.fillOval(10,10,50,50);
Q. Write a simple applet program which display three concentric circle. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
(OR)
HTML Source:
<html> <applet code=‖CircleDemo.class‖ height=300 width=200>
</applet>
</html>
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
Output
Example:
g.drawArc(10, 10, 30, 40, 40, 90);
g.drawPolygon(x, y, n);
Q. Write the syntax and example for each of following graphics methods:
1) drawPoly ( ) 2) drawRect ( ) 3) drawOval ( ) 4) fillOval ( )
For syntax refer above 5.2.3.2 and all........
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400>
</applet>*/
void setBackground(Color.newColor)
where newColor specifies the new color. The class color defines the constant
for specific color listed below.
setForeground (Color.yellow);
The following methods are used to retrieve the current background and foreground
color.
Color getBackground( )
Color getForeground( )
A font determines look of the text when it is painted. Font is used while painting text
on a graphics context & is a property of AWT component.
Variable Meaning
String name Name of the font
float pointSize Size of the font in points
int size Size of the font in point
int style Font style
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
To select a new font, you must first construct a Font object that describes that
font. Font constructor has this general form:
fontName specifies the name of the desired font. The name can be specified
using either the logical or face name.
All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, Monospaced, and Symbol. Dialog is the
font used by once system‟s dialog boxes.
Dialog is also the default if you don‟t explicitly set a font. You can also use
any other fonts supported by particular environment, but be careful—these other fonts
may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of
these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR
them together.
For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
Q. Describe any three methods of font class with their syntax and example
of each. [W-14, S-15 ]
Sr.
Methods Description
No
1 static Font decode(String str) Returns a font given its name.
boolean equals(Object Returns true if the invoking object contains the
2 same font as that specified by FontObj.Otherwise,
FontObj) :
it returns false.
3 String toString( ) Returns the string equivalent of the invoking font.
4 Returns the name of the font family to which the
String getFamily( )
invoking font belongs.
static Font getFont(String Returns the font associated with the system
property specified by property. null is returned if
5 property)
property does not exist.
Returns the font associated with the System
6 static Font getFont(String property specified by property.
property,Font defaultFont)
The font specified by defaultFont is returned if
property does not exist.
7 String getFontName( ) Returns the face name of the invoking font.
8 String getName( ) Returns the logical name of the invoking font.
Example:-
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
Q. Write method to set font of a text and describe its parameters. [S-16]
The AWT supports multiple type fonts emerged from the domain of traditional
type setting to become an important part of computer-generated documents and
displays. The AWT provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts.
Fonts have a family name, a logical font name, and a face name. The family
name is the general name of the font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name specifies a specific font, such as
Courier Italic To select a new font, you must first construct a Font object that
describes that font.
One Font constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
Syntax:
public abstract String[ ] getAvailableFontFamilyNames(Locale 1)
Parameters:
l - a Locale object that represents a particular geographical, political, or
cultural region. Specifying null is equivalent to specifying Locale.getDefault().
Or
String[ ] getAvailableFontFamilyNames( )
It will return an array of strings that contains the names of the available font families
Important Questions:-
4 Marks Questions:-
1) Write syntax and example of 1) drawString ( ) 2) drawRect ( ) ; 3) drawOval ( )
4) drawArc ( ).
2) Describe following states of applet life cycle : a) Initialization state. b) Running state.
c) Display state
3) State the use of font class. Describe any three methods of font class with their syntax
and example of each.
4) Differentiate applet and application with any four points.
5) State syntax and explain it with parameters for : i)drawRect ( ) ii) drawOral ( )
6) Design an Applet program which displays a rectangle filled with red color and
message as ―Hello Third year Students‖ in blue color.
7) Describe applet life cycle with suitable diagram.
8) Differentiate between applet and application (any 4 points).
9) Write a program to design an applet to display three circles filled with three different
colors on screen.
10) Explain all attributes available in < applet > tag.
1. What are stream classes ? List any two input stream classes from character stream
[S-15, S-16]
Definition:
The java. IO package contain a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two
groups based on the data type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode
characters. There are two kinds of character stream classes, namely, reader stream classes
and writer stream classes
2. What are streams ? Write any two methods of character stream classes. [W-15]
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system.
All streams behave in the same manner, even if the actual physical devices
to which they are linked differ. Thus, the same I/O classes and methods can be applied to
any type of device.
Java 2 defines two types of streams: byte and character.
Byte streams provide a convenient means for handling input and output of bytes.
Byte streams are used, for example, when reading or writing binary data.
Character streams provide a convenient means for handling input and output
of characters.
They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams.
Writer Class
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error
2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers.
3) void write(intch): Writes a single character to the invoking output stream. Note that the
parameter is an int, which allows you to call write with expressions without having to cast
them back to char.
5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking output
stream.
7) void write(String str, int offset,int numChars): Writes a sub range of numChars
characters from the array str, beginning at the specified offset.
2. public int read(char[ ] cbuf, int offset, int length) throws IOException -
Reads characters into a portion of an array.
3. public void close()throws IOException - Closes the stream and releases any
system resources associated with it. Once the stream has been closed, further
read(), ready(), mark(), reset(), or skip() invocations will throw an IOException.
Closing a previously closed stream has no effect
6. public void reset()throws IOException - Resets the stream. If the stream has been
marked, then attempt to reposition it at the mark. If the stream has not
been marked, then attempt to reset it in some way appropriate to the particular
stream, for example by repositioning it to its starting point. Not all character-input
streams support the reset() operation, and some support reset() without supporting
mark().
4. Write any two methods of File and FileInputStream class each.[S-15, W-15]
1. int available( )- Returns the number of bytes of input currently available for
reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream
that will remain valid until numBytes bytes are read.
4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. –1
is returned when the end of the file is encountered.
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. –1 is returned when the end of
the file is encountered.
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area, such
as a file. At a later time, you may restore these objects by using the process of
deserialization.
Example:
Assume that an object to be serialized has references to other objects, which,
inturn, have references to still more objects. This set of objects and the
relationships among them form a directed graph. There may also be circular
references within this object graph. That is, object X may contain a reference to
object Y, and object Y may contain a reference back to object X. Objects may also
contain references to themselves. The object serialization and deserialization facilities
have been designed to work correctly in these scenarios. If you attempt to serialize an
object at the top of an object graph, all of the other referenced objects are recursively
located and serialized. Similarly, during the process of deserialization, all of these objects
and their references are correctly restored.
import java.io.*;
class CopyData
{
public static void main(String args[ ])
{
//Declare input and output file stream
byte byteRead;
try
{
// connect fis to in.dat
fis=new FileInputSream(―in.dat‖);
// connect fos to out.dat
fos= new FileOutputStream(―out.dat‖);
//reading bytes from in.dat and write to out.dat
do
{
byteRead =(byte)fis.read( );
fos.write(byteRead);
}
while(byteRead != -1);
}
Catch(FileNotFoundException e)
{
System.out.println(―file not found‖);
}
Catch(IOException e)
{
System.out.pritln(e.getMessage( ));
}
finally // close file
{
fis.close( );
fos.close( );
}
Catch(IOException e)
{ }
}
}
}
7. What is use of ArrayList Class ? State any three methods with their use from
ArrayList.[W-15, S-16]
1. void add(int index, Object element) Inserts the specified element at the specified
position index in this list. Throws IndexOutOfBoundsException if the specified index
is is out of range (index < 0 || index >size()).
2. boolean add(Object o) Appends the specified element to the end of this list.
9. Object get(int index) Returns the element at the specified position in this
list. Throws IndexOutOfBoundsException if the specified index is is out of range
(index <
0 || index >= size()).
10. intindexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
11. intlastIndexOf(Object o) Returns the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this element.
12. Object remove(int index) Removes the element at the specified position in this
list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >=
size()).
14. Object set(int index, Object element) Replaces the element at the
specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).
16. Object[ ] toArray() Returns an array containing all of the elements in this list in
the correct order. Throws NullPointerException if the specified array is null.
18. void trimToSize() Trims the capacity of this ArrayList instance to be the
list's current size.
ii. getDate()
Syntax:
public int getDate()
Returns the day of the month. This method assigns days with the values of
1 to 31.
1. setTime():
2.getDay()
int getDay():
Returns the day of the week represented by this date.
The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 =
Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or
begins with the instant in time represented by this Date object, as interpreted in the
local time zone.
2) max() :
Syntax: static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt()
Syntax: static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double
4) pow() :
Syntax: static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the
second argument.
5) exp()
Syntax: static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round() :
Syntax: static int round(float a)
Use : This method returns the closest int to the argument.
7) abs()
Syntax: static int abs(int a)
Use : This method returns the absolute value of an int value.
import java.util.*;
public class SetDemo
{
public static void main(String args[])
{
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e){}
}
}
12. State syntax and describe any two methods of map class.[S-16]
The Map Classes Several classes provide implementations of the map interfaces. A
map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects. The keys must be
unique, but the values may be duplicated. Some maps can accept a null key and
null values, others cannot.
Methods:
void clear // removes all of the mapping from map
booleancontainsKey(Object key) //Returns true if this map contains a mapping for the
specified key.
Boolean conainsValue(Object value)// Returns true if this map maps one or more keys to
the specified value
Boolean equals(Object o) //Compares the specified object with this map for equality