Unit-1 Java (Nep)
Unit-1 Java (Nep)
nd
BCA 2 semester(NEP)
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.
There are four types of Java applications that can be created using Java programming:
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
SHWETHA RANI R S 1 ST BCA Page 4
OBJECT ORIENTED PROGRAMMMING WITH JAVA
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:
3. Object–oriented
5. Distributed
8. High Performance
.java) code(.class)
6. Simple, Small and Familiar: Java is a small and simple language. Many
features of C &C++that are either redundant or sources of unreliable code
are not part of Java.
• Pentium system
• Minimum16 MB memory
• A hard drive
• A mouse
Java environment
The JDK comes with a collection of tools that are used for developing
and running Java programs. They include:
• javac(Java compiler)
• java(Java interpreter)
• javap(Java disassemble)
• javah(for C headerfiles)
• jdb(Java debugger)
06 Javap Javadisassemble,whichenablesustoconvertbytecodefilesintoap
rogram description
07 Jdb Java debugger, which helps us to find errors in our programs
a) Stand–alone applications
b) Web applets
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:
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
Class Declaration:
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 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.
• 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
• Running the program: We need to use the Java Interpreter to run a stand-
alone program.At the command prompt type: java filename
Important:
Bytecode→filename.class(itwillbeautomaticallycreatedwhenwecompiletheJavapr
ogram)
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.
/** ....*/ known as documentation comment. This form of comment is used for
generating documentation automatically.
Import Statements: The next thing after a package statement may be a number
of import statements. This is similar to the # include statement in C.
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.
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.
Main Method Class: Since every Java stand-alone program requires a main
method as its starting point, this class is the essential part of a Java program. A
simple Java program may contain only this part. The main method creates objects
of various classes and establishes communications between them.
JAVA TOKENS:
1. Keywords:Keywordsareanessentialpartofalanguagedefinition.Javalangua
gehasreserved60wordsaskeywords.Someofthemare:case,private,public,pr
otected,static,super, throw, break, switch, do, final, class, finally etc.,
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
VARIABLES:
Variable names may consist of alphabets ,digits ,the under score and dollar characters.
• Uppercaseandlowercasearedistinct.ThismeansthatthevariableTotalisnotth
esameas total or TOTAL.
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:
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.
Size and range of Integer types
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
OPERATORS
OPERATORS IN JAVA
Operators in java
a. + (addition)
b. – (subtraction)
c. * (multiplication)
d. / (division)
e. % (modulus)
A. Integer Arithmetic: When both the operands in a single arithmetic
a+b=18
a*b=51
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.
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 NOT
4.ASSIGNMENT OPERATORS:
v op =exp;
Advantages:
• What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
5.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 --;
6.CONDITIONALOPERATORS:
exp1?exp2 :exp3
Working of ?:
exp3 is evaluated and its value becomes the value of the conditional expression.
Note that only one of the expressions (either exp2 orexp3) is evaluated.
In the above example ,x will be assigned the value of b.This can be achieved
using the if..else statement as follows:
7.BITWISE OPERATORS:
Java has a distinction of supporting special operators known as
bitwise operators for manipulation of data at values of bit level. These operators are used
for testing the bits or shifting them to the right or left. Bitwise operators may not be
applied to float or double.
Operato Meaning
r
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive
OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with
zero fill
8. SPECIALOPERATORS:
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.
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
Types of if statement:
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");
Output:
I am Not in if
Entry
Test
expressio True
n
Statement block
Fals
e
Statement x
Next statement
if(test expression)
{
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.
Entry
Test
True expression False
?
Statement x
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15
When a series of decisions are involved,we may have to use more than one if…else
statement in nested form
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too
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.
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output:
i is 20
THE SWITCHSTATEMENT
Java has a built-in multiway decision statement known as a switch. The
switch statement tests the value of a given variable (or expression) against a list of case
values and when a match is found,a block of statements associated with that case is
executed.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
case valueN:
statementN;
break;
default:
statementDefault;
}
When the switch is executed, the value of the expression is successfully compared against the values
value 1,value 2, If a case is found whose value matches with the value
Of the expression, then the block of statements that follows the case are 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.
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}}
Output:
i is greater than 2.
THE ?: OPERATOR:
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
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.
do {
//code to be executed / loop body
//update statement
}while (condition);
Working:
Since the test condition is evaluated at the bottom of the loop, the do...
while construct provides an exit-controlled loop and therefore the body of the
loop is always executed atleast once.
1
2
3
for(initialization;testcondition; increment)
The execution
} of the for statement is as follows:
2. The value of the control variable is tested using the test condition. The test
condition is a relational expression, such as i<10 that determines when the
loop will exit. If the condition is true,the body of the loop is
executed;otherwise the loop is terminated and the execution continues with
the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to
the for statement after evaluating the last statement in the loop. Now, the
control variable is incremented using an assignment statement such as i =
i + 1 and the new value of the control variable is again tested to see whether
it satisfies the loop condition. If the condition is satisfied, the body of the
loop is again executed. This process continues till the value of the control
variable fails to satisfy the test condition.
1
2
3
For-each Loop
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.
Let us see the example of print the elements of Java array using the for-each loop.
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
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class.
void means that this method does not have a return value
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!");
}
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.
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.
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.
arrayRefVar=new datatype[size];
//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:
10
20
70
40
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]);
}
}
Data is stored in row and column based index (also known as matrix form).
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
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.
.
SHWETHA RANI R S 1 ST BCA Page 39
OBJECT ORIENTED PROGRAMMMING WITH JAVA
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.
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;
ADDING METHODS:
A class with only data fields (and without methods that operate on that
data) has no life. The objects created by such a class cannot respond to any
messages. We must therefore add methods that are necessary for manipulating the
data contained in the class. Methods are declared inside the body of the class but
immediately after the declaration of instance variables.
type methodname(parameterlist)
method body;
The type specifies the type of value the method would return. This could
be a simple data type such as int as well as any class type. It could even be
void type, if the method does not return any value. The method name is a valid
identifier. The parameter list is always enclosed in parentheses. This list
contains variable names and types of all the values we want to give to the
method as input. The variables in the list are separated by commas.
Class Rectangle
int length,width;
length=x;
width=y;
}
}
Note that the method has a return type of void because it does not return
any value. We pass two integer values to the method which are then assigned
to the instance variables length and width. The getdata method is basically
added to provide values to the instance variables. Notice that we are able to
use directly length and width inside the method
CREATING OBJECTS:
Objects in Java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.
the first statement declares a variable to hold the object reference and the second
one actually assigns the object reference to the variable. The variable rect1 is now
an object of the rectangle class.
Eg:
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
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;
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 25 rect2.width 30
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.
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
{
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
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[])
{
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
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
modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
} }
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public 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();
obj.msg();
}
}
INBUILT CLASSES
STRING CLASS
The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on
String objects such as trimming, concatenating, converting, comparing, replacing strings etc.
some important methods of String class.
Java String toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this String into uppercase letter and
String toLowerCase() method into lowercase letter.
public class Stringoperation1
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.toUpperCase()); //SACHIN
System.out.println(s.toLowerCase()); //sachin
System.out.println(s); //Sachin(no change in original)
}
}
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
public class Stringoperation2
{
public static void main(String args[])
{
String s=" Sachin ";
System.out.println(s); // Sachin
System.out.println(s.trim()); //Sachin
}
}
output
Sachin
Sachin
Java String charAt() Method
The String class charAt() method returns a character at specified index.
Stringoperation4.java
public class Stringoperation4
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3)); //h
}
}
Output
S
h
Java String length() Method
The String class length() method returns length of the specified String
public class Stringoperation5
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.length());//6
} }
Output
6
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String.
Stringoperation7.java
public class Stringoperation7
{
public static void main(String args[])
{
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
} }
Output
1010
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 −
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.