Unit-1 Java (Nep)
Unit-1 Java (Nep)
nd
BCA 2 semester(NEP)
Dr VIKRAM B Page 1
OBJECT ORIENTED PROGRAMMMING WITH JAVA
SYLLABUS
Unit - 1
Introduction to Java: Basics of Java programming. Data types, Variables, Operators, Control
structures including selection, Looping, Java methods, Overloading, Math class, Arrays in java.
Objects and Classes: Basics of objects and classes in java, Constructors, Finalizer, Visibility
modifiers, Methods and objects, Inbuilt classes like String, Character, String Buffer, File, this
reference.
Unit-2
Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object
class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator,
Abstract class, Interface in java, Package in java, UTIL package.
Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.
Unit - 3
Event and GUI programming: Event handling in java, Event types, Mouse and key events,
GUI Basics, Panels, Frames, Layout Managers: Flow Layout, Border Layout, Grid Layout, GUI
components like Buttons, Check Boxes, Radio Buttons,
Labels, Text Fields, Text Areas, Combo Boxes, Lists, Scroll Bars, Sliders, Windows, Menus, Dialog
Box, Applet and its life cycle, Introduction to swing. Exceptional handling mechanism.
I/O programming: Text and Binary I/O, Binary I/O classes, Object I/O, Random Access Files.
INTRODUCTION TO JAVA
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun Microsystems, James Gosling is
known as the father of Java. Before Java, its name was Oak. Since Oak was already a
registered company, so James Gosling and his team changed the name from Oak to Java.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop
computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the
server and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices
such as set-top boxes, phone, and appliances.
Web Applications: An applications that run on the server is called web applications. We
use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.
Message communication
Objects: It is an instance of a class. It can also be defined as basic run-
time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to
handle.
Polymorphism: (Greek word. poly means many, morphism means different forms of
representation)
It is another important OOP concept. Polymorphism, a Greek term, means the ability
to take more than one form. The process of making an operator to exhibit different behaviour in
different instances is known as operator overloading. Using a single function name to perform
different types of tasks is known as function overloading.
Dynamic binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding also known as latebinding means that the code associated
with a given procedure call is not known until the time of the call at run-time.
JAVA FEATURES:
.java) code(.class)
Java environment
The JDK comes with a collection of tools that are used for developing
and running Java programs. They include:
Appletviewer (for viewing Java applets)
javac(Java compiler)
java(Java interpreter)
javap(Java disassemble)
javah(for C headerfiles)
javadoc(for creating HTML documents)
jdb(Java debugger)
06 Javap Javadisassemble,whichenablesustoconvertbytecodefilesintoap
rogram description
07 Jdb Java debugger, which helps us to find errors in our programs
Stand – alone applications are programs written in Java to carry out certain tasks
on a stand –alone local computer. HotJava itself is a Java application program.
Executing a stand-alone Java program involves two steps:
1. Compiling source code into bytecode using javac compiler
Applets are small Java programs developed for Internet applications. An applet
located on a distant computer (Server) can be downloaded via Internet and
executed on a local computer(Client)using a Java– capable browser.
SIMPLE JAVA PROGRAM
Class sample
The first line class sample declares a class, which is an object-oriented construct.
sample is a Java identifier that specifies the name of the class to be defined.
Opening Brace:
Every class definition in Java begins with an opening brace { and end with a
matching closing brace }
The main Line:
The third line public static void main(String args[]) defines a method named
main. Conceptually, this is similar to the main() function in C / C++. Every Java
application program must include the main() method. This is the starting point for
the interpreter to begin the execution of the program. A Java application can have
any number of classes but only one of them must include a main method to initiate
the execution.
All parameters to a method are declared inside a pair of
parentheses. Here, String args[] declares a parameter named args, which contains
an array of objects of the class type String.
The output Line: The only executable statement in the program is
Creating the program: We can create a program using any text editor.
We must save the program using filename.java extension ensuring that the
filename contains the class name properly. This file is called source file.
Note that, all Java source files will have the extension java. Further, If a
program contains multiple classes, then filename must be the class name
of the class containing the main method.
Compiling the program: To compile the program, we must run the Java Compiler
javac, with the name of the source file on the command line
javac filename.java
Bytecodefilename.class(itwillbeautomaticallycreatedwhenwecompiletheJavapr
ogram)
JavaCompilerit converts source code into bytecode.
Sourcecode Bytecode
The virtual machine code is not machine specific. The machine specific
code (known as machine code) is generated by the Java interpreter by acting as an
intermediatry between the virtual machine and the real machine. Interpreter is
different for different machines.
VirtualMachine RealMachine
A Java program may contain many classes of which only one class
defines a main method. Classes contain data members and methods that
operate on the data members of the class. Methods may contain data type
declarations and executable statements. To write a Java program, we first
define classes and then put them together.
This statement instructs the interpreter to load the text class contained in the
package student. Using import statements ,we can have access to classes that are
part of other named packages.
Interface Statements: An interface is like a class but includes a group of method
declarations. This is also an optional section and is used only when we wish to
implement the multiple inheritance feature in the program.
Class Definitions: A Java program may contain multiple class definitions. Classes
are the primary and essential elements of a Java program. These classes are used
to map the objects of real-world problems. The number of classes used depends
on the complexity of the problem.
JAVA TOKENS:
1. Keywords:Keywordsareanessentialpartofalanguagedefinition.Javalangua
gehasreserved60wordsaskeywords.Someofthemare:case,private,public,pr
otected,static,super, throw, break, switch, do, final, class, finally etc.,
Keywords have specific meaning in Java, we cannot use them as
names for variables, classes, methods and so on. All keywords are
to be written in lower-case letters. Java is case-sensitive.
2. Identifiers: Identifiers are programmer-designed tokens. They are used for
naming classes, methods, variables, objects, labels, packages and
interfaces in a program. Java identifiers follow the following rules:
a) They can have alphabets, digits and the underscore.
b) They must not begin with a digit.
c) Uppercase and lowercase are distinct.
d) They can be of any length.
3. Literals:LiteralsinJavaareasequenceofcharacters(digits,letterandotherchar
acters) that represent constant values to be stored in variables. Java
language specifies five types of literals namely:
a) Integer literals
b) Floating-point literals
c) Character literals
d) String literals
e) Boolean literals
4. Operators: An operator is a symbol that takes one or more arguments and
operates on them to produce a result.
5. Separators: Separators are symbols used to indicate where groups of code
are divided and arranged. They basically define the shape and function of
our code. Some of these operators are : ( ) { } [] , ; .
VARIABLES:
A variable is an identifier that denotes a storage location used to store a
data value. A variable may take different values at different times during the
execution of the program. A variable name can be chosen by the programmer in a
meaningful way so as to reflect what it represents in the program.
Eg: average, height, total_ height, class Strength
Variable names may consist of alphabets ,digits ,the under score and dollar characters.
They must not begin with a digit.
Uppercaseandlowercasearedistinct.ThismeansthatthevariableTotalisnotth
esameas total or TOTAL.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
DATATYPES:
Data types specify the size and type of values that can be stored. Java
language is rich in its data types. The variety of data types available allow the
programmer to select the type appropriate to the needs of the application. Data
types in Java are:
a. Primitive types(also called intrinsic or built-in types)
b. Derived types(also known as reference types)
1. Integer Types :Integer type can hold whole numbers such as 123, -96 and
5639. The size of the values that can be stored depends on the integer data
type we choose. Java supports 4 types of integers namely byte, short, int
and long. Java does not support the concept of unsigned types and
therefore all Java values are signed meaning they can be positive or
negative.
Type Size
Byte 1byte
short 2bytes
int 4bytes
long 8bytes
Integer
2. Floating point types: Integer types can hold only whole numbers and
therefore we use another type known as floating point type to hold numbers
containing fractional parts such as 27.59, -1.375 (known as floating point
constants). There are two kinds of floating point storage in Java.The float
type values are single-precision numbers while the double types represent
double precision
Floating point
float double
Type Size
float 4bytes
double 8bytes
d. / (division)
e. % (modulus)
A. Integer Arithmetic: When both the operands in a single arithmetic
expression such as a + b are integers, the expression is called an integer
expression and the operation is called integer arithmetic. Integer
arithmetic always yields an integer value.
a-b=10
a+b=18
a*b=51
a / b=3(decimal part truncated)
a%b=2(remainder of integer division)
B. Real Arithmetic: An arithmetic operation involving only real
operands is called real arithmetic. A real operand may assume values
either in decimal or exponential notation.
C. Mixed – mode Arithmetic: When one of the operands is real and the
other is integer, the expression is called a mixed – mode arithmetic
expression. If either operand is of the real type, then the other operand
is converted to real and the real arithmetic is performed.The result will
be a real.
Eg:15/ 10.0 produces the result 1.5
2. RELATIONALOPERATORS:
Relational operators are used to compare two quantities.
Operator Meaning
< Is less than
<= Is less than or equal to
> Isgreaterthan
>= Is greater than or equal to
== Is equal to
!= Is not equal to
3. LOGICALOPERATORS:
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
1. ASSIGNMENT OPERATORS:
What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
The statement is more concise and easier to read.
Use of shorthand operator results in a more efficient code.
2. INCREMENTANDDECREMENTOPERATORS:
Java supports increment and decrement operators namely++ and- -
The operator ++ adds 1 to the operand while --subtracts1. Both are unary
operators and are used in the following form:
++m; or m++;
-- m or m --;
5. SPECIALOPERATORS:
Java supports some special operators:
a. Instanceof
b. Member selection operator(.)
InstanceofOperator:
The instanceof is an object reference operator and returns true if the object
on the left-hand side is an instance of the class given on the right-hand side. This operator
allows us to determine whether the object belongs to a particular class or not.
E.g.: person instance of student
Is true if the object person belongs to the class student; otherwise it is false.
Dot operator:
The dot operator(.) is used to access the instance variables and methods of class
objects.
E.g.: person1.age // reference to the variable age person1.salary() //reference to the
method salary()
It is also used to access classes and sub-packages from a package.
Selection statements are a program control structure in Java. As the name suggests, they are
used to select an execution path if a certain condition is met. There are three selection statements in
Java: if, if..else, and switch.
When a program breaks the sequential flow and jumps to another part of
the code, it is called branching. When the branching is based on a particular
condition, it is known as conditional branching.If branching takes place without
any decision,it is known as unconditional branching.
Java language possesses such decision making capabilities and supports
the following statements known as control or decision making statements.
1. If statement
2. Switch statement
DECISION MAKINGWITHIFSTATMENT
if statement is a powerful decision making statement and is used to
control the flow of execution of statements .It is basically a two–way decision statement
and is used in conjunction with an expression.
If(test expression)
It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression (relation or condition) is „true‟ or „false‟ it transfers the
control to a particular statement. This point of program has two paths to follow, one for
the true condition and the other for the false condition.
Entry
Test
expression
False
True
1. Simple if statement
2. If...else statement
4. Elseifladder
SIMPLE IF STATMENT
if(test expression)
Statement-block;
Statement x;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}
Output:
I am Not in if
Test
expressio True
Statement block
Fals
Statement x
Next statement
Else
}
Statement x;
If the test expression is true, then the true-block statement (s) immediately
following the if statement, are executed; otherwise, the false -block statement (s)
are executed. In either case, either true– block or false – block will be executed,
not both.
Test
True expression False
?
Statement x
When a series of decisions are involved,we may have to use more than one if…else
statement in nested form
if (i == 10)
There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement associated
with each else is an if.
This construct is known as the elseif ladder. The conditions are evaluated from the top
downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement x(skipping the rest of the
ladder).When all the n conditions becomes false, then the final else containing the default
– statement will be executed.
The break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement, transferring the control to the
statement-x following the switch.
The default is an optional case. When present, it will be executed if the value of
the expression does not match with any of the case values. If not present, no action
takes place when all matches fail and the control goes to the statement– x.
The Java language has an unusual operator, useful for making two-way
decisions. This operator is a combination of ? and : and takes three operands. This
operator is popularly known as the conditional operator.
LOOPING
The process of repeatedly executing a block of statements is known as
looping. The statements in the block may be executed any number of times, from zero to
infinite number.If a loop continues forever, it is called an infinite loop.
A looping process, in general would include the following four steps:
2. The do statement
The simplest of all the looping structures in Java is the while statement.
Initialization;
while(test condition)
{
Body of the loop
}
Working:
Thewhileisanentrycontrolledloopstatement.Thetestconditionisevaluated
andif the condition is true, then the body of the loop is executed. After execution
of the body, the test condition is once again evaluated and if it is true, the body is
executed once again. This process of repeated execution of the body continues
until the test condition finally becomes false and the control is transferred out of
the loop. On exit, the program continues with the statement immediately after the
body of the loop.
while Example program:
public class While Example {
public static void main(String[] args) {
int i=1;
while(i<=3){
System.out.println(i);
i++;
}
}
}
do {
//code to be executed / loop body
//update statement
}while (condition);
Working:
S
OBJECT ORIENTED PROGRAMMMING WITH JAVA
for(initialization;testcondition; increment)
Output
1
2
3
JAVA METHODS
A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known
as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod () {
// code to be executed
}
}
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String args[])
{
myMethod();
}
}
Output: I just got executed!
OVERLOADING
METHOD OVERLOADING
If a class has having same name but different in parameters, it is known as Method Overloading.
Advantage of method overloading
Method overloading increases the readability of the program.
Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method in an object,
Java matches up the method name first and then the number and type of
parameters to decide which one of the definitions to execute. This process is
known as polymorphism.
To create an overloaded method, all we have to do is to provide several
different method definitions in the class, all with the same name, but with different
parameter lists. The difference may either be in the number or type of arguments.
That is, each parameter list should be unique. Note that the methods return type
does not play a role in this.
Different ways to overload the method
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers. In this example, we are creating static
methods so that we don't need to create instance for calling methods.
S Dr VIKRAM B 1ST BCA Page 37
OBJECT ORIENTED PROGRAMMMING WITH JAVA
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));
}
}
Output:
22
33
Math.function_name()Exampl
e:
double y=Math.sqrt(x);
ARRAYS IN JAVA
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
1. dataType[ ] arr; (or)
2. dataType arr[ ];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output: 70
10 40
20 50
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
Dr VIKRAM B 1ST BCA Page 40
S
OBJECT ORIENTED PROGRAMMMING WITH JAVA
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.println(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445
Unit-1
Objects and Classes: Basics of objects and classes in java, Constructors, Finalizer, Visibility
modifiers, Methods and objects, Inbuilt classes like String, Character, String Buffer, File, this
reference.
A class is a user-defined data type with a template that serves to define its
properties.Once the class type has been defined, we can create“variable”of that
type using declarations that are similar to the basic type declarations. In Java, these
variables are termed as instance of classes, which are the actual objects.
The basic form of class declaration is:
Class classname
{
Variable declaration;
Method declaration;
}
ADDING VARIABLES:
Class Rectangle
{
int length;
int width;
}
class Rectangle contains two integer type instance variables. It is allowed to declare them in one line
as
int length,width;
It is important to understand that each object has its own copy of the
instance variables of its class. This means that any changes to the variables of one
object have no effect on the variables of another. It is also possible to create two
or more references to the same object.
Eg : Rectangle r1=new Rectangle() ;
Rectangle r2 =r1
r1
rectangleobject
r2
here object name is the name of the object, variable name is the name of the
instance variable inside the object that we wish to access, method name is the
method that we wish to call, and type and number with the parameter list of the
method name declared in the class .The instance variables of the rectangle class
may be accessed and assigned values as follows:
rect1.lenght=15;
rect1.width=25;
rect2.lenght=18;
rect2.width=30;
Dr VIKRAM B 1ST BCA Page 43
OBJECT ORIENTED PROGRAMMMING WITH JAVA
note that the two objects rect1 and rect2 store different values as shown
below:rect1 rect1 rect2
rect1.length rect2.length 18
15
rect1.width rect2.width 30
25
This is one way of assigning values to the variables in the objects. Another way
and more convenient way of assigning values to the instance variables is to use a
method that is declared inside the class.
Rectangle rect1=new Rectangle (); // creating an object
this code create rect1 object and then passes in the values 15 and 25 for the x and y
parameters of the method getdata. This method then assigns these values to length and width
variables respectively.
CONSTRUCTORS:
All objects that are created must be given initial values using two
approaches. The first approach uses the dot operator to access the instance
variables and then assigns values to them individually. It can be a tedious
approach to initialize all the variables of all the objects.
The second approach takes the help of a method like get data to initialize
rect1 .getdata(15,25 ) ;
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also
class Rectangle
{
int length, width;
Rectangle (int x, int y) //defining constructor
Dr VIKRAM B 1ST BCA Page 44
OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
length = x;
width = y;
}
int rectArea ( )
{
return (length *width);
}
}
class RectangleArea
{
public static void main (string args[])
{
Rectangle rect1= new Rectangle (15, 10); //calling constructor
int areal = rectl.rectArea( );
System.out.println ("Areal = "+ areal);
}
}
Output
Areal = 150
In parameterized constructor at the time of object instantiation, the constructor is explicitly
invoked by passing arguments.
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Example of default constructor
class perimeter
{
int length;
int breadth;
perimeter () //default constructor
{
length = 0;
breadth = 0;
}
perimeter (int x, int y) //parameterized constructor
{
length = x;
breadth=y;
}
void cal_perimeter ()
{
int peri;
peri= 2* (length + breadth);
System.out.println("\nThe perimeter of the rectangle is :"+peri);
}
}
class Ex_default_c
{
public static void main(String args[])
Dr VIKRAM B 1ST BCA Page 45
OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
perimeter p1 = new perimeter (); // calling default constructor
perimeter p2= new perimeter (5, 10); // calling parameterized constructor
p1.cal_perimeter();
p2.cal_perimeter ();
Output of Program :
The perimeter of the rectangle is :0
The perimeter of the rectangle is : 30
FINALIZER METHODS:
We have seen that a constructor method is used to initialize an object when it is declared.
This process is known as initialization. Similarly, Java supports a concept called finalization,
which is just opposite to initialization.
We know that Java run-time is an automatic garbage collecting system. It automatically
frees up the memory resources used by the objects. But objects may hold other non-object
resources such as file descriptors or window system fonts. The garbage collector cannot free
these resources. In order to free these resources we must use a finalizer method. This is similar
to destructors in C++.
The finalizer method is simply finalize() and can be added to any class. Java calls that method
whenever it is about to reclaim the space for that object. The finalize method should explicitly
define the tasks to be performed.
The finalize( ) method has this general form:
protected void finalize( )
{
//finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class. Note that finalize( ) is only called just prior to garbage collection. It is not
called when an object goes out-of-scope.
Finalize() is the method of Object class. This method is called just before an object is
garbage collected. finalize() method overrides to dispose system resources, perform clean-up
activities and minimize memory leaks
VISIBILITY MODIFIERS
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed
from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within
Dr VIKRAM B 1ST BCA Page 46
OBJECT ORIENTED PROGRAMMMING WITH JAVA
the class, outside the class, within the package and outside the package.
Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}}
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class. It provides more accessibility than the default
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Character class
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 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.
Methods
Method Description
codePointAt(char[]a, int index) Returns the codePoint for the specified index of
the given array.
codePointAt(char[]a, int index, Returns the codePoint of the char array at the
int limit ) specified index where only the elements of the
array with the index less than the specified limit
being used.
codePointBefore(char[]a, int Returns the codePoint for the given array in the
index) preceding index.
StringBuffer class
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following
are the important points about StringBuffer −
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
Class Declaration
Following is the declaration for java.lang.StringBuffer class −
public final class StringBuffer
extends Object
implements Serializable, CharSequence
Class constructors
Sr.No. Constructor & Description
1 StringBuffer()
This constructs a string buffer with no characters in it and an initial capacity of 16
characters.
2 StringBuffer(CharSequence seq)
This constructs a string buffer that contains the same characters as the specified
CharSequence.
3 StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified initial capacity.
4 StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified string.
Useful Methods
Modifier Method Description
and Type
Boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]
Boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.
Boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.
this reference
The this is a keyword in Java which is used as a reference to the object of the
current class, with in an instance method or a constructor. Using this you can refer the
members of a class such as constructors, variables and methods.
Using “this” you can −
Differentiate the instance variables from local variables if they have same names, within a
constructor or a method.
class Student
{
int age;
Student(int age)
{
this.age = age;
}
}
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.