java oops advance
java oops advance
I – SEMESTER
STUDY MATERIAL
Prepared by
Dr. G. Geetha Devi
SKIIMS B - SCHOOL
SKIIMS B-SCHOOL
SRI KALAHASTISWAEA INSTITUTE OF INFORMATION AND
MANAGENT SCIENCES
Kapugunneri, Srikalahasti – 517641.
What Is an Object?
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {cadence = newValue}
void changeGear(int newValue) { gear = newValue}
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) {speed = speed - decrement; }
void printStates(){
System.out.println("cadence:" + cadence + " speed:" +
speed + " gear:" + gear); } }
What Is Inheritance?
The syntax for creating a subclass is simple. At the beginning of your class
declaration, use the extends keyword, followed by the name of the class to
inherit from:
What Is an Interface?
interface Bicycle {
// wheel revolutions per minute
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement); }
To implement this interface, the name of your class would change (to a
particular brand of bicycle, for example, such as ACMEBicycle), and you'd
use the implements keyword in the class declaration:
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue}
void changeGear(int newValue) {
gear = newValue;}
void speedUp(int increment) {
speed = speed + increment; }
void applyBrakes(int decrement) {
What Is a Package?
The Java Platform API Specification contains the complete listing for all
packages, interfaces, classes, fields, and methods supplied by the Java SE
platform. Load the page in your browser and bookmark it. As a programmer,
it will become your single most important piece of reference documentation.
Features of Java
The prime reason behind creation of Java was to bring portability and
security feature into a computer language.Those features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand.The confusing and ambiguous concepts of C++ are either left
out in Java or they have been re-implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an
important part of C++.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java
can be easily extended as it is based on Object Model. Following are some
basic concept of OOP's.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are
compiled into platform specific machines. Java is guaranteed to be write-
once, run-anywhere language.On compilation Java program is compiled into
bytecode. This bytecode is platform independent and can be run on any
machine, plus this bytecode format also provide security. Any machine with
5) Secure
When it comes to security, Java is always the first choice. With java
secure features it enable us to develop virus free, temper free system. Java
program always runs in Java runtime environment with almost null
interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that
can do many tasks simultaneously. Benefit of multithreading is that it utilizes
same memory and other resources to execute multiple threads at the same
time, like While typing, grammatical errors are checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a
particular computer architecture, hence a Java program is easy to intrepret
on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation
dependent features. Everything related to storage is predefined, example:
size of primitive data types
9) High Performance
JAVA Architecure :
Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java
Java is a high level programming language. A program written in high level
language cannot be run on any machine directly. First, it needs to be
translated into that particular machine language. The javac compiler does
this thing, it takes java program (.java file containing source code) and
translates it into machine code (referred as byte code or .class file).
Java Virtual Machine (JVM) is a virtual machine that resides in the real
machine (your computer) and the machine language for JVM is byte
code. This makes it easier for compiler as it has to generate byte code for
JVM rather than different machine code for each type of
machine.
JVM Architecture
Heap: Heap is a part of JVM memory where objects are allocated. JVM
creates a Class object for each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for
storing temporary variables.
PC Registers: This keeps the track of which instruction has been executed
and which one is going to be executed. Since instructions are executed by
threads, each thread has a separate PC register.
Native Method stack: A native method can access the runtime data areas
of the virtual machine.
JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine(JVM), class libraries, and other files excluding
development tools such as compiler and debugger.
Which means you can run the code in JRE but you can’t develop and compile
the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries
and files provided by JRE.
Variables are containers for storing data values. In Java, there are
different types of variables, for example:
To create a variable, you must specify the type and assign it a value:
Where type is one of Java's types (such as int or String), and variable is the
name of the variable (such as x or name). The equal sign is used to assign
values to the variable.
To create a variable that should store text, look at the following example:
SRI KALAHASTISWARA INSTITUTE OF INFORMATION AND MANAGEMENT SCIENCES Page 11
Example Create a variable called name of type String and assign it the
value "John":
Example Create a variable called myNum of type int and assign it the
value 15:
You can also declare a variable without assigning the value, and assign the
value later:
System.out.println(myNum);
Final Variables
However, you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the variable as "final"
or "constant", which means unchangeable and read-only):
Example
final int myNum = 15; myNum = 20; // will generate an error: cannot
assign a value to a final variable
You can also use the + character to add a variable to another variable:
Example
Example
Declare Many Variables To declare more than one variable of the same
type, use a comma-separated list:
Example int x = 5, y = 6, z = 50;System.out.println(x + y + z);
The general rules for constructing names for variables (unique identifiers)
are:
Java Operators
Example int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 =
sum2 + sum2;
= x =5 x =5
+= x += 3 x =x+3
-= x -= 3 x =x-3
/= x /= 3 x =x/3
%= x %= 3 x =x%3
|= x |= 3 x =x|3
^= x ^= 3 x =x^3
== Equal to x == y
!= Not equal x != y
Control Structures
In the most basic sense, a program is a list of instructions. Control
structures are programming blocks that can change the path we take
through those instructions.
There are three kinds of control structures:
The if/else statement is the most basic of control structures, but can also be
considered the very basis of decision making in programming.
While if can be used by itself, the most common use-scenario is choosing
between two paths with if/else:
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
Theoretically, we can infinitely chain or nest if/else blocks but this will hurt
code readability, and that's why it's not advised.
We'll explore alternative statements in the rest of this article. Ternary
Operator
We can use a ternary operator as a shorthand expression that works like
an if/else statement.
Let's see our if/else example again:
if (count > 2) { System.out.println("Count is higher than 2");
} else { System.out.println("Count is lower or equal than 2");}
We can refactor this with a ternary as follows:
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or
equal than 2");
While ternary can be a great way to make our code more readable, it isn't
always a good substitute for if/else.
Switch If we have multiple cases to choose from, we can
use switch statement.Let's again see a simple example:
int count = 3;
switch (count) {
case 0: System.out.println("Count is equal to 0"); break;
case 1: System.out.println("Count is equal to 1") break;
default: System.out.println("Count is either negative, or higher than
1");break;}
Three or more if/else statements can be hard to read. As one of the possible
workarounds, we can use switch, as seen above.
And also keep in mind that switch has scope and input limitations that we
need to remember before using it.
Loops
int whileCounter = 1;
while (whileCounter <= 50) { methodToRepeat() whileCounter++;}
Both code blocks above will call methodToRepeat 50 times.
Break
We need to use break to exit early from a loop.
Let's see a quick example:
List<String> names = getNameList();
String name = "John Doe";
int index = 0;
for ( ; index < names.length; index++) {
if (names[index].equals(name)) { break; }}
Here, we are looking for a name in a list of names, and we want to stop
looking once we've found it.
Continue
Simply put, continue means to skip the rest of the loop we're in:
List<String> names = getNameList();
String name = "John Doe";
String list = "";
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) { continue;
}list += names[i];}
Here, we skip appending the duplicate names into the list.
Java Arrays
String[] cars;
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Examplecars[0] = "Opel";
Array Length To find out how many elements an array has, use
the length property:
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
Syntax
The following example outputs all elements in the cars array, using a "for-
each" loop:
The example above can be read like this: for each String element (called i -
as in index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-
each method is easier to write, it does not require a counter (using the
length property), and it is more readable.
Multidimensional Arrays
To create a two-dimensional array, add each array within its own set
of curly braces:Example int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
To access the elements of the myNumbers array, specify two indexes: one
for the array, and one for the element inside that array. This
example accesses the third element (2) in the second array (1) of
myNumbers:
We can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes): Example is
System.out.println(myNumbers[i][j]);}}}
Control Structures :
Simple if statement
if (condition) {
If..else statement
int a = 15;
if (a > 20)
else
System.out.println("Hello World!");}}}
Output:
a is less than 10
Hello World!
Nested if statement
if (condition1) {
if (condition2) {
Example:
else
System.out.println("Hello World!");}}
Output:
s is an even number and greater than 10!
Hello World!
Switch statement
Example:
String musicInstrument;
switch (instrument) {
musicInstrument = "Invalid";break;}
System.out.println(musicInstrument);}}
Output:
Flute
Looping Statements
While
Known as the most common loop, the while loop evaluates a certain
condition. If the condition is true, the code is executed. This process is
continued until the specified condition turns out to be false.
The condition to be specified in the while loop must be a Boolean expression.
An error will be generated if the type used is int or a string.
Syntax:
Example:
{System.out.println(i);i = i+2;}}}
Output:
5 7 9 11 13 15
Do..while
The do-while loop is similar to the while loop, the only difference being that
the condition in the do-while loop is evaluated after the execution of the loop
body. This guarantees that the loop is executed at least once.
Syntax:
do{//code to be executed}while(condition);
Example:
Output:
20
Moving on with this article on Control Statements in Java The for loop in java
is used to iterate and evaluate a code multiple times. When the number of
iterations is known by the user, it is recommended to use the for loop.
Syntax:
{statement;}
Example:
Output:
5
6
7
8
9
10
For-Each
The traversal of elements in an array can be done by the for-each loop. The
elements present in the array are returned one by one. It must be noted
that the user does not have to increment the value in the for-each loop.
Example:
Output:
18
25
28
29
30
Branching Statements
Break
The break statement in java is used to terminate a loop and break the
current flow of the program.
Example:
}}}
Output:
5
6
7
Continue
To jump to the next iteration of the loop, we make use of the continue
statement. This statement continues the current flow of the program and
skips a part of the code at the specified condition.
Example:
Output:
6 8 10 12 14
Arrays
Creating an array
In Java, there are two ways to create an array. The first way is using
the new keyword as shown below.int[] array = new int[10];The other way to
create an array is using a shortcut syntax. The shortcut syntax allows us to
instantiate the array with exactly the values we need. Using this syntax, we
skip having to do the costly operation of looping through the array to insert
an element at each index.
If you don't know the elements that you want to put in your array when you
instantiate it go with the new keyword. It's important to note that no matter
how we create an array we need to know the size we want to allocate to the
array. The indexes of the array are zero-indexed. If you have an array
length of 10 the first element of this array will actually be at the index of 0
and the last index will be 9.
array.length When first learning arrays in Java it can be easy to get tripped
up on the length property being one based. Remember when trying to find
where an array ends you will always want the length -
System.out.println(myObj.x);}}
You can also create an object of a class and access it in another class.
This is often used for better organization of classes (one class has all the
attributes and methods, while the other class holds the main() method (code
to be executed)).
Remember that the name of the java file should match the class name. In
this example, we have created two files in the same directory/folder:
Main.java
Second.java
o Change the value in Method: Java supports only call by value. So, if
we pass a primitive value, it will not change the original value. But, if
we convert the primitive value in an object, it will change the original
value.
o Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
The eight classes of the java.lang package are known as wrapper classes in
Java. The list of eight wrapper classes are given below:
Auto boxing
System.out.println(a+””+i+++);}} output:20 20 20
Constructors
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization
It is a special type of method which is used to initialize the object.Every time an object
is created using the new() keyword, at least one constructor is called.It calls a default
constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Java Default constructor: “A constructor does not having any parameter”.Main purpose of
these one is to provide the default values to the object like0,null,etc,depending on the
type
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types
There is no copy constructor in Java. However, we can copy the values from one object to another like copy
constructor in C++.
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
Overloading of methods
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters, and
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class Adder{
Access Control
Access control specifies the accessibility of code. By using these you can specify the
scope of data, method, class etc.There are 3 types of access control in :
1. Public or Default
2. Private
3. Internal
Public access control also known as default. It is accessible for all. If you don't specify
any access control explicitly in your code, by default it follows public access control.
1. type AccessControl() =
2. member public x.a = 10
3. member public x.display() = printfn "This is public method"
4. let ac = new AccessControl() ac.display()
Output: error FS0491: The member or object constructor 'display' is not accessible.
Private members may only be accessed from within the declaring type.
Internal access control is only accessible from the same assembly. An assembly is a
file which is automatically generated by your compiler after compilation of F# code. It
can be either Dynamic Link Library (DLL) or Executable File (exe).
Nested class
Nested class is such class which is created inside another class. In Kotlin, nested class
is by default static, so its data member and member function can be accessed without
creating an object of class. Nested class cannot be able to access the data member of
outer class.
Inner class
Inner class is a class which is created inside another class with keyword inner. In other
words, we can say that a nested class which is marked as "inner" is called inner class.
The advantage of inner class over nested class is that, it is able to access members of
outer class even it is private. Inner class keeps a reference to an object of outer class
Abstract class in Java
Abstraction in Java
These are important points :An abstract class must be declared with an
abstract keyword,It can have abstract and non-abstract methods,It cannot
be instantiated,It can have constructors and static methods also,It can have
final methods which wil force the subclass not to change the body of the
method.
Obj.run();}}
File: TestBank.java
2. Types of Inheritance
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality. In the terminology of Java, a class which is inherited is called a
parent or superclass, and the new class is called child or subclass.
File: TestInheritance2.java
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
Method Overriding:
o Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
In this example, we have defined the run method in the subclass as defined
in the parent class but it has some specific implementation. The name and
parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. class Bike2 extends Vehicle{
4. void run(){System.out.println("Bike is running safely");}
Java Math class provides several methods to work on math calculations like
min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Output:
Maximum number of x and y is: 28.0 Square root of y is: 2.0
Power of x and y is: 614656.0 Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906 log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624 log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12 expm1 of a is: 1.446257064290475E1
LogarithmicMathMethods:
Math.log(),Math.log10(),Math.log1p(),Math.exp(),Math.expm1()
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.Here, we will have the detailed learning of creating and using
user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.2) Java package provides access protection.3) Java
package removes naming collision.
There are three ways to access the package from outside the package.
Let's take an example, Sun Microsystem has definded a package named java
that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and
so on
Interface in Java
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents
the IS-A relationship.It cannot be instantiated just like the abstract class.
There are mainly three reasons to use interface. They are given below.
Syntax:
1. interface <interface_name>{
In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.
There are mainly two types of exceptions: checked and unchecked. Here, an
error is considered as the unchecked exception. According to Oracle, there
are three types of exceptions:
There are given some scenarios where unchecked exceptions may occur.
They are as follows:
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException
Un caught exceptions :
The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in exception
handler.
Java programming language has a very strong exception handling
mechanism. It allow us to handle the exception use the keywords like try,
catch, finally, throw, and throws. When an uncaught exception occurs, the
JVM calls a special private method known dispatchUncaughtException( ),
on the Thread class in which the exception occurs and terminates the
thread.
The Division by zero exception is one of the example for uncaught
exceptions. Look at the following code
import java.util.Scanner
public class uncaughtExceptionExample{ public static void main(String[]
args) { Scanner read =new Scanner(system.in);System.out.println(“enter
the a and b values:”);
int a=readnexInt(); int b=readnextInt();int
c=a/b;System.out.println(a+”/”+b+”=”+c);}}
When we execute the above code, it produce the following output for the
value a = 10 and b = 0
The keyword try is used to define a block of code that will be tests the
occurence of an exception. The keyword catch is used to define a block of
code that handles the exception occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the
compiler but automatically caught and handled by the Java built-in exception
handler.
Both try and catch are used as a pair. Every try block must have one or
more catch blocks. We can not use try without atleast one catch, and catch
alone can be used (catch without try is not allowed).
try{…….. code to be tested………}
1. throw exception;
2. public class TestThrow1{
3. static void validate(int age){
4. if(age<18)
SRI KALAHASTISWARA INSTITUTE OF INFORMATION AND MANAGEMENT SCIENCES Page 14
5. throw new ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote"); }
8. public static void main(String args[]){
9. validate(13);
10. System.out.println("rest of the code..."); }}
Difference between throw and throws in Java
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
Multitasking
Thread in java
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
4) Non-Runnable (Blocked) This is the state when the thread is still alive,
but is currently not eligible to run.
Multithreading in Java
Advantages of multithread:
Synchronization in Java
Types of Synchronization
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java: 1 by synchronized
method 2. by synchronized block 3 by static synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } }}
class MyThread1 extends Thread{
Table t; MyThread1(Table t){
this.t=t; }
public void run(){
t.printTable(5); } }
class MyThread2 extends Thread{
Table t; MyThread2(Table t){ this.t=t; }
public void run(){
t.printTable(100); } }
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
SRI KALAHASTISWARA INSTITUTE OF INFORMATION AND MANAGEMENT SCIENCES Page 20
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
. t1.start(); t2.start(); } }
Output: 5 100 10 200 15 300 20 400 25 500
1) wait() method
Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.
Public final void wait() throws InterruptedException :waits until object is
notified. public final void wait(long timeout)throws InterruptedException
:waits for the specified amount of time.
2) notify() method
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
wait() sleep()
wait() method releases the sleep() method doesn't
lock release the lock.
is the method of Object is the method of Thread class
class
is the non-static method is the static method
is the non-static method is the static method
String Handling
CharSequence Interface
How to create a string object? There are two ways to create String object: By
string literal ,By new keyword
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference v
ariable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant
pool.
1. By equals() method
2. By = = operator
3. By compareTo() method
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
o s1 == s2 :0
o s1 > s2 :positive value
o s1 < s2 :negative value
Java string concatenation operator (+) is used to add strings. For Example:
Substring in Java
You can get substring from the given string object by one of the two
methods:
The java string toUpperCase() method converts this string into uppercase
letter and string toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin System.out.println(s);
Java String charAt() method The string charAt() method returns a character at
specified index.
Java String charAt() method The string charAt() method returns a character at
specified index.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned.
SRI KALAHASTISWARA INSTITUTE OF INFORMATION AND MANAGEMENT SCIENCES Page 27
Java String valueOf() method The string valueOf() method coverts given
type such as int, long, float, double, boolean, char and char array into
string.
Java String replace() method The string replace() method replaces all
occurrence of first sequence of character with second sequence of character.
Java StringBuffer class Java StringBuffer class is used to create mutable
(modifiable) string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
2) StringBuffer insert() method The insert() method inserts the given string
with this string at the given position.
3)StringBuffer replace() method The replace() method replaces the given string
from the specified beginIndex and endIndex.
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic conversion
of primitive into an object is known as autoboxing and vice-versa unboxing.
o Change the value in Method: Java supports only call by value. So, if
we pass a primitive value, it will not change the original value. But, if
we convert the primitive value in an object, it will change the original
value.
o Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility classes
to deal with objects.
o Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
Number Class
Java Number class provides methods to convert the represented
numeric value to byte, double, float, int, long, and short type. The
various Java Number methods are as follows-
The Character class generally wraps the value of all the primitive type char
into an object. Any object of the type Character may contain a single field
RCR Institute of Management & Technology {ICET Code: RCRM} Page 31
Prepared by :Mrs P.Lalitha, MCA, Department of Computer Science
whose type is char. All the fields, methods, and constructors of the class
Character are specified by the Unicode Data file which is particularly a part
of Unicode Character Database and is maintained by the Unicode
Consortium.
The Boolean class wraps a value of the primitive type boolean in an object.
Its object contains only a single field whose type is boolean.
Methods:
booleanValue(),compare(),compareTo(),equals(),getBoolean(),hashCode(),lo
gicalAnd(),logicalOr(),logicalXor(),parseBoolean(),toString() , valueOf()
Class declaration
Class constructors
1
Vector()
This constructor is used to create an empty vector so that its internal
data array has size 10 and its standard capacity increment is zero.
2
Vector(Collection<? extends E> c)
This constructor is used to create a vector containing the elements of
the specified collection, in the order they are returned by the
collection's iterator.
3
Vector(int initialCapacity)
This constructor is used to create an empty vector with the specified
initial capacity and with its capacity increment equal to zero.
4
Vector(int initialCapacity, int capacityIncrement)
This constructor is used to create an empty vector with the specified
initial capacity and capacity increment.
Stack
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO). Java collection framework
provides many interfaces and classes to store the collection of objects. One
of them is the Stack class that provides different operations such as push,
pop, search, etc.
In Java, Stack is a class that falls under the Collection framework that
extends the Vector class. It also implements interfaces List, Collection,
Iterable, Cloneable, Serializable. It represents the LIFO stack of objects.
Before using the Stack class, we must import the java.util package. The
stack class arranged in the Collections framework hierarchy, as shown
below.
Methods of the Stack Class We can perform push, pop, peek and
search operation on the stack. The Java Stack class provides
mainly five methods to. Along with this, it also provides all the
methods of the Java Vector class.
Method Modifier perform these operations Method
and Description
Type
empty() boolean The method checks the stack is empty or
not.
push(E item) E The method pushes (insert) an element onto
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The
position of the bucket is identified by calling the hashcode() method. A
Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor
is 0.75.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
Following is an example which makes use of these two classes to copy an
input file into an output file –
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
All the programming languages provide support for standard I/O where the
user's program can take input from a keyboard and then produce an output
on the computer screen. If you are aware of C or C++ programming
languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similarly, Java provides the following three standard
streams −
Standard Input − This is used to feed the data to user's program
and usually a keyboard is used as standard input stream and
represented as System.in.
Standard Output − This is used to output the data produced by the
user's program and usually a computer screen is used for standard
output stream and represented as System.out.
Standard Error − This is used to output the error data produced by
the user's program and usually a computer screen is used for
standard error stream and represented as System.err
FileInputStream
This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream
object.
1
File(File parent, String child)
This constructor creates a new File instance from a parent
abstract pathname and a child pathname string.
2
File(String pathname)
This constructor creates a new File instance by converting the
given pathname string into an abstract pathname.
3
File(String parent, String child)
This constructor creates a new File instance from a parent
pathname string and a child pathname string.
4
File(URI uri)
This constructor creates a new File instance by converting the
given file: URI into an abstract pathnam
1
public String getName()
Returns the name of the file or directory denoted by this
abstract pathname.
2
public String getParent()
Returns the pathname string of this abstract pathname's
parent, or null if this pathname does not name a parent
directory.
3
public File getParentFile()
Returns the abstract pathname of this abstract pathname's
parent, or null if this pathname does not name a parent
directory.
4
public String getPath()
Converts this abstract pathname into a pathname string.
AWT Packages
It consists of 12 packages of 370 classes (Swing is even bigger, with 18
packages of 737 classes as of JDK 8). Fortunately, only 2 packages -
java.awt and java.awt.event - are commonly-used.
In the above figure, there are three containers: a Frame and two Panels.
A Frame is the top-level container of an AWT program. A Frame has a
title bar (containing an icon, a title, and the minimize/maximize/close
buttons), an optional menu bar and the content display area. A Panel is
a rectangular area used to group related GUI components in a certain
layout. In the above figure, the top-level Frame contains two Panels.
A Frame provides the "main window" for your GUI application. It has a title
bar (containing an icon, a title, the minimize, maximize/restore-down and
close buttons), an optional menu bar, and the content display area. To write
a GUI program, we typically start with a subclass extending
from java.awt.Frame to inherit the main
window as follows:
An AWT Dialog is a "pop-up window" used for interacting with the users.
A Dialog has a title-bar (containing an icon, a title and a close button)
and a content display area, as illustrated.
An AWT Applet (in package java.applet) is the top-level container for an
applet, which is a Java program running inside a browser.
import java.awt.*;
import java.awt.event.*;
public class AWTCounter extends Frame implements ActionListener {
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private int count = 0;
public AWTCounter () {
setLayout(new FlowLayout());
lblCount = new Label("Counter"); add(lblCount);
tfCount = new TextField(count + "", 10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Count");
add(btnCount);
btnCount.addActionListener(this);
setTitle("AWT Counter"); setSize(250, 100);
setVisible(true);
public static void main(String[] args) {
AWTCounter app = new AWTCounter();}
@Override
public void actionPerformed(ActionEvent evt) {
++count;
tfCount.setText(count + ""); }
}
Swing Introduction
Swing is part of the so-called "Java Foundation Classes (JFC)" (have you
heard of MFC?), which was introduced in 1997 after the release of JDK 1.1.
JFC was subsequently included as an integral part of JDK since JDK 1.2. JFC
consists of:
Swing API: for advanced graphical programming.
Accessibility API: provides assistive technology for the disabled.
Java 2D API: for high quality 2D graphics and images.
Pluggable look and feel supports.
Drag-and-drop support between Java and native applications.
The goal of Java GUI programming is to allow the programmer to build GUI
that looks good on ALL platforms. JDK 1.0's AWT was awkward and non-
object-oriented (using many event.getSource()). JDK 1.1's AWT introduced
event-delegation (event-driven) model, much clearer and object-oriented.
JDK 1.1 also introduced inner class and JavaBeans – a component
programming model for visual programming environment (similar to Visual
Basic).
Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an
add-on JFC (Java Foundation Classes). Swing is a rich set of easy-to-use,
easy-to-understand JavaBean GUI components that can be dragged and
dropped as "GUI builders" in visual programming environment. Swing is now
an integral part of Java since JDK 1.2.
Java Applet
o Secured
Drawback of Applet
java.applet.Applet class
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
1. //First.java
2. import java.applet.Applet; import java.awt.Graphics;
3. public class First extends Applet{
4. public void paint(Graphics g){
5. g.drawString("welcome",150,150); }
myapplet.html
1. <html> <body>
2. <applet code="First.class" width="300" height="300"> </applet> </b
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5. public void paint(Graphics g){
6. g.drawString("welcome to applet",150,150); } }
7. /* <applet code="First.class" width="300" height="300"> </applet> */
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Applet is mostly used in games and animation. For this purpose image
is required to be displayed. The java.awt.Graphics class provide a method
drawImage() to display the image.
RCR Institute of Management & Technology {ICET Code: RCRM} Page 53
Prepared by :Mrs P.Lalitha, MCA, Department of Computer Science
Syntax of drawImage() method:
myapplet.html
1. <html> <body>
2. <applet code="DisplayImage.class" width="300" height="300">
3. </applet> </body> </html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter(). Syntax:
myapplet.html
1. <html> <body>
2. <applet code="UseParam.class" width="300" height="300">
3. <param name="msg" value="Welcome to applet">
4. </applet> </body> </html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to b
moved.
myapplet.html
1. <html> <body>
2. <applet code="DisplayImage.class" width="300" height="300">
3. </applet> </body> </html>
Changing the state of an object is known as an event. For example, click on button
dragging mouse etc. The java.awt.event package provides many event classes an
Listener interfaces for event handling.
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o TextField
o TextArea
o Checkbox
o Choice
o List
We can put the event handling code into one of the following places:
public void setBounds(int xaxis, int yaxis, int width, int height); have
been used in the above example that sets the position of the component it
may be button, textfield etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
File: FirstSwingExample.java
1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible } }
Java JFrame
Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
Nested Class
Modifier and Class Description
Type
protected JFrame.AccessibleJFrame This class implements
class accessibility support for the
JFrame class.
Fields
Modifier and Type Field Description
protected accessibleContext The accessible
AccessibleContext context property.
static int EXIT_ON_CLOSE The exit application
Constructors
Constructor Description
JFrame() It constructs a new frame that is
initially invisible.
JFrame(GraphicsConfiguration It creates a Frame in the specified
gc) GraphicsConfiguration of a screen
device and a blank title.
JFrame(String title) It creates a new, initially invisible
Frame with the specified title.
JFrame(String title, It creates a JFrame with the specified
GraphicsConfiguration gc) title and the specified
GraphicsConfiguration of a screen
device.
Useful Methods
Modifier and Method Description
Type
protected void addImpl(Component comp, Object Adds the
constraints, int index) specified child
Component.
protected createRootPane() Called by the
JFrame Example
1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.Jpanel;
Output
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It
allows the editing of multiple line text. It inherits JTextComponent class
JRadioButton Constructors
1. JRadioButton(): It is used to create an unselected radio button with
no text.
These controls are subclasses of Component. Although this is not a particularly ric
set of controls, it is sufficient for simple applications. (Note that both Swing and JavaF
provide a substantially larger, more sophisticated set of controls.)
Java Networking
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) Protocol
3) Port Number
4) MAC Address
6) Socket
java.net package
INTERFACES
CookiePolicy CookieStore
FileNameMap SocketOption
InetAddress ServerSocket
SocketImplFactory ProtocolFamily
InetAddress
Inet Address encapsulates both numerical IP address and the domain name
for that address. Inet address can handle both IPv4 and Ipv6 addresses.
Inet Address class has no visible constructor. To create an inet Address
object, you have to use Factory methods.
URL class
Java URL Class present in java.net package, deals with URL (Uniform
Resource Locator) which uniquely identify or locate resources on internet.
Java includes support for both IPv4 and IPv6 addresses. Because of this,
two subclassesof InetAddress were
created: Inet4Address and Inet6Address. Inet4Address represents
a traditional-style IPv4 address. Inet6Address encapsulates a newer
IPv6 address. Because they are subclasses
of InetAddress, an InetAddress reference can refer to either. This is
one way that Java was able to add IPv6 functionality without breaking
existing code or adding many more classes. For the most part, you can
simply use InetAddress when working with IP addresses because it can
accommodate both styles
Java Socket Programming
Factory Methods
The InetAddress class has no visible constructors. To create
an InetAddress object, you have to use one of the available factory
static InetAddress[ ]
Instance Methods
The InetAddress class has several other methods, which can be used
on the objects returned by the methods just discussed. Here are some of
the more commonly used methods:
boolean equals(Object other) : Returns true if this object has the same
Internet address as other.
String toString( ) : Returns a string that lists the host name and the IP
address for convenience.
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform
Resource Locator. It points to a resource on the World Wide Web. For
example:
URL(String spec)
Creates an instance of a URL from the given protocol, host, port number,
and file.
Creates an instance of a URL from the given protocol, host, port number,
file, and handler.
Creates an instance of a URL from the given protocol name, host name, and
file name.
Creates an instance of a URL by parsing the given spec with the specified
handler within a given context.
Method Description
public boolean equals(Object it compares the URL with the given object.
obj)
The URLConnection class provides many methods, we can display all the
data of a webpage by using the getInputStream() method. The
getInputStream() method returns all the data of the specified URL in the
stream that can be read and displayed.
1. ServerSocket API
The ServerSocketclass is used to implement a server program. Here are
the typical steps involve in developing a server program:
The steps 1 to 5 can be repeated for each new client. And each new
connection should be handled by a separate thread.
Note that the accept() method blocks the current thread until a connection is
made. And the connection is represented by the returned Socket object.
Once a Socket object is returned, you can use its InputStream to read data
sent from the client like this:
The InputStream allows you to read data at low level: read to a byte array.
So if you want to read the data at higher level, wrap it in
an InputStreamReader to read data as characters:
As the OutputStream provides only low-level methods (writing data as a byte array), y
can wrap it in a PrintWriter to send data in text format, for example:
The argument true indicates that the writer flushes the data after each method call (a
flush).
Invoke the close() method on the client Socket to terminate the connection with the clien
1 socket.close();
This method also closes the socket’s InputStream and OutputStream, and it c
RCR Institute of Management & Technology {ICET Code: RCRM} Page 85
Prepared by :Mrs P.Lalitha, MCA, Department of Computer Science
throw IOException if an I/O error occurs when closing the socket. Terminate t
server:
A server should be always running, waiting for incoming requests from clients. In case
server must be stopped for some reasons, call the close() method on the ServerSoc
instance:
1 serverSocket.close();
When the server is stopped, all currently connected clients will be disconnected.
The ServerSocket class also provides other methods which you can consult in
Javadoc here
import java.io.*;
import java.net.*;
import java.util.Date;
public class TimeServer {
while (true) {
Socket socket = serverSocket.accept();
writer.println(new Date().toString());}
And the following code is for a client program that simply connects to the serv
and prints the data received, and then terminates:
import java.net.*;
import java.io.*;
System.out.println(time);
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8. Statement stmt=con.createStatement();
9. ResultSet rs=stmt.executeQuery("select * from emp");
10. while(rs.next())
11. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString
(3));
12. con.close(); }catch(Exception e){ System.out.println(e);} }}
2) set classpath:
There are two ways to set the classpath:
o temporary
o permanent
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
You can read your big query and store results in some kind of buffer. And
only when buffer is full you should run subquery for all data collected in
buffer. This significantly reduces number of SQL statements to execute.
When you load a lot of records from database it is very, very important to
set proper fetch size on your jdbc connection. This reduces number of
physical hits to database socket and speeds your process
4. PreparedStatement
Java performance tuning tips relevent for tuning JDBC usage. The top tips
are:
Topic Description
Closing Describes the importance of closing JDBC driver objects when
objects when they are no longer needed.
not in use
Managing Describes techniques for improving transaction performance.
transaction
size
Working with Describes techniques for improving performance when using
statements the Statement or ResultSet objects.
and result
sets
Using Describes an adaptive buffering feature, which is designed to