Java Material
Java Material
2020 – 21
L T P C
II Year – II Semester
3 0 0 3
JAVA PROGRAMMING
Course Objectives:
The learning objectives of this course are:
To identify Java language components and how they work together in applications
To learn the fundamentals of object-oriented programming in Java, including defining
classes, invoking methods, using class libraries.
To learn how to extend Java classes with inheritance and dynamic binding and how to
use exception handling in Java applications
To understand how to design applications with threads in Java
To understand how to use Java APIs for program development
Course Outcomes:
Able to realize the concept of Object Oriented Programming & Java Programming
Constructs
Able to describe the basic concepts of Java such as operators, classes, objects,
inheritance, packages, Enumeration and various keywords
Apply the concept of exception handling and Input/ Output operations
Able to design the applications of Java & Java applet
Able to Analyze & Design the concept of Event Handling and Abstract Window
Toolkit
UNIT I
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens
in Java Programs, Java Statements, Command Line Arguments, User Input to Programs,
Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods,
Attribute Final, Introduction to Operators, Precedence and Associativity of Operators,
Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -)
Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise
Logical Operators.
R-20 Syllabus for CSE, JNTUK w. e. f. 2020 – 21
UNIT II
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value
and by Reference, Keyword this.
UNIT III
Arrays: Introduction, Declaration and Initialization of Arrays, Storage of Array in Computer
Memory, Accessing Elements of Arrays, Operations on Array Elements, Assigning Array to
Another Array, Dynamic Change of Array Size, Sorting of Arrays, Search for Values in
Arrays, Class Arrays, Two-dimensional Arrays, Arrays of Varying Lengths, Three-
dimensional Arrays, Arrays as Vectors.
UNIT IV
Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes
into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package
and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and
Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class, Time
Package, Class Instant (java.time.Instant), Formatting for Date/Time in Java, Temporal
Adjusters Class, Temporal Adjusters Class.
UNIT V
String Handling in Java: Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings, Methods for Comparison of Strings, Methods for
Modifying Strings, Methods for Searching Strings, Data Conversion and Miscellaneous
Methods, Class String Buffer, Class String Builder.
Text Books:
UNIT-1
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or Tokens
in Java Programs, Java Statements, Command Line Arguments, User Input to Programs,
Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic
Constants, Formatted Output with printf() Method, Static Variables and Methods, Attribute
Final, Introduction to Operators, Precedence and Associativity of Operators, Assignment
Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -) Operators,
Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise Logical
Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,
Ternary Operator?:, Switch Statement, Iteration Statements, while Expression, do–while
Loop, for Loop, Nested for Loop, for–Each for Loop, Break Statement, Continue Statement.
INTRODUCTION TO JAVA:
Features of Java:
Platform Independence: Java works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.) and Programs developed in JAVA are executed anywhere on any
system.
Simple: They made java simple by eliminating difficult concepts of C and C++.
example the concept of pointers and Java is simple because it has the same syntax of C
and C++
Object Oriented: Object oriented throughout - no coding outside of class definitions,
including main ().
2. Identifiers: Identifiers used for naming classes, methods, variables, objects, labels
and interfaces in a program.
Java identifiers follow the following rules:
Examples of legal and illegal identifiers follow, first some legal identifiers:
int _a;
int $c;
int 2_w;
int _$;
int this_is_a_very_detailed_name_for_an_identifier;
The following are illegal (Recognize why):
int :b;
int -d;
int e#;
int .f;
JAVA PROGRAMMING II B. TECH II SEMESTER
2. All classes and interfaces should start with capital letter, for more then one word
the second word’s first character should be capital.
Ex:- Student, HelloJava
3. Constant variables should be in capital letters and for more than one word
underscore is used.
Ex:- MAX, TOTAL_VALUE
3. Special Symbols: The following special symbols are used in Java having
somespecial meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Braces{}: These opening and ending curly braces marks the start and end of a
block of code containing more than one executable statement.
comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
semi colon : It is an operator that essentially invokes something called an
initialization list.
asterick (*): It is used to create pointer variable.
assignment operator: It is used to assign values.
Operators: Java provides many types of operators which can be used according to the need.
They are classified based on the functionality they provide. Some of the types are-
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator(conditional operator)
Bitwise Operators and bit-shift operators
instance of operator
JAVA PROGRAMMING II B. TECH II SEMESTER
Documentation section:
It consists of comment lines(program name, author, date,…….),
// - for single line comment.
/*--- */ - multiple line comments.
/** -- */ - known as documentation comment, which generated documentation automatically.
Package statement:
This is the first statement in java file. This statement declares a package name and informs
the compiler that the class defined here belong to this package.
Ex: - package student
Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import java. lang. String
The above statement instructs the interpreter to load the String class from the lang package.
Note:
Import statement should be before the class definitions.
A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method
declarations. Note: Methods in interfaces are not defined just declared.
Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A
programcan have multiple class definitions.
Class Sample:
The keyword class is used to declare a class and Sample is the JAVA identifier ie name of the
class.
String args[]:
Any information that you pass to a method is received by variables specified with in the set of
parenthesis that follow the name of the method. These variables are called parameters. Here
args[] is the name of the parameter of string type.
JAVA PROGRAMMING II B. TECH II SEMESTER
System.out.println:
It is equal to printf() or cout<<, since java is a true object oriented language, every method
must be part of an object.
The println method is a member of out object, which is a static data member of System class.
Note: println always appends a newline character to the end of the string. So the next println
prints the statements in next line.
Important Note:
If the source code file name is Test.java and the class name is Hello, then to compile the
program we have to give.
C:> Javac Test.java ( which creates a Hello.class file )
How it works…!
Compile-time Environment Run-time Environment
Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java Java
Time
Bytecodes Interpreter Java
Compiler
move locally Virtual
or through machine
Java network
Compiler
Runtime System
JAVA STATEMENTS:
A statement specifies an action in a Java program.
Java statements can be broadly classified into three categories:
Declaration statement
Expression statement
Control flow statement
For example,
int num;
int num2 = 100;
String str;
JAVA PROGRAMMING II B. TECH II SEMESTER
All of these are possible in Java using flow control statements. The if statement, while
loop statement and for loop statement are examples of control flow statements.
Example 1:
class Commarg
{
public static void main(String args[])
{
int i=0,l;
l=args.length;
System.out.println("Number of arguments are:"+l);
while(i<l)
{
System.out.println(args[i]);
i++;
}
}
}
Ex:
C:..\> java Commarg hello how are u
JAVA PROGRAMMING II B. TECH II SEMESTER
output:
number of arguments are : 4
hello
how
are
u
Note: From the above output it is clear that hello is stored at args[0]
Position and so on…..
Example-2:
Program to add two no’s using command line arguments.
class CmdAdd2
{
public static void main(String args[])
{
// if two arguments are not entered then come out
if(args.length!=2)
{
System.out.println("Please enter two values. .. ");
return;
}
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println("The Result is:"+c);
}
}
To run the program:
> java CmdAdd2 10 20
The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class.
For Example, we will use the nextLine() method to read String.
Example:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = s.nextLine();
// Numerical input
int age = s.nextInt();
double salary = s.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
JAVA COMMENTS:
Comments can be used to explain Java code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).
This example uses a single-line comment before a line of code:
Example :
// This is a comment
System.out.println("Hello World");
code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
JAVA VARIABLES:
Declaring (Creating) Variables: To create a variable, you must specify the type and assign
it avalue
Syntax: type variable = value;
Where type is one of Java's types (such as int or String), and variable is the name of
the variable (such as any identifier). The equal sign is used to assign values to the variable.
In Java, there are different types of variables, for example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
JAVA PROGRAMMING II B. TECH II SEMESTER
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
boolean - stores values with two states: true or false
Example:
int num = 5;
float num1 = 5.99f;
char ch = 'D';
boolean status = true;
String name = "sai";
Declare Many Variables: To declare more than one variable of the same type, use a comma-
separated list:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
DATA TYPES IN JAVA: Datatype specifies the size and types of values that a
variable hold. Java is rich in it’s data types.
JAVA PROGRAMMING II B. TECH II SEMESTER
Primitive Data Types: A primitive data type specifies the size and type of variable
values, and it has no additional methods.
Note 1: Note that you should end the value with an "f"
Note 2: Note that you should end the value with a "d"
Example:
int num = 5;
float num1 = 5.99f;
double num3=5.7896d;
char ch = 'D';
boolean status = true;
String name = "sai";
System.out.println("Value inside integer type variable " + num);
System.out.println("Value inside float type variable " + num1);
System.out.println("Value inside double type variable " + num1);
System.out.println("Value inside character type variable " + ch);
System.out.println("Value inside boolean type variable " + status);
System.out.println("Value inside string type variable " + name);
Type casting: Converting one datatype into another type is called “Type casting”.
JAVA PROGRAMMING II B. TECH II SEMESTER
Data types:
There are two types of data types.
primitive data types or Fundamental data types.
o These data types will represent single entity (or value).
o Ex : int, char, byte,…….
Referenced Data types or Advanced Data types.
o These Data types represent several values.
o Ex: arrays, classes, enums,…
Note: We can convert a primitive type to another primitive type and a Referenced type to
another Referenced type, but to convert Primitive type to Referenced type and Referenced
type to Primitive type Wrapper classes are used.
Widening primitive data types: Converting lower data type into higher data type is called
widening.
byte, short, char, int, long, float
double Lower higher
Ex 1:
char ch=’A’;
int no=ch;
Ex 2:
int x=5000;
float sal=x;
widening is also known as implicit casting.
Narrowing implicit Data types:
Converting higher data type into lower data type is called narrowing.
Ex 1:
int n=65;
char ch=(char)n;
... here ch will contain A
Ex 2:
double d=12.890;
JAVA PROGRAMMING II B. TECH II SEMESTER
int x=(int)d;
.. here x will contain 12
narrowing is unsafe because there will be loss of data or precision or accuracy. So narrowing
is not done by compiler automatically. The programmer has to use cast operator explicitly.
Narrowing is also called Explicit casting.
Static methods:
A static method is a method that does not act upon instance variables of a class.
A static method is declared by using the keyword static.
Static methods are called using classname.methodName()
The reason why static methods cannot act on instance variables is that JVM first loads
static elements of the .class file one specific memory location inside the RAM and
then searches for the main method, and then only it creates the objects.
Since objects are not available at the time calling static methods, the instance
variables are also not available at the time of calling the static methods.
Static methods are also called as class methods.
They cannot refer to this or super keywords (super used in inheritance)
Example:
class Smethod
{
static void disp()
{
System.out.println("Hi... ");
}
public static void main(String args[])
{
disp();
disp();
disp();
}
}
Static variable:
The variables that are created comman to all the objects are called static
variables/class variables.
The static variables belong to the class as a whole rather than the objects.
It is mainly used when we need to count no of objects created for the class
Example: Count
class emp
{
int eno;
String name;
static int count; No- 101 No- 102
Name-tanu Name-man
JAVA PROGRAMMING II B. TECH II SEMESTER
To format and display the output, printf() method is available in PrintStream class.
This method works similar to printf() function in C.
Note: printf() is also available from J2SE 5.0 or later.
The following format characters can be used in printf():
%s – String
%c – char
%d – decimal integer
%f – float number
%o – octal number
%b, %B – Boolean value
%x, %X – hexadecimal value
%e, %E – number scientific notation
%n – new line character
Example :
class PrintfDemo
{
public static void main(String[] args)
{
String s="sai";
int n=65;
float f=15.45f;
System.out.printf(" String =%s %n number=%d %n HexaDecimal=%x %n
Float=%f",s,n,n,f);
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
Attribute Final:
Final variables: It is just like const in c/c++, which restricts the user to modify. The value
offinal variable is finalized at the time of declaration it self.
Ex:
final double PI=3.14
example:
class Final
{
public static void main (String args[])
{
final int a=10;
System.out.println("before modification:"+a);
a=a+10; //Error: cannot assign a value to final variable a a=a+10;
System.out.println("after modification:"+a);
}
}
For-each loop:
The enhanced for loop, new to java 5, is a specialized for loop that simplifies looping
through an array or a collection.
Syntax:
for(declaration: expression)
{
---
---
}
Declaration: Its Data type should be same as the current array element.
Expression: It should be the array variable
Example:
class Loop
{
public static void main(String args[])
{
int x[]= {10,20,30,40,50};
float y[]={1.5f,2.5f,3.5f,4.5f,5.5f};
String names[]={"vahida","madhuri","lalitha","anil","manik"};
for(int i:x)
{
System.out.println(i);
}
for(float j:y)
JAVA PROGRAMMING II B. TECH II SEMESTER
{
System.out.println(j);
}
for(String s:names)
{
System.out.println(s);
}
}
}
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
JAVA PROGRAMMING II B. TECH II SEMESTER
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
if(condition)
{
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
JAVA PROGRAMMING II B. TECH II SEMESTER
else{
statement 2; //executes when condition is false
}
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the program
may enter in the block of code where the condition is true. We can also define an else statement at the
end of the chain.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
Student.java
JAVA PROGRAMMING II B. TECH II SEMESTER
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Student.java
3. if(address.endsWith("India")) {
4. if(address.contains("Meerut")) {
5. System.out.println("Your city is Meerut");
6. }else if(address.contains("Noida")) {
7. System.out.println("Your city is Noida");
8. }else {
9. System.out.println(address.split(",")[0]);
10. }
11. }else {
12. System.out.println("You are not living in India");
13. }
14. }
15. }
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
JAVA PROGRAMMING II B. TECH II SEMESTER
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
Output:
While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
JAVA PROGRAMMING II B. TECH II SEMESTER
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
Output:
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
Output:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while
loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.
JAVA PROGRAMMING II B. TECH II SEMESTER
1. while(condition) {
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Calculation .java
Output:
0
2
4
6
8
10
JAVA PROGRAMMING II B. TECH II SEMESTER
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
Output:
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
Output:
0
1
2
3
4
JAVA PROGRAMMING II B. TECH II SEMESTER
5
6
Calculation.java
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
1. public class ContinueExample {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. for(int i = 0; i<= 2; i++) {
5. for (int j = i; j<=5; j++) {
6. if(j == 4) {
7. continue;
JAVA PROGRAMMING II B. TECH II SEMESTER
8. }
9. System.out.println(j);
10. }
11. }
12. }
13. }
JAVA PROGRAMMING II B. TECH II SEMESTER
Output:
0
1
2
3
5
1
2
3
5
2
3
5
JAVA PROGRAMMING II B. TECH II SEMESTER
UNIT II
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members,
Declaration of Class Objects, Assigning One Object to Another, Access Control for Class
Members, Accessing Private Members of Class, Constructor Methods for Class, Overloaded
Constructor Methods, Nested Classes, Final Class and Methods, Passing Arguments by Value
and by Reference, Keyword this.
Class:
A class is the blueprint from which individual objects are created.
This means the properties and actions of the objects are written in the class.
VariableDeclaration-n;
Object:
Object is an entity of a class.
Object Creation Syntax:
ClassName objectName=new className ();
JAVA PROGRAMMING II B. TECH II SEMESTER
Class Members:
All the variable declared and method defined inside a class are called class members.
Instance variables:
The variables defined within a class are called instance Variables (datamembers).
Methods:
The block in which code is written is called method (member functions).
Instance variables:
Instance variables are declared inside a class. Instance variables are created when the
objects are instantiated (created). They take different values for each object.
Class variables:
Class variables are also declared inside a class. These are global to a class. So these
are accessed by all the objects of the same class. Only one memory location is created for a
class variable.
Local variables:
Variables which are declared and used with in a method are called local variables.
Parameters:
Variables that are declared in the method parenthesis are called parameters.
class Test
{ int a; //default access
void setData(int i)
{
a=i;
}
int dispData()
{
return a;
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test(); //object creation
ob.setData(100);
System.out.println(" value of a is:-”+ob.dispData());
}
}
Public:
If the members of a class are declared as public then the members (variables/methods) are
accessed by outside of the class.
Private:
If the members of a class are declared as private then only the methods of same class can
access private members (variables/methods).
Protected:
Discussed later at the time of inheritance.
Default access:
If the access specifier is not specified, then the scope is friendly. A class, variable, or method
that has friendly access is accessible to all the classes of a package (A package is collection
of classes).
Example:
class Test
{
int a; //default access
public int b; // public access
private int c; // private access
//methods to access c
void setData(int i)
{
}
int dispData()
{
JAVA PROGRAMMING II B. TECH II SEMESTER
} c=i;
}
return c;
class AccessTest
{
public static void main(String args[])
{
Test ob=new Test();
//a and b can be accessed directly
ob.a=10;
ob.b=20;
// c can not be accessed directly because it is private
//ob.c=100; // error
// private data must be accessed with methods of the same class
ob.setData(100);
System.out.println(" value of a, b and c are:"+ob.a+" "+ob.b+"
"+ob.dispData());
ob.dispData();
}
}
Assigning One Object to Another or Cloning of objects:
We can copy the values of one object to another using many ways like :
Example:
class Copy
{
int a=10;
}
class CopyObject
{
public static void main(String args[])
{
Copy c1=new Copy();
Copy c2=c1;
System.out.println("object c1 value-"+c1.a);
System.out.println("object c2 value-"+c2.a);
}
JAVA PROGRAMMING II B. TECH II SEMESTER
}
Constructors:
1. JAVA provides a special method called constructor which enables an object to
initialize itself when it is created.
2. Constructor name and class name should be same.
3. Constructor is called automatically when the object is created.
4. Person p1=new Person() invokes the constructor Person() and Initializes the
Person object p1.
5. Constructor does not return any return type (not even void).
There are two types of constructors.
Default constructor: A constructor which does not accept any parameters.
Parameterized constructor:A constructor that accepts arguments is called parameterized
constructor.
Default constructor Example:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle() // Default Constructor method
{
System.out.println("Constructing Rectangle..");
length=10;
bredth=20;
}
int rectArea()
{
return(length*bredth);
}
}
class Rect_Defa
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
System.out.println("Area of rectangle="+r1.rectArea());
}
}
Note: If the default constructor is not explicitly defined, then system default constructor
automatically initializes all instance variables to zero.
Parameterized constructor:
class Rectangle
{
int length,bredth; // Declaration of variables
Rectangle(int x,int y) // Constructor method
{
length=x;
bredth=y;
}
int rectArea()
{
return(length*bredth);
JAVA PROGRAMMING II B. TECH II SEMESTER
}
}
class Rect_Para
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(5,10);
System.out.println("Area of rectangle="+r1.rectArea());
}
}
Writing more than one constructor with in a same class with different parameters is
called constructor overloading.
Example:
class Addition
{
int a,b;
Addition()
{
a=10;
b=20;
}
Addition(int a1,int b1)
{
a=a1;
b=b1;
}
void add()
{
System.out.println("Addition of "+a+" and "+b+" is "+(a+b));
}
}
class ConsoverLoading
{
JAVA PROGRAMMING II B. TECH II SEMESTER
{
System.out.println(data);
}
}
Local l=new Local();
l.msg();
}
public static void main(String args[]){
localInner1 obj=new localInner1();
obj.display();
}
}
{
sample();
System.out.println("I am outer class varible:"+a);
}
}
}
class StaticInnerClass
{
public static void main(String args[])
{
Outer.Inner m=new Outer.Inner();
System.out.println("I am Inner class varible:"+m.b);
m.display();
}
}
Syntax:
final class A
{
}
class B extends A // cannot be inherited
{ ---
Final Method:
To prevent method riding final keyword is used.
Methods declared as final cannot be overridden.
class A
{
int a=10;
final void display()
{
System.out.println("I am display() of class-A");
System.out.println("my value is:"+a);
}
}
class B extends A
{
int b=20;
void display() //can’t be overriden
{
System.out.println("I am display() of class-B");
System.out.println("my value is:"+b);
}
}
class Final_Methods_Classes
{
public static void main(String args[])
{
B b=new B();
b.display();
}
}
{
public static void main(String args[]) //calling function
{
Example e=new Example();
System.out.println("a value before calling change() :"+e.a); //10
e.change(10); //call by value(passing primitive data type)
System.out.println("a value after calling change() :"+e.a); //10
}
}
‘this’ keyword:
‘this’ is a keyword that referes to the object of the class where it is used.
When an object is created to a class, a default reference is also created internally to
the object.
JAVA PROGRAMMING II B. TECH II SEMESTER
class Sample
{
private int x;
Sample()
{
this(10); // calls parameterized constructor and sends 10
this.access(); //calls present class method
}
Sample(int x)
{
this.x=x; // referes present class reference variable
}
void access()
{
System.out.println("X ="+x);
}
}
class ThisDemo
{
public static void main(String[] args)
{
Sample s=new Sample();
}
}
Methods in java:
Types of Method
Predefined method:
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the method.
For example, print("Java"), it prints Java on the console.
Example:
User-defined Method:
Example:
import java.util.Scanner;
JAVA PROGRAMMING II B. TECH II SEMESTER
}
}
Recursive Methods:
Nesting of Methods:
A method can be called by using only its name by another method of the same class that is
called Nesting of Methods.
Syntax:
class Main
{
method1()
{
// statements
}
method2()
{
// statements
Example:
public class NestingMethod
{
public void a1()
{
System.out.println("****** Inside a1 method ******");
// calling method a2() from a1() with parameters a
a2();
}
public void a2()
{
System.out.println("****** Inside a2 method ******");
}
public void a3()
{
System.out.println("****** Inside a1 method ******");
a1();
}
public static void main(String[] args)
{
// creating the object of class
JAVA PROGRAMMING II B. TECH II SEMESTER
Note: when a super class method is overridden by the sub class method calls only the sub
class method and never calls the super class method. We can say that sub class method is
replacing super class method.
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
ARRAYS
Introduction:
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type
can be created and may have one or more dimensions. A specific element in an array is accessed by its
index. Arrays offer a convenient means of grouping related information.
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must
create an array variable of the desired type.
Declaration:
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for the array
determines what type of data the array will hold.
For example, the following declares an array named month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array actually
exists. In fact, the value of month_days is set to null, which represents an array with no value. To link
month_days with an actual, physical array of integers, you must allocate one using new and assign it to
month_days. new is a special operator that allocates memory.
Here, type specifies the type of data being allocated, size specifies the number of elements in the array,
and array-var is the array variable that is linked to the array. That is, to use new to allocate an array, you
must specify the type and number of elements to allocate. The elements in the array allocated by new
will automatically be initialized to zero (for numeric types), false (for boolean), or null.
This example allocates a 12-element array of integers and links them to month_days:
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further, all elements in
the array will be initialized to zero.
Page 1
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Let’s review: Obtaining an array is a two-step process. First, you must declare a variable of the desired
array type. Second, you must allocate the memory that will hold the array, using new, and assign it to
the array variable. Thus, in Java all arrays are dynamically allocated.
Initialization:
Arrays can be initialized when they are declared. The process is much the same as that used to initialize
the simple types. An array initializer is a list of comma-separated expressions surrounded by curly
braces. The commas separate the values of the array elements. The array will automatically be created
large enough to hold the number of elements you specify in the array initializer. There is no need to use
new.
For example, to store the number of days in each month, the following code creates an initialized array
of integers:
Page 2
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Alternative Array Declaration Syntax:
Java also supports the following type of code for array declaration. In this declaration the type is
followed by square bracket and the name or identifier of the array follows the square bracket.
type [ ] identifier; //one dimensional
type [ ] [ ] identifier; //two dimensional
Example: int [ ] num;
NOTE: Use of a square bracket before and after the identifier will create a multi-dimensional array.
int [ ] num [ ];
the above declaration is equivalent to
int [ ] [ ] num; or int num [ ] [ ];
The operator new which is a keyword, allocates memory for storing the array elements.
For example with the following declaration
int [] num = new int [4];
The compiler allocates 4 memory spaces each equal to 4 bytes for storing the int type values of elements
of array numbers. When an array is created as above, elements of the array are automatically initialized
to 0 by the compiler.
int num [ ] = {10,20,30,40};
Page 3
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Operations on Array Elements
An array element is a variable of the type declared with the array. All the operations that are admissible
for that type of a variable can be applied to an individual array element.
Similar to primitive types or objects of classes, the array may also be declared as a parameter of a
method.
Acess_modifier type method_identifier (type array [], type other_parameter, …)
Unlike in C and C++ languages, in Java, an array may be assigned as a whole to another array of same
data type. In this process, the second array identifier, in fact, becomes the reference to the assigned
array. The second array is not a new array, instead only a second reference is created.
Page 4
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Dynamic Change of Array Size
The number of elements (size) of the array may change during the execution of the program. This
feature is unlike C and C++ wherein the array once declared is of fixed size, that is, the number of
elements cannot be changed.
In Java, however, you may change the number of elements by dynamically retaining the array name. In
this process, the old array is destroyed along with the values of elements.
Example:
int [ ] num = new int [5];
num = new int [10];
Sorting of Arrays
Sorting of arrays if often needed in many applications of arrays. For example, in the preparation of
examination results, you may require to arrange the entries in order of grades acquired by students or in
alphabetical order in dictionary style. The arrays may be sorted in ascending or descending order.
Several methods are used for sorting the arrays that include the following:
1. Bubble sort
2. Selection sort
3. Sorting by insertion method
4. Quick sort
Page 5
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Searching an array for a value is often needed. Let us consider the example of searching for your name
among the reserved seats in a retail reservation chart, air travel reservation chart, searching for a book in
a library, and so on.
Two methods are employed: linear search and binary search for sorted arrays.
Class Arrays
The package java.util defines the class arrays with static methods for general processes that are carried
out on arrays such as sorting an array for full length of the array or for part of an array, binary search of
an array for the full array or part of array, for comparing two arrays if they are equal or not, for filling a
part of the full array with elements having a specified value, and for copying an array to another array.
The sort method of arrays class is based on quick sort technique.
The methods are applicable to all primitive types as well as to class objects.
Page 6
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Methods of Class Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act
like regular multidimensional arrays. However, as you will see, there are a couple of subtle differences.
To declare a multidimensional array variable, specify each additional index using another set of square
brackets.
For example, the following declares a twodimensional array variable called twoD:
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of
arrays of int. Conceptually, this array will look like the one shown in below figure.
The following program numbers each element in the array from left to right, top to bottom, and then
displays these values:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
Page 7
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19
When you allocate memory for a multidimensional array, you need only specify the memory for the first
(leftmost) dimension. You can allocate the remaining dimensions separately. For example, this
following code allocates memory for the first dimension of twoD when it is declared. It allocates the
second dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this situation,
there may be in others. For example, when you allocate dimensions manually, you do not need to
allocate the same number of elements for each dimension. As stated earlier, since multidimensional
arrays are actually arrays of arrays, the length of each array is under your control. For example, the
following program creates a two-dimensional array in which the sizes of the second dimension are
unequal:
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
Page 8
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
12
345
6789
The array created by this program looks like this:
The use of uneven (or irregular) multidimensional arrays may not be appropriate for many applications,
because it runs contrary to what people expect to find when a multidimensional array is encountered.
However, irregular arrays can be used effectively in some situations. For example, if you need a very
large two-dimensional array that is sparsely populated (that is, one in which not all of the elements will
be used), then an irregular array might be a perfect solution.
It is possible to initialize multidimensional arrays. To do so, simply enclose each dimension’s initializer
within its own set of curly braces. The following program creates a matrix where each element contains
the product of the row and column indexes. Also notice that you can use expressions as well as literal
values inside of array initializers.
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
Page 9
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
This program generates the following output:
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Arrays as Vectors
Similar to arrays, vectors are another kind of data structure that is used for storing information. Using
vector, we can implement a dynamic array. As we know, an array can be declared in the following way:
int marks[ ] = new int [7];
the basic difference between arrays and vectors is that vectors are dynamically allocated, where as
arrays are static. The size of vector can be changed as and when required, but this is not true for arrays.
The vector class is contained in java.util package. Vector stores pointers to the objects and not objects
themselves. The following are the vector constructors.
Page 10
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Inheritance
Introduction:
Inheritance is the technique which allows us to inherit the data members and methods from base class to
derived class.
• Base class is one which always gives its features to derived classes.
• Derived class is one which always takes features from base class.
A Derived class is one which contains some of features of its own plus some of the data
members from base class.
Process of inheritance
Syntax for INHERITING the features from base class to derived class:
Here, clsname-1 and clsname-2 represents derived class and base class respectively.
Extends is a keyword which is used for inheriting the data members and methods from base class to
the derived class and it also improves functionality of derived class.
For example:
class c1;
{
int a;
void f1()
{
…………;
}
};
class c2 extends c1
{
int b;
void f2()
{
…………;
}
};
Whenever we inherit the base class members into derived class, when we creates an object of
derived class, JVM always creates the memory space for base class members first and later memory
space will be created for derived class members.
Page 11
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Example:
Write a JAVA program computes sum of two numbers using inheritance?
Answer:
class Bc
{
int a;
};
class Dc extends Bc
{
int b;
void set (int x, int y)
{
a=x;
b=y;
}
void sum ()
{
System.out.println ("SUM = "+(a+b));
}
};
class InDemo
{
public static void main (String k [])
{
Dc do1=new Dc ();
do1.set (10,12);
do1.sum ();
}
};
Types of Inheritances
Single Inheritance: It means when a base class acquired the properties of super class
class Animal
{
void eat()
Page 12
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}
In this example base class is Dog and super class is Animal:
Multilevel Inheritance:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class, thereby making this derived class the base class for the new class. As you can see in below flow
diagram C is subclass or child class of B and B is a child class of A
Example:
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Page 13
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D
Example:
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
Page 14
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
}
}
Output:
method of Class A
method of Class A
method of Class A
Multiple Inheritance:
Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base classes.
Page 15
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Note: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
leads to problems in the hierarchy. This results in unwanted complexity when further extending the
class.
The diagram is just for the representation, since multiple inheritance is not possible in java
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
class D extends A
{
Page 16
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
This example is just to demonstrate the hybrid inheritance in Java. Although this example is
meaningless, you would be able to see that how we have implemented two types of inheritance(single
and hierarchical) together to form hybrid inheritance.
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context.
Final can be:
1. variable
2. method
3. class
The main purpose of using a class being declared as final is to prevent the class from being subclassed.
If a class is marked as final then no class can inherit any feature from the final class.
Example:
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
Page 17
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Output:
Compile time error
Since class Bike is declared as final so the derived class Honda cannot extend Bike
Although a subclass includes all of the members of its superclass, it cannot access those members of the
superclass that have been declared as private.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
This program will not compile because the reference to j inside the sum( ) method of B
causes an access violation. Since j is declared as private, it is only accessible by other members
of its own class. Subclasses have no access to it.
Page 18
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Application of Keyword Super
Super keyword is used for differentiating the base class features with derived class features.
Super keyword is placing an important role in three places.
variable level
method level
constructor level
In order to distinguish the base class members with derived class members in the derived
class, the base class members will be preceded by a keyword super.
For example:
class Bc
{
int a;
};
class Dc extends Bc
{
int a;
void set (int x, int y)
{
super.a=x;
a=y; //by default 'a' is preceded with 'this.' since 'this.' represents current class
}
void sum ()
{
System.out.println ("SUM = "+(super.a+a));
}
};
class InDemo1
{
public static void main (String k [])
{
Dc do1=new Dc ();
do1.set (20, 30);
do1.sum ();
}
};
Page 19
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Super at method level:
Whenever we inherit the base class methods into the derived class, there is a possibility that
base class methods are similar to derived methods.
To differentiate the base class methods with derived class methods in the derived class, the
base class methods must be preceded by a keyword super.
Syntax for super at method level: super. base class method name
For example:
class Bc
{
void display ()
{
System.out.println ("BASE CLASS - DISPLAY...");
}
};
class Dc extends Bc
{
void display ()
{
super.display (); //refers to base class display method
System.out.println ("DERIVED CLASS- DISPLAY...");
}
};
class InDemo2
{
public static void main (String k [])
{
Dc do1=new Dc ();
do1.display ();
}
};
class A
{
int i,j;
A(int a,int b)
{
i=a;
j=b;
Page 20
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
}
void show()
{
System.out.println("i and j values are"+i+" "+j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);//super class constructor
k = c;
}
// display k – this overrides show() in A
void show()
{
super.show();
System.out.println("k: " + k);
}
class Override
{
}
}
Method Overriding // Refer 2nd unit
Dynamic Method Dispatch // Refer 2nd unit
Abstract Classes:
In JAVA we have two types of classes. They are concrete classes and abstract classes.
• A concrete class is one which contains fully defined methods. Defined methods are also known as
implemented or concrete methods. With respect to concrete class, we can create an object of that
class directly.
Page 21
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
An abstract class is one which contains some defined methods and some undefined
methods. Undefined methods are also known as unimplemented or abstract methods.
Abstract method is one which does not contain any definition.
To make the method as abstract we have to use a keyword called abstract before the function
declaration.
Notice that no objects of class A are declared in the program. As mentioned, it is not possible to
instantiate an abstract class.
Page 22
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Interface in Java
Introduction
An interface in java is a blueprint of a class.
It has static constants and abstract methods. The interface in java is a mechanism to achieve abstraction.
There can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
Using the keyword interface, you can fully abstract a class’ interface from its implementation.
That is, using interface, you can specify what a class must do, but not how it does it.
Interfaces are syntactically similar to classes, but they lack instance variables, and their methods
are declared without any body
Variables can be declared inside of interface declarations.
They are implicitly final and static, meaning they cannot be changed by the implementing class.
They must also be initialized. All methods and variables are implicitly public.
Declaring an Interface
An interface is defined much like a class. This is the general form of an interface:
Here is an example of an interface definition. It declares a simple interface that contains one method
called callback( ) that takes a single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, include the implements clause in a class definition, and then create the methods defined by the
interface. The general form of a class that includes the implements clause looks like this:
Page 23
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
class classname [extends superclass] [implements interface [,interface...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma.
Here is a small example class that implements the Callback interface shown earlier.
It is both permissible and common for classes that implement interfaces to define additional members
of their own. For example, the following version of Client implements callback( ) and adds the method
nonIfaceMeth( ):
You can declare variables as object references that use an interface rather than a class type.
Any instance of any class that implements the declared interface can be referred to by such
a variable. When you call a method through one of these references, the correct version will
be called based on the actual instance of the interface being referred to.
Page 24
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
The following example calls the callback( ) method via an interface reference variable:
class TestIface
{
public static void main(String args[])
{
Callback c = new Client();
c.callback(42);
}
}
Multiple Interfaces
interface Showable
{
void show();
}
Page 25
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
}
Output: Hello
Welcome
Nested Interfaces:
An interface i.e. declared within another interface or class is known as nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface
must be referred by the outer interface or class. It can't be accessed directly.
There are given some points that should be remembered by the java programmer.
o Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
o Nested interfaces are declared static implicitly.
Example:
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
Inheritance of Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting
classes. When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within the interface inheritance chain.
Page 26
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
// One interface can extend another.
interface A
{
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A
{
void meth3();
}
// This class must implement all of A and B
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to
be provided in a separate class. So, if a new method is to be added in an interface, then its
implementation code has to be provided in the class implementing the same interface. To overcome this
issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods
with implementation without affecting the classes that implement the interface
Page 27
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
Example:
interface TestInterface
{
// abstract method
public void square(int a);
// default method
default void show()
{
System.out.println("Default Method Executed");
}
}
Output:
16
Default Method Executed
Default methods are also known as defender methods or virtual extension methods.
The interfaces can have static methods as well which is similar to static method of classes.
Example:
interface TestInterface
{
// abstract method
Page 28
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
public void square (int a);
// static method
static void show()
{
System.out.println("Static Method Executed");
}
}
Output:
16
Static Method Executed
Functional Interfaces
A functional interface is an interface that contains only one abstract method. They can have only one
functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance
of a functional interface.
A functional interface can have any number of default methods. Runnable, ActionListener, Comparable
are some of the examples of functional interfaces.
FunctionalInterface annotation is used to ensure that the functional interface can’t have more
than one abstract method. In case more than one abstract methods are present, the compiler flags an
‘Unexpected @FunctionalInterface annotation’ message.
@FunctionalInterface
interface Square
{
int calculate(int x);
}
class Test
{
Page 29
JAVA PROGRAMMING II B. TECH II SEMESTER
(R20)
public static void main(String args[])
{
int a = 5;
Output:
25
Page 30
JAVA PROGRAMMING II B. TECH II SEMESTER
UNIT IV
Packages and Java Library: Introduction, Defining Package, Importing Packages and
Classes into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang
Package and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-
boxing and Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class,
Time Package, Class Instant (java. time. Instant), Formatting for Date/Time in Java, Temporal
Adjusters Class, Temporal Adjusters Class.
Advantages of packages:
packages hide the classes and interfaces in a separate sub directory, so accidental
deletion of classes and interfaces will not take place.
Two classes in two different packages can have the same name.
A group of packages is called a library. The reusability nature of packages makes
programming easy.
There are two types of packages.
o Built-in packages/Java API packages.
o User Defined Packages.
Java API Packages:
o Java API provides a large number of classes grouped into different packages
according functionality.
Page | 1
JAVA PROGRAMMING II B. TECH II SEMESTER
java
Package Contents
name
java.lang lang package contains language support classes. There classes are imported
by java compiler automatically for its usage.
lang package contains classes for primitive types, string, threads,
exceptions, etc…….
java.util Utility classes such as vectors, hash tables, etc…….
java.io Contains classes for input/output of data.
java.awt Contains for graphical user interface, classes for windows, buttons, lists,
menus, etc…..
java.net Classes for networking, contains classes for communicating local
computers and internet servers.
Java.applet Classes for creating and implementing applets
Defining Package
A package is created using keyword package
o Syntax:
package <package>;
Package statement must be the first statement in a java source file.
o Ex:
package studentspack; // package declaration
class Student // class declaration
{
}
Create a package which contans Addition class in that.
package pack;
public class Addition
{
private double a,b;
Page | 2
JAVA PROGRAMMING II B. TECH II SEMESTER
-d tells java compiler to create a separate sub directory and place the .class file there.
Dot (.) indicates that the package should be created in the current directory.
Program to use Addition.class from mypack:
class UsePack
{
public static void main(String args[])
{
pack.Addition obj=new pack.Addition(10,20.5);
obj.sum();
}
}
Note:
Instead of referring the package name every time, we can import the package like this
o import pack.Addition;
Then the program can be written asS....
import pack.Addition;
class UsePack
{
public static void main(String args[])
{
Addition obj=new Addition(10,20.5);
obj.sum();
}
}
Page | 3
JAVA PROGRAMMING II B. TECH II SEMESTER
import java.awt.Font;
- imports Font class in our program.
(or)
import java.awt.*;
- imports all classes of awt package in our program.
PATH CLASSPATH
PATH is an environment CLASSPATH is an environment variable that tells the java
variable. compailer where to look for class files to import. Generally
CLASSPATH is set to a directory or JAR file.
It is used by the operating It is used by Application ClassLoader to locate the .class file.
system to find the executable
files (.exe).
You are required to include You are required to include all the directories which contain
the directory which contains .class and JAR files.
.exe files.
PATH environment variable The CLASSPATH environment variable can be overridden
once set, cannot be by using the command line option -cp or -CLASSPATH to
overridden. both javac and java command.
CLASSPATH is an environment variable that tells the java compailer where to look for class
files to import. Generally CLASSPATH is set to a directory or JAR file.
Type the following command in your Command Prompt and press enter.
set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;
Page | 4
JAVA PROGRAMMING II B. TECH II SEMESTER
In the above command, the set is an internal DOS command that allows the user to change the
variable value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%)
is an existing environment variable. The semicolon is a separator, and after the (;) there is the
PATH of rt.jar file.
Access Control:
Page | 5
JAVA PROGRAMMING II B. TECH II SEMESTER
Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at runtime.
o protected Object clone()
o boolean equals(Object obj)
o protected void finalize()
o Class getClass()
o int hashCode()
o void notify()
o void notifyAll()
o void wait()
o String toString()
The wrapper classes
o Boolean
o Character
o Integer
o Short
o Byte
o Long
o Float
o Double
The classes String, StringBuffer, and StringBuilder similarly provide commonly used
operations on character strings.
Class Throwable encompasses objects that may be thrown by the throw statement.
Subclasses of Throwable represent errors and exceptions.
Enumeration in java:
class EnumExample
{
//defining enum within class
public enum Season { WINTER, SPRING,
SUMMER, FALL } public static void main(String[]
args)
{
//printing all enum
for (Season s : Season.values())
{
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is:
"+Season.valueOf("WINTER").ordinal()); System.out.println("Index of
SUMMER is: "+Season.valueOf("SUMMER").ordinal());
}}
Page | 6
JAVA PROGRAMMING II B. TECH II SEMESTER
class Math:
class MathClass
{
public static void main(String args[])
{
System.out.println("Absolute value-"+Math.abs(-90));
System.out.println("Minimum value-"+Math.min(90,20));
System.out.println("Maximum value-"+Math.max(90,20));
System.out.println("round value-"+Math.round(79.52));
System.out.println("sqrtroot value-"+Math.sqrt(25));
System.out.println("cuberoot value-"+Math.cbrt(125));
System.out.println("power value-"+Math.pow(2,5));
System.out.println("ceil value-"+Math.ceil(2.2));
System.out.println("ceil value-"+Math.floor(2.8));
System.out.println("floorDiv value-"+Math.floorDiv(25,3));
System.out.println("random value-"+Math.random());
System.out.println("rint value-"+Math.rint(81.68));
System.out.println("subtractExact value-"+Math.subtractExact(732, 190));
System.out.println("multiplyExact value-"+Math.multiplyExact(732, 190));
System.out.println("incrementExact value-"+Math.incrementExact(732));
System.out.println("decrementExact value-"+Math.decrementExact(732));
System.out.println("negateExact value-"+Math.negateExact(90));
}
}
Wrapper Classes:
Primitive data types can be converted into object types by using the wrapper classes
contained in java.lang package.
Below table shows the simple data types and their corresponding wrapper classes:
The wrapper classes have a number of unique methods for handling primitive data types and
objects.
Page | 7
JAVA PROGRAMMING II B. TECH II SEMESTER
Converting string Objects to Numeric objects using static method value Of().
Method Conversion Action
X=Double.valueOf(str) Converts string to Double object
X=Float.valueOf(str) Converts string to Float object
X=Integer.valueOf(str) Converts string to Integer Object
X=Long.valueOf(str) Converts string to Long object
Page | 8
JAVA PROGRAMMING II B. TECH II SEMESTER
Byte class:
The following are the Byte class constructures
Byte(byte N);
Byte(String str);
Ex:
Byte b1=new Byte(100);
Byte b2=new Byte("Hello");
Note:
Byte class constructor accepts number as well as string as its parameters.
Page | 9
JAVA PROGRAMMING II B. TECH II SEMESTER
class BoxingExample1
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
UnBoxing Example
class UnboxingExample1
{
Page | 10
JAVA PROGRAMMING II B. TECH II SEMESTER
Page | 11
JAVA PROGRAMMING II B. TECH II SEMESTER
Stack
StringTokenizer
Timer
TimerTask
TimeZone
TreeMap
TreeSet
UUID
Vector
WeakHashMap
Interfaces of util package
Collection<E>
Comparator<T>
Deque<E>
Enumeration<E>
EventListener
Formattable
Iterator<E>
List<E>
ListIterator<E>
Map<K,V>
Map.Entry<K,V>
NavigableMap<K,V>
NavigableSet<E>
Observer
Queue<E>
RandomAccess()
Set<E>
SortedMap<K,V>
SortedSet<E>
Formatter Class:
The java.util.Formatter class provides support for layout justification and alignment, common
formats for numeric, string, and date/time data, and locale-specific output.
Once the Formatter object is created, it may be used in many ways. The format specifier
specifies the way the data is formatted.
Page | 12
JAVA PROGRAMMING II B. TECH II SEMESTER
Random Class:
//all the functions of Random class will generate Pseudo random numbers
import java.util.Random;
public class Test
{
public static void main(String[] args)
{
Random random = new Random();
System.out.println(random.nextInt(10));
System.out.println(random.nextBoolean());
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextGaussian());
}
}
Time Package
Class Instant (java. time. Instant)
Page | 13
JAVA PROGRAMMING II B. TECH II SEMESTER
strDate = formatter.format(date);
Page | 14
JAVA PROGRAMMING II B. TECH II SEMESTER
Temporal Adjusters
Class:
ixmport java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class TemporalAdjusterExample
{
public static void main(String[] args)
{
output = now.with(TemporalAdjusters.firstDayOfMonth());
System.out.println("firstDayOfMonth :: " + output);
output = now.with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println("firstDayOfNextMonth :: " + output);
output = now.with(TemporalAdjusters.firstDayOfNextYear());
System.out.println("firstDayOfNextYear :: " + output);
output = now.with(TemporalAdjusters.firstDayOfYear());
System.out.println("firstDayOfYear :: " + output);
output = now.with(TemporalAdjusters.lastDayOfYear());
System.out.println("lastDayOfYear :: " + output);
output = now.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("lastDayOfMonth :: " + output);
output = now.with(TemporalAdjusters.lastDayOfYear());
System.out.println("lastDayOfYear :: " + output);
}
Page | 15
JAVA PROGRAMMING II B. TECH II SEMESTER
Compile-time errors:
All syntax errors will be detected and displayed by the java
compiler and therefore these errors are known as compile-time
errors.
Whenever the compiler displays an error, it will not create
the .class file.
Run-time errors:
Sometimes a program may compile successfully creating the
.class file but may not run properly because of abnormal
conditions.
Common run-time errors are
o The file you try to open may not exist.
o Dividing an integer by Zero.
o Accessing an element that is out of the bonds of an array
type.
o Trying to store a value into an array of an incompatiable
class or type.
o Trying to cast an instance of a class to one of its
subclasses.
o And many more……………..
Each exception is a class, part of java.lang package and it is
derived from Throwable class.
Page | 16
JAVA PROGRAMMING II B. TECH II SEMESTER
Unchecked Exceptions
Checked Exceptions
Unchecked Exceptions:
Checked Exceptions:
Page | 17
JAVA PROGRAMMING II B. TECH II SEMESTER
Page | 18
JAVA PROGRAMMING II B. TECH II SEMESTER
Page | 19
JAVA PROGRAMMING II B. TECH II SEMESTER
try
{
statement; // generates exception
}
catch(Exception-type e)
{
statement; // process the exception
}
Page | 20
JAVA PROGRAMMING II B. TECH II SEMESTER
Program:
class TryCatch
{
public static void main(String[] args)
{
int a=10;
int b=5;
int c=5;
int r;
try
{ r=a/(b-c); // exception here
System.out.println("This will not be executed. .... ");
}
catch(ArithmeticException e)
{ System.out.println("Cannot divide by 0....."); }
System.out.println("After catch statement. ... ");
}
}
Note: Once an exception is thrown, control is transferred to catch
block and never returns to try block again.
Page | 21
JAVA PROGRAMMING II B. TECH II SEMESTER
try
{
statement;
}
catch(Exception-type 1 e)
{
statement; // process exception type 1
}
catch(Exception-type 2 e)
{
statement; // process exception type 2
}
catch(Exception-type N e)
{
statement; // process exception type N
}
When an exception in a try block is generated, java treats the multiple catch
statements like cases in switch statement.
The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.
Code in the catch block is not compulsory.
o catch (Exception e){}
o the catch statement simply ends with a curly braces( {} ), which does nothing,
this statement will catch an exception and then ignore it.
import java.util.*;
class MultiCatch
{
public static void main(String args[])
{
int no,d,r;
no=d=r=0;
try
{
no=Integer.parseInt(args[0]);
d=Integer.parseInt(args[1]);
Page | 22
JAVA PROGRAMMING II B. TECH II SEMESTER
r=no/d;
System.out.println("Result :"+r);
}
catch (NumberFormatException nf)
{
System.out.println(nf);
}
catch (ArrayIndexOutOfBoundsException ai)
{
System.out.println(ai);
}
catch (ArithmeticException ae)
{
System.out.println(ae);
}
}
}
try-with-resources:
In Java, the try-with-resources statement is a try statement that declares one or more
resources. The resource is as an object that must be closed after finishing the program. The try-
with-resources statement ensures that each resource is closed at the end of the statement
execution.
Syntax:
try(resource code)
{
use resources
}
catch()
{
handle exceptions
}
Example:
import java.io.*;
class TryWithRes
{
public static void main(String args[])
{
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Custom Exceptions:
we can create our own exceptions that are derived classes of the Exception class. Creating our
own Exception is known as custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user need.
Example:
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
Page | 24
JAVA PROGRAMMING II B. TECH II SEMESTER
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example:
class NestedExcep
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println("A number can't be divide with zero");
}
Page | 25
JAVA PROGRAMMING II B. TECH II SEMESTER
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
catch(Exception e)
{
System.out.println("handeled");
}
}
}
class ThrowsTest1
{
public static void main(String args[]) throws IOException
{
Test t1=new Test();
t1.doWork();
}
}
Page | 26
JAVA PROGRAMMING II B. TECH II SEMESTER
UNIT V
String Handling in Java: Introduction, Interface Char Sequence, Class String, Methods for
Extracting Characters from Strings, Methods for Comparison of Strings, Methods for
Modifying Strings, Methods for Searching Strings, Data Conversion and Miscellaneous
Methods, Class String Buffer, Class String Builder.
Java Database Connectivity: Introduction, JDBC Architecture, Installing MySQL and MySQL
Connector/J, JDBC Environment Setup, Establishing JDBC Database Connections, ResultSet
Interface, Creating JDBC Application, JDBC Batch Processing, JDBC Transaction
Management.
1. Address of the object is assigned to the variable s. This object will be like a character
array.
2. Once a string object is created, the data inside the object cannot be modified, that’s
why we say strings are immutable.
Different ways of creating String objects:
String s1=new String();
String s2=new String("sai");
String s3="sai";
Difference between new and " "
1. Using new keyword any number of objects are created for the same class.
String s1=new String("sai");
String s2=new String("sai");
JAVA PROGRAMMING II B. TECH II SEMESTER
The above statements will create two different objects, with different address(same
contents) assigned to different variable s1 and s2 respectively.
2. Assignment operator is used to assign the string to the variable s3. in this case, JVM
first of all checks whether the same object is already available in the string constant
pool or not. If it is available, then it creates another reference to it. If same object is
not available, then it creates another object with the with the content “PREM” and
stores it into the string constant pool.
String s3="sai”;
String s4="sai”;
class StringDiff
{
public static void main(String args[])
{
String s1=new String("sai");
String s2=new String("sai");
String s3="sai";
String s4="sai";
if(s1==s2)
System.out.println("Equal..");
else
System.out.println("NOT Equal..");
if(s3==s4)
System.out.println("Equal..");
else
System.out.println("NOT Equal..");
}
}
Note: The java. lang. String class implements Serializable, Comparable and Char
Sequence interfaces.
JAVA PROGRAMMING II B. TECH II SEMESTER
The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.
Class String:
The java. lang. String class provides many useful methods to perform operations on
sequence of char values.
class SCat
{
public static void main (String args[])
{
String s1="eng";
s1=s1+" college";
System.out.println(s1);
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
We said that String objects immutable(contents of the object are not changed once created).
s1=s1+" Computers";
when this statement is executed a new string is created with the contents of LHS and RHS of
the + operator. And the old object will eligible for garbage collection.
byte b[]=s1.getBytes();
for(byte a:b)
System.out.println(a);
String s2="Aditya";
char[] ch=s2.toCharArray();
for(char c:ch)
System.out.print(c);
}
}
Methods for Comparison of Strings
The following methods are used to compare Strings
1. equals()
2. compareTo()
Example:
class Compare
{
public static void main(String args[])
{
String s1="Aditya";
String s2="Sai";
String s3="aditya";
String s4="Aditya";
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s1));
if(s1.equals(s4))
System.out.println("Equals");
else
System.out.println("Not Equals");
if(s1==s4)
System.out.println("Equals");
JAVA PROGRAMMING II B. TECH II SEMESTER
else
System.out.println("Not Equals");
}
}
Methods for Modifying Strings
The following methods are used to modify Strings
1. concat()
2. replace()
3. trim()
4. substring()
Example:
class StringClass
{
public static void main(String args[])
{
String name="ADITYA";
String name1="college";
String name3="";
String name4="Aditya College of Engineering and Technology";
String name5=" Aditya College of Engineering and Technology ";
System.out.println("sub string example: "+name.substring(2,4));
System.out.println("concat example: "+name.concat(name1));
System.out.println("replace example: "+name.replace('a','A'));
System.out.println("trim example: "+name5.trim());
}
}
Methods for Searching Strings
The following methods are used searching Strings
1. indexOf()
2. lastIndex()
3. charAt()
4. contains()
JAVA PROGRAMMING II B. TECH II SEMESTER
Example:
class StringClass
{
public static void main(String args[])
{
String name="ADITYA";
String name1="college";
String name3="";
String name4="Aditya College of Engineering and Technology";
String name5=" Aditya College of Engineering and Technology ";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println("contains example: "+name.contains("IT"));
System.out.println("indexof example: "+name.indexOf('t'));
}
}
Data Conversion and Miscellaneous Methods
Example:
class StringClass
{
public static void main(String args[])
{
String name="ADITYA";
String name1="college";
String name3="";
String name4="Aditya College of Engineering and Technology";
String name5=" Aditya College of Engineering and Technology ";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
System.out.println("string length is: "+name.length());
JAVA PROGRAMMING II B. TECH II SEMESTER
StringBuffer class:
1. String buffer is a peer class of string. The string buffer class creates mutable strings of
flexible length which can be modified in terms of both length and content.
2. StringBuffer reserves space for 16 characters.
3. EnsureCapacity () adds double+2 spaces.
4. The following are methods of StringBuffer Class
1. length()
2. capacity()
3. charAt()
4. append()
5. toString()
6. reverse()
7. ensureCapacity()
8. setCharAt()
JAVA PROGRAMMING II B. TECH II SEMESTER
9. delete();
10. deleteCharAt();
11. replace();
12. substring();
13. insert()
Example 1:
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Engineering Student");
System.out.println("Buffer:"+sb);
System.out.println("Length:"+sb.length());
System.out.println("Capacity:"+sb.capacity());
// Displaying all the characters of the string
for(int i=0;i<s.length();i++)
{
System.out.println("Character at position:" +i+" is "+s.charAt(i));
}
// Appending at the end
s.append(" CSE");
System.out.println("New string is:"+s);
}
}
Example 2:
class StringBufferDemo1
{
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer(10);
JAVA PROGRAMMING II B. TECH II SEMESTER
System.out.println("sb3 toString:"+sb3.toString());
System.out.println("sb1 length is:"+sb1.length());
System.out.println("sb2 length is:"+sb2.length());
System.out.println("sb3 length is:"+sb3.length());
System.out.println("sb1 capacity is:"+sb1.capacity());
System.out.println("sb2 capacity is:"+sb2.capacity());
System.out.println("sb3 capacity is:"+sb3.capacity());
sb1.ensureCapacity(50);
System.out.println("sb1 capacity is:"+sb1.capacity());
StringBuffer sb4=new StringBuffer("hi are u");
System.out.println("sb4 character is:"+sb4.charAt(0));
System.out.println("sb4 character is:"+sb4.charAt(4));
sb4.setCharAt(0,'H');
sb4.setCharAt(4,'H');
sb4.reverse();
System.out.println(sb4);
sb4.insert(4," Prem");
String s="Good Bye";
boolean b=true;
int i=99;
double d=99.99;
sb5.append('r');
sb5.append('a');
sb5.append('j');
JAVA PROGRAMMING II B. TECH II SEMESTER
System.out.println(sb5);
StringBuffer sb6=new StringBuffer("Raj Jain");
sb6.insert(4," Kumar ");
System.out.println(sb6);
sb6.delete(1,3);
sb6.deleteCharAt(3);
sb6.replace(0,4,"Hello");
String s1=sb6.substring(4);
String s2=sb6.substring(0,4);
System.out.println(s1);
System.out.println(s2);
}
};
equals() and ==:
equals() and == performs two different operations. equals() method compares the characters
inside a String object.
The == operator compares two object references to see whether they refer to the same
instance.
StringBuilder class:
StringBuilder class has been added in JDK1.5 which has same features like
StringBuffer class. StringBuilder class objects are also mutable as the stringBuffer Objects.
Difference:
StringBuffer is class is synchronized and StringBuilder is not.
Multithreaded Programming:
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.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
Commonly used methods of Thread class:
public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on
the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority(int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
JAVA PROGRAMMING II B. TECH II SEMESTER
Creating threads in java is simple. Threads are created in the form of objects that contain a
method called run(). The run() is heart and soul of any thread. The whole code that
constitutes a new thread is written inside the run() method.
Threads can be created by the user in two ways
1. By extending Thread class
2. By implementing Runnable interface
JAVA PROGRAMMING II B. TECH II SEMESTER
}
}
ob1 ob2 ob3
Note:
Methods of Thread class are inherited in our own class, so every
object created for our class is a thread.
Every object(thread) has its own start(),run() and many more
methods.
Whenever start() method is called run() is excuted.
The run() method is just like your main() method where you can
declare variables, use other classes, and can call other methods.
The run() is an entry point for another thread. This thread will end
when run() returns.
Example:
class NewThread1 extends Thread
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{ System.out.println(Thread.currentThread().getName()+" : "+i);
JAVA PROGRAMMING II B. TECH II SEMESTER
Thread.sleep(1000);
}
}
catch(InterruptedException e){}
System.out.println("Child thread exiting. .. ");
};
}
class NewThreadDemo1
{
public static void main(String args[])throws InterruptedException
{
NewThread1 t1=new NewThread1();
t1.setName("Child Thread");
t1.start();
}
};
By implementing Runnable interface:
We can’t extend more than one class to our class because multiple inheritance is not
possible, in such situations we can implement runnable interface.
Runnable implementation is slightly less simple. To run a separate thread, you still
need a thread instance.
To implement Runnable interface, a class need to implement a single method called
run().
Syntax: Public void run()
Example:
class NewThread3 implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(Thread.currentThread().getName()+" : "+i);
Thread.sleep(1000);
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
catch(InterruptedException e){}
System.out.println("Child thread exiting. .. ");
};
}
class NewThreadDemo3
{
public static void main(String args[])throws InterruptedException
{
NewThread3 obj=new NewThread3();
Thread t1=new Thread(obj);
t1.setName("Child Thread");
t1.start();
}
};
Thread Priorities:
When the threads are created and started, a ‘thread scheduler’ program in JVM will load them
into memory and execute them. This scheduler will allot more JVM time to those thread which are
having priority.
The priority numbers will change from 1 to 10.
Thread.MAX_PRIORITY – 10
Thread.MIN_PRIORITY – 1
Thread.NORM_PRIORITY - 5
Example:
class MyClass extends Thread
{
int count=0;
public void run()
{
for(int i=1;i<=10000;i++)
count++;
System.out.println("Completed Thread:"+Thread.currentThread().getName());
System.out.println("It's Priority:"+Thread.currentThread().getPriority());
}
}
class Prior
{
public static void main(String args[])
{
MyClass m=new MyClass();
Thread t1=new Thread(m,"One");
Thread t2=new Thread(m,"Two");
t1.setPriority(2);
t2.setPriority(Thread.NORM_PRIORITY);
t1.start();
t2.start();
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
Newborn state:
When a thread object is created it is said to be in newborn state. It is not yet scheduled for
running. At this stage we can do only following things.
Schedule it for running using start() method.
Kill it using Stop() method.
If scheduled, it moves to the runnable state. If any other method is used an exception will be
thrown.
Runnable state:
Runnable state means the thread is ready for execution and is waiting for the availability
of the processor. i.e The thread has joined the queue of threads that are waiting for
execution.
If all threads have equal priority, they are given time slots for execution in round robin
fashion. i.e first come first serve manner.
The thread that relinquishes control joins the queue at the end and again waits for its
turn. This process of assigning time to threads is knows as time slicing.
JAVA PROGRAMMING II B. TECH II SEMESTER
If we want a thread to relinquish control to another thread of equal priority before its turn
comes, we can do so by using the yield().
Running State:
Running means the processor has given its time to the thread for execution.
A running thread may relinquish its control in one of the following situtations.
Suspend:
It has been suspended using suspend() method. A suspended thread can be revived using
resume() method. This is useful when we want to suspend a thread for some time due to certain
reason. But do not want to kill.
Sleep:
It has been made to sleep. We put a thread to sleep for a specified time period using the method
sleep(time) where time is in milliseconds. This means that the thread is out of the queue during
this time period. It re-enters the runnable state as soon as time period is elapsed.
Wait:
It had been told to wait until some event occurs. This is done using wait() method. The thread
can be scheduled to run again using notify() method.
Blocked State:
A thread is said to be blocked when it is prevented from entering into the
Runnable state. Subsequently the running state.
JAVA PROGRAMMING II B. TECH II SEMESTER
Synchronization
When a thread is already acting on an object, preventing any other thread from acting
on the same object is called “Thread synchronization” or “Thread safe”.
Synchronized object is like a locked object, When a thread enters the object, it locks it,
so that the next thread cannot enter till it comes out.
This means the object is locked mutually on threads, so this object is called
mutex(Mutually exclusive lock).
How to synchronize the object:
There are two ways
Synchronized block
Synchronized keyword
Synchronized block:
Here we can embed a group of statements of the object(inside run() method) within a
synchronized block.
synchronized(this)
{
Statements;
}
JAVA PROGRAMMING II B. TECH II SEMESTER
Synchronized keyword:
We can synchronize an entire method my using synchronized keyword.
synchronized void display()
{
Statements;
}
Example for Synchronized block can be executed only by one thread:
class Reserve implements Runnable
{
int avaliable=1;
int wanted;
Reserve(int i)
{
wanted=i;
}
public void run()
{
synchronized(this)
{
System.out.println("Avaliable Berths= " +avaliable);
if(avaliable>=wanted)
{
String name=Thread.currentThread().getName();
System.out.println(wanted+" berths reserved for "+name);
try
{
Thread.sleep(1000);
avaliable=avaliable-wanted;
}
catch(InterruptedException ie)
{ ie.printStackTrace(); }
}
else
System.out.println("Sorry no berths. ..");
}
}
}
class Sync
{
public static void main(String args[])
{
Reserve obj=new Reserve(1);
Thread t1=new Thread(obj);
JAVA PROGRAMMING II B. TECH II SEMESTER
t1.setName("First person...");
t2.setName("Second Person. .. ");
t1.start();
t2.start();
}
};
}
}
};
t1.start();
t2.start();
}
}
Inter-thread Communication:
In some cases, two or more threads should communicate with each other. For example,
a consumer thread is waiting for a producer to produce the data. When the producer completes
the production of data, then the consumer thread should take that data and use it.
Methods used for inter -thread communication:
obj.wait() : This method makes a thread wait for the object(obj) till it receives a notification
from a notify() or notifyAll() method.
obj.notify() : This method releases an object(obj) and sends a notification to a waiting thread
that the object is available.
obj.notifyAll() : This method is useful to send notification to all waiting threads at once that
the object is available.
Example:
class Communicate1
{
public static void main(String args[])throws Exception
{
Producer obj1=new Producer();
// pass producer object to Consumer
Consumer obj2=new Consumer(obj1);
//Create two threads and attach to producer and consumer
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t2.start();//consumer waits
t1.start();//producer starts production
}
}
JAVA PROGRAMMING II B. TECH II SEMESTER
{
prod=p;
}
public void run()
{
synchronized(prod.sb)
{
// wait till a notification is received from producer thread. Here
//there is no wastage of time of even a single millisecond
try{
prod.sb.wait();
}
catch(Exception e){}
System.out.println(prod.sb);
}//end of sync
}//end of run
}//end of consumer class
6. The java.sql package contains classes and interfaces for JDBC API. A list of
popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
A list of popular classes of JDBC API are given below:
o DriverManager class
o Blob class
o Clob class
o Types class
7. We can use JDBC API to handle database using Java program and can perform the
following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
JAVA PROGRAMMING II B. TECH II SEMESTER
JDBC drivers are not required to support this feature. You should use
the DatabaseMetaData.supportsBatchUpdates() method to determine if the target
database supports batch update processing. The method returns true if your JDBC
driver supports this feature.
The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.
Just as you can add statements to a batch for processing, you can remove them with
the clearBatch() method. This method removes all the statements you added with the
addBatch() method. However, you cannot selectively choose which statement to
remove.
Here is a typical sequence of steps to use Batch Processing with Statement Object −
JAVA PROGRAMMING II B. TECH II SEMESTER
Add as many as SQL statements you like into batch using addBatch() method on
created statement object.
Execute all the SQL statements using executeBatch() method on created statement
object.