0% found this document useful (0 votes)
29 views46 pages

Oops M1

Uploaded by

mca.bca.2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views46 pages

Oops M1

Uploaded by

mca.bca.2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Object Oriented using Java 22MCA22

MODULE-01
OOPS CONCEPTS AND JAVA PROGRAMMING: OOP concepts: Classes and objects, data abstraction,
encapsulation,Inheritance, benefits of inheritance, polymorphism, procedural and object oriented programming
paradigm. Java programming: History of java, comments data types, variables, constants, scope and life time of
variables, operators,operator hierarchy, expressions, type conversion and casting, enumerated types, control flow
statements, jump statements,simple java stand alone programs, arrays, console input and output, formatting
output, constructors ,methods, parameterpassing, static fields and methods, access control, this reference,
overloading methods and constructors, recursion, garbagecollection, exploring string class.

What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming language.

History of java
 Earlier, C++ was widely used to write object oriented programming languages; however,
it wasnot a platform independent and needed to be recompiled for each different
processor.
 Where as Java applications are typically compiled to byte code (.class file) that can run
on anyplatform (OS + Processor).
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June1991. Developed by the Sun Microsystems.
 James Gosling known as the father of Java.
 Before Java, its name was Oak. Since Oak was already registered company,
so JamesGosling and his team changed the name from Oak to Java.
 It went by the name Green later, and was later renamed Java, from Java coffee, said to
be consumedin large quantities by the Java language's creators.

Platform: Any hardware or software environment in which a program runs, is known


as platform.Since Java has a runtime environment (JRE) and API, it is called a platform.

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 desk to
computer
 Java Enterprise Edition (JEE): It is used to create large programs that run on the
server andmanages heavy traffic and complex transactions.
 Java Micro Edition (JME): It is used to develop applications for small device
such as set- topboxes, phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java programming

Standalone Applications: Java standalone applications uses GUI components such a


AWT, Swing,and JavaFX. These components contain buttons, list, menu, scroll panel, etc It
is also known as desktop alienations.

Enterprise Applications: An application which is distributed in nature is


called enterpriseapplications.
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

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.

Mobile Applications: Java ME is a cross-platform to develop mobile applications


which runacross smartphones. Java is a platform for App Development in Android.

Features of Java:-
1. Simple: Java is a simple language because its syntax is simple, clean, and easy to understand.
Complex and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For
example, pointer and operator overloading are not used in Java.

2. Object-Oriented: In Java, everything is in the form of the object. It means it has some data
and behavior. A program must have at least one class and object.

3. Robust: Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection features
make it strong.

4. Secure: Java is a secure programming language because it has no explicit pointer and programs
runs in the virtual machine. Java contains a security manager that defines the access of Java classes.

5. Platform-Independent: Java provides a guarantee that code writes once and run anywhere.
This bytecode is platform-independent and can be run on any machine.

6. Portable: Java Byte code can be carried to any platform. No implementation dependent
features.Everything related to storage is predefined, for example, the size of primitive data
types.

7. High Performance: Java is an interpreted language. Java enables high performance with the
use ofthe Just-In-Time compiler.

8. Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the internet. EJB
and RMI are usedto create a distributed system.
9. Multi-threaded: Java also supports multi-threading. It means to handle more than one job a
time.
10..Compiled and interpreted language :Java uses a two step translation process. Java source
codeis compiled down to "byte code" by the Java compiler (javac). Then byte code is converted into
machine code by the Java Interpreter (Java Virtual Machine - JVM).

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

OOPs (Object Oriented Programming System)

Object-oriented programming is a way of solving a complex problem by breaking them into a small
sub-problem. An object is a real-world entity. It is easier to develop a program by using an object. In
OOPs, we create programs using class and object in a structured manner.

Class: A class is a template or blueprint or prototype that defines data members and methods of an
object. An object is the instance of the class. We can define a class by using the class keyword.

Object: An object is a real-world entity that can be identified distinctly. For example, a desk, a
circle can be considered as objects. An object has a unique behavior, identity, and state. Data fields
with their current values represent the state of an object (also known as its properties or attributes).

Abstraction: An abstraction is a method of hiding irrelevant information from the user.


For example, the driver only knows how to drive a car; there is no need to know how does the car
run. We can make a class abstract by using the keyword abstract. In Java, we use abstract class and
interface to achieve abstraction.

Encapsulation: An encapsulation is the process of binding data and functions into a single unit.
A class is an example of encapsulation. In Java, Java bean is a fully encapsulated class.

Inheritance: Inheritance is the mechanism in which one class acquire all the features of another
class. We can achieve inheritance by using the extends keyword. It facilitates the reusability of
the code.

Polymorphism: The polymorphism is the ability to appear in many forms. In other words, single
action in different ways. For example, a boy in the classroom behaves like a student, in house
behaves like a son. There are two types of polymorphism: run time polymorphism and compile-time
polymorphism.

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.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Message communication: An object – oriented program consists of a set of objects that


communicate with each other. The process of programming in an object-oriented language therefore
involves the following basic steps:
1. Creating classes that define objects and their behavior.
2. Creating objects from class definitions and
3. Establishing communication among object

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Documentation section: A set of comment lines like: name of the program, author name, date of
creation, etc.
a. Package statement: This is the first statement allowed in Java file, this statement declares a
package names.
b. Import statement: This statement imports the packages that the classes and methods of
particular package can be used in the current program.
c. Interface statement: An interface is like a class but includes group of methods declaration. Inter
face is used to implement the multiple inheritance in the program.
e . Class definition/statements: A Java program may contains one more class definitions.
f. Main method class: Every Java standalone program requires a main method, as it begins the
execution, this is essential part of Java program

Important:

Source code→ filename.java(program written by the programmer)


Byte code→ filename.class(it will be automatically created when we compile the Java
program)

Java Compiler→it converts source code into bytecode.


Java Interpreter→it translates bytecode into machine code.

JAVA VIRTUAL MACHINE (JVM)

All language compiler translates source code into machine code for a specific computer .Java
compiler also does the same thing .Java compiler produces an inter media code known as bytecode
for a machine that does not exist. This machine is called the Java Virtual Machine (JVM)and it exists
only inside the computer memory.It is simulated computer within the computer and does all major
functions of a real computer.

Java program java compiler virtual machine

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

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 intermediary between the virtual machine
and the real machine. Interpreter is different for different machines.

Byte code java interpreter machine code

Simple Java Program


import java.io.*;
public class Welcome
{
public static void main (String args[])
{
System.out.println (“welcome to Java Program”);
}
}

public: It is access specifier and this method can be called from outside also.
static: This main method must always declared as static because the whole program has only one
main method and without using object the main method can be executed by using the class name.
void: The main method does not return anything.
main: - The main method similar to main function in c and c++. This main method call first (execute
first) by the interpreter to run the java program. String: It is built-in class under language package.
args []: This is an array of type string. a command line arguments holds the argument in this array.
System.out.println:
System: It is a class which contains several useful methods.
out: It is an object for a system class to execute the method.
println: This is a method to print string which can be given within the double coats. After printed the
contents the cursor should be positioned at beginning of next line
print: after printed the content the cursor should be positioned next to the printed content

Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
Types of Java Comments
There are 3 types of comments in java.
• Single Line Comment
• Multi Line Comment
• Documentation Comment
Java Single Line Comment:
The single line comment is used to comment only one line.
Syntax:
//This is single line comment

Example:
class CommentExample1 {
public static void main(String[] args) { int i=10; //Here, i is a variable
System.out.println(i);
}
}
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

Java Multi Line Comment:


The multiline comment is used to comment multiple lines of code.
Syntax:
/*
*/
Example:
This is multi line comment

class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and print variable in java. */ int i=10; System.out.println(i);
}
}

Java Documentation Comment:


• The documentation comment is used to create documentation API.
• To create documentation API, you need to use Javadoc
tool. Syntax:
/**
This is documentation comment
*/

Java Tokens: Tokens are the basic building-blocks of the java language or it is a small unit in the
program. There exist 6 types of tokens in JAVA.
1. Keywords
2. Identifier
3. Separators
4. Comments

Keywords: Java keywords are also known as reserved words. Keywords are particular words that
act as a key to a code. These are predefined words by Java so they cannot be used as a variable or
object name or class name.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Some points regarding Java keywords:


 const and goto are resevered words but not used.
 true, false and null are literals, not keywords.
 All keywords are in lower-case.

Identifier: Identifier is case sensitive names given to variable, methods, class, object, packages ,etc

Rules for identifiers:


1) May consists of letters, digits, underscore and a dollar symbol.
2) Must begin with a letter (A to Z or a to z), dollar ($) or an underscore (_).
3) A key word cannot be used as an identifier.
4) They are case sensitive.
5) Whitespaces are not allowed. Examples of legal identifiers: age, $salary, _value, 1_value

Separators: They are character used to group and arrange Java source code into segments.
Java uses 6 types of separators:

Separator Name Use


. Period It is used to separate the package name from
sub-package name & class name.
, Comma It is used to separate the consecutive
parameters in the method definition. It is also
used to separate the consecutive variables of
same type while declaration.
; Semicolon It is used to terminate the statement in Java.
() Parenthesis This holds the list of parameters in method
definition. Also used in control statements &
type casting.
{} Braces This is used to define the block/scope of code,
class, methods.
[] Brackets It is used in array declaration.

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.

Rules for naming a variable:


• They must not begin with a digit.
• Uppercase and lowercase are distinct. This means that the variable Total is not the same as total
or TOTAL.
• It should not be a keyword.
• White space is not allowed.
• Variable names can be of any length.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

There are three types of variables in java:


1.Local variable
2.Instance(member) variable
3. Static(Class) variable.

Scope determine when the variable is created and destroyed


1) Local Variables: A variable declared inside the body block of the method or Constructor
is called a local variable.
The scope of these variables exists only within the block in which the variable is declared. i.e., we
can access these variables only within that block.
Initialization of the local variable is mandatory before using it in the defined scope.
A local variable cannot be defined with "static" keyword.

2) Instance variables [Member variables] :- Instance variables are non-static variables and are
declared in a class outside any method, constructor, or block.
As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifies for instance variables. If we do not specify any
access specifier, then the default access specifier will be used.
Initialization of Instance Variable is not mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.

3) Static variables [class variables]:- Static variables are also known as Class variables. A variable that
is declared as static keyword is called a static variable

These variables are declared similarly as instance variables. The difference is that static variables
are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of
how many objects we create.
Static variables are created at the start of program execution and destroyed automatically when
execution ends.
Initialization of Static Variable is not Mandatory. Its default value is 0

Example : public class A


{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

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.

Size and range of Integer


types Type Size
Byte 1byte
Short 2bytes
int 4bytes
long 8bytes

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
Size and range of Floating point types
Type Size
float 4bytes
double 8bytes
3. Character type: In order to store character constants in memory, Java provides a character data
type called char. The char type assumes a size of 2 bytes but, basically it can hold only a single
character.

4. Boolean type: Boolean type is used when we want to test a particular condition during the
execution of the program. There are only two values that a Boolean type can take: true or false.
Both these words have been declared as keywords. Boolean type is denoted by the keyword
Boolean and uses only one bit of storage.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

OPERATORS IN JAVA

Operators: An operator is a symbol that takes one or more arguments and operates on them to
produce a result.

Types of operators:
 Unary Operator: An Operator which can accepts only one operands is known as unary
operator Eg: not(!), increment(++), decrement(--)
 Binary Operator: An Operator which can accepts two operands is known as Binary
operator Eg: Arithmetic, logical, relational operator
 Ternary Operator: An Operator which can accept three operands is known as ternary operator.
Eg: conditional operands.

1. ARITHMATIC OPERATORS: An operator which allows the user to perform basic


arithmetic operation.
1. + (addition)
2. – (subtraction)
3. * (multiplication)
4. / (division)
5. % (modulus)

2.RELATIONAL OPERATORS: Relational operators are used to compare two quantities.


Operator Meaning
1. < Is less than
2. <= Is less than or equal to
3. > Is greater than
4 . >= Is greater than or equal to
5. == Is equal to
6. != Is not equal to

3. LOGICAL OPERATORS:
Logical operates are used to check whether an expression is true or false.

Operator Meaning
1. && logical AND
2. || logical OR
3. ! logical NOT

4. ASSIGNMENT OPERATORS: Assignment operators are used to assign the value of


an expression to a variable.
Normally we use = symbol for assignment, in addition to that java supports shorthand assignment
operator.

Ex: v op =exp;
where v is a variable, exp is an expression and op is a Java binary operator. The operator op =is
known as the shorthand assignment operator.
V op = exp; is equivalent to v =v op
(exp); E.g.: x+=y+1 is same as x=x+

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

(y+1);

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

5. Unary Operators: Unary operators need only one operand. They are used to increment, decrement
or negate a value.
– : Unary minus :used for negating the values.
+ : Unary plus : indicates the positive value.It performs an automatic conversion to int when the
type of its operand is the byte, char, or short. This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1.There are two varieties
of increment operators.
 Post-Increment: Value is first used for computing the result and
then incremented.Ex: m++
 Pre-Increment: Value is incremented first, and then the result
is computed.Ex: ++m
- - : Decrement operator, used for decrementing the value by 1. There are two varieties
of decrement operators.
 Post-decrement: Value is first used for computing the result and
then decremented.Ex: m--
 Pre-Decrement: Value is decremented first, and then
the result isEx:--m

6. CONDITIONAL OPERATORS(Ternary operator): Ternary operator is a shorthand


version ofthe if-else statement. It has three operands and hence the name ternary.
general format : condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the statements after
the „?‟ else execute the statements after the „:.‟

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.

Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with

8. java supports some special operators:


1. Instanceof
2. Member selection operator(.)

Instanceof Operator:
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
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

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.

Expressions
• An expression is a syntactic construction that has a value.
• Expressions are formed by combining variables, constants, and method returned values
using operators.
The Type Promotion Rules:
• With in expression, it is possible to mix two or more different types of data as long as they
are compatible with each other.
• you can mix short and long within an expression because they are both numeric types.
• When different types of data are mixed an expression, they are all converted to the same type.
• All char, byte and short values are promoted to int.
• If one operand is a long, the whole expression is promoted to long.
• If one operand is a float operand, the entire is promoted to float.
• If one operand is double, the result is double
Ex:
class cit
{
public static void main(String[] args)
{
byte b;
int i;
b=10;
char ch1=‘a’,ch2=‘b’;
ch1=(char)(ch1 + ch2);
i=b * b;
// no cast needed System.out.println(“ i and b:” +i+ “ “+b);
System.out.println(ch1);

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

}
}
Type conversion and casting:
 Booleans cannot be converted to other types.
 For the other primitive types (char, byte, short, int, long, float, and double), there are two kinds of conversion:
1. Implicit or Widening or Automatic Type Conversion
2. Explicit or Narrowing or Type casting Implicit conversions: An implicit conversion means that a value of one type
is changed to a value of another type without any special directive from the programmer.
 A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly
by the JVM.
 The lower size is widened to higher size. This is also named as automatic type conversion.

EX:

public class Test


{
public static void main(String[] args)
{
int i = 100;
//occupies 4 bytes long l = i;
// occupies 8 bytes double f = l;
// occupies 8 bytes
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
OUTPUT:
Int value 100
Long value 100 Float value 100.0

Explicit conversions:
 If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 The general form of cast is (target-type)expression
 Here, target-type specifies the desired type to convert the specified value to.
 The thumb rule is, on both sides, the same data type should exist.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

EX:
class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d;
int i = (int)l;
System.out.println("Double value "+d); //100.04
System.out.println("Long value "+l); // 100
System.out.println("Int value "+i); // 100
}
}

Enumerated types:
A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has
the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just
like classes, you can give them constructors, add instance variables and methods, and even
implement interfaces.
Properties of Enum in Java
There are certain properties followed by Enum as mentioned below:
 Every enum is internally implemented by using Class.
 Every enum constant represents an object of type enum.
 Enum type can be passed as an argument to switch statements.
 Every enum constant is always implicitly public static final. Since it is static, we can access it
by using the enum Name. Since it is final, we can’t create child enums.
 We can declare the main() method inside the enum. Hence we can invoke the enum directly
from the Command Prompt.

EX: Declaration outside the class


// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
EX: Declaration inside a class
// enum declaration inside a class.

public class Test {


enum Color {
RED,
GREEN,
BLUE;
}

// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}

Control Flow Statements


The control statements are used to control the flow of execution of the
program. Java contains the following types of control statements:

1) Selection Statements / Decision making statements: if, if-else, switch.


2) Iteration Statements / Looping Statements: while, do-while, for.
3) Branching Statements / Jumping Statements: break, continue, and return.

Selection Statements / Decision making statements: As the name suggests, decision-making


statements decide which statement to execute and when. Decision making statements evaluate the
Boolean expression and control the program flow depending upon the result of the condition
provided.

There are two types of decision making statements in Java, i.e.,


1. If statement
2. switch statement.

1) If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the
program is diverted depending upon the specific condition. The condition of the If statement gives
a Boolean value, either true or false. In Java, there are four types of if statements given below.

1. Simple if statement
2. if-else statement

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

4. Nested if-else statement


4.else if ladder

Simple if

statment Syntax:
If(expression)
{
Statements;
}

Java program to illustrate If statement


class IfDemo
{
public static void main(String args[])
{
int i = 10;

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

The if...else statement


The if. ..else statement is an extension of the simple if

statement. if(test expression) {

True block statement(s)


}
Else
{
False block statement(s)
}
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.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Java program to illustrate if-else statement


class IfElseDemo
{

public static void main(String args[])


{
int i = 10;

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

Nested if else statements

When a series of decisions are involved, we may have to use more than one if…else
statement in nested form

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

if the condition1 is false, the statement3 will be executed;otherwise it continues to perform the
second test. If the condition 2 is true, the statement 1 will be evaluated; otherwise the statement
2 will be evaluated and then the control is transferred to the statement x.

Java program to illustrate nested-if statement


class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

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

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

THE ELSE IF LADDER

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.

SWITCH STATEMENT
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;
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

case valueN:
statementN;
break;
default:
statement Default;
}
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.

Java program to illustrate switch-case


class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
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;

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

default:
System.out.println("i is greater than 2.");
}
}}
Output:
i is greater than 2.

DECISION MAKING 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.
Three types of Loops

1. The while statement


2. The do statement
3. The for statement

THE WHILE STATEMENT:


It is Entry–controlled loop
Syntax
while(test condition)
{
Body of the loop

Working:

The while is an entry controlled loop statement. The test condition is evaluated and if 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 WhileExample {


public static void main(String[] args)
{ int i=1;
while(i<=3){
System.out.println(i); i+
+;
}
}
}
Output
1
2
3
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

THE DO STATEMENT: It is Exit– controlled

loop do {

// statement
}while (condition);

Working:
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end
of the loop, the test condition in the while statement is evaluated. If the condition is true, the program
continues to evaluate the body of the loop once again. This process continues as long as the
condition is true. When the condition becomes false, the loop will terminated and the control goes to
the statement that appears immediately after the while statement. 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.

Do While Example program


public class DoWhileExample {
public static void main(String[] args)
{ int i=1;
do{
System.out.println(i);
i++;
}
while(i<=3);
}
}

Output:
1
2
3

THE FOR STATEMENT:(Entry –controlled loop)

for loop is another entry–controlled loop that provides a more concise loop control structure.

Syntax:

for(initialization; test condition; increment/decrement)


{
Body of the loop
}

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment statements such as i =1 and
count =0.The variables I and count are known as loop-control variables.
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.

for loop Example

public class ForExample


{
public static void main(String[] args)
{
//Code of Java for loop
for(int i=1;i<=3;i++)
{
System.out.println(i);
}
}
}
For-each Loop
The Java for-each loop prints the array elements one by one. It holds an array element in
avariable, then executes the body of the loop.
Syntax:
for(data_type variable: array)
{
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.
//Java Program to print the array elements using
for-each loopclass Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using
for- each loopfor(int
i:arr)
System.out.println(i);
}}
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

Output:
33
3
4
5

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:

Syntax
Access modifier return type method name()
{

Body of the method


}

Example:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}

public static void main(String args[])


{
myMethod();
}
}

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Output: I just got executed!

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

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.

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.

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

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2

public static void main(String[] args)


{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
} }
Output:
22
24.9

MATH CLASS

The java.lang.Math class contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions Mathematical functions
such as cos, sqrt, log etc are frequently used in analysis of real – life problems. Java supports these
basic math functions through
Math class defined in the java.lang package.

These functions should be used as


follows: Math.function_name()

Example:
double y=Math.sqrt(x);

Example:-
Import java.math.*;
Public class JavaMathExample1
{
Public static void main(String[] args)
{
Double x = 28;
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

Double y = 4;

// return the maximum of two numbers


System.out.println(“Maximum number of x and y is: “ +Math.max(x, y));

// return the square root of y


System.out.println(“Square root of y is: “ + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28


System.out.println(“Power of x and y is: “ + Math.pow(x,
y));

// return the logarithm of given value


System.out.println(“Logarithm of x is: “ + Math.log(x));

// return a power of 2
System.out.println(“exp of a is: “ +Math.exp(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.

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


class Testarray1
{
public static void main(String args[])
{
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

int a[]={33,3,4,5};//declaration, instantiation and initialization

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Multidimensional Array in Java


Data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


dataType[ ][ ] arrayRefVar; (or)

dataType arrayRefVar[ ][ ];
(or) dataType [ ]arrayRefVar[
];

Example to instantiate Multidimensional Array in Java


int[ ][ ] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in Java


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

//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();
}
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

} }

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Output:
123
245
445

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


class <class_name>{
field; //data
member
method; //member function
}

Rules for defining a class:


1. The name start with a capital letter
2. They can be only one public class per program
3.A program can have any number of non-public classes

Object: object is an instance of a class used to access the both Data member & member functions
outside the class also.
Object Definitions:
An object is a real-world
entity. An object is a runtime
entity.
The object is an entity which has state and behaviour.
The object is an instance of a class.
An object is an instance of a class. A class is a template or blueprint from which objects
are created. So, an object is the instance(result) of a class.

An object has three characteristics:

State: represents the data (value) of an object.


Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to
write, so writing is its behavior.

Creating object:
Syntax: <class_name> <object_name>=new <class_name>(arguments_list)

An object is created by instantiating a class. The process creating an object is called as instantiation
and the created object is an instance. The object is created by using ‘new’ operator
Ex: sum s=new sum();

Accessing Class member:


We can access the member of the class using Dot ( . ) operator.

Syntax: Obj_name.variabele_name;
Obj_name.function_name();
Ex: s.a;
s.add();

Example program
public class CreateObjectExample1
{
void show()
{
System.out.println("Welcome to javaTpoint");
}
public static void main(String[] args)
{
//creating an object using new keyword
CreateObjectExample1 obj = new
CreateObjectExample1();
//invoking method using the
object obj.show();
}
}

Constructors in Java
It is a special type of method which is used to initialize the object.
Syntax of constructor:
class ClassName {
ClassName() //
constructor
{
}

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>()

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.

//Java Program to create and call a default constructor

class Bike1{
//creating a default constructor Bike1()
{System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default
constructor Bike1 b=new
Bike1();
}
}

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Output:

Bike is created

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized

constructor. Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.

class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name =
n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
111

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

Output:

111 Karan
222 Aryan

Visibility modifiers

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.

Strings :- A combination or collection of characters is called as


string.The strings are objects in java of the class ‘String’.
System.out.println(“Welcome to java”);

The string “welcome to java” is automatically converted into a string object by


java.A stringin java is not a character array and it is not terminated with “NULL”.

String are declared and


created:-Using character
strings

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

String str1=new
String(“PES”);String
str2=new String(str1); String
str3=”Mandya”
We can also create string object by assigning value directly.

String object also create by using either new operator or enclosing of characters in double codes.

Methods of string classes :


1. Length: public int
length();It will give the
length of a string.

2. concat: public String


concat(String str);It used to join of two
string.
Ex: String
str1=”PES”String
str2=”college”
String str3=str1.concat(str2);
„+‟ operator is also used to concatenate of two string. )//it is returns PEScollege

3. equals: public Boolean equals(String obj);


This method also check weather two strings are equal or not . it returns true if the Two strings
areequalotherwise it returns false.
Ex: String str1=”college”; String
str2=”college”if(str1.equals(str2))
System.out.println(“two strings
are equal”);else
System.out.println(“two strings are Not equal”);

4. equalsIgnoreCase:- public Boolean equalsIgnoreCase(String obj);


The method ignores the case while comparing the content, It return True when the two
stringscharacter are in the different cases.
Ex: String str1=”college” String str2=”college”Str1.equalsIgnoreCase(str2);

5. toLowerCase:- public String toLowerCase();


This method converts all the character to Lower
case.
Ex: String str1=”WELcome TO
java”String
str2=str1.toLowerCase();

6. toUpperCase:- public String


toUpperCase(); This method converts all
the character to Upper case.Ex: String
str1=”WELcome TO java”

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

String str2=str1.toUpperCase();

7. replace:-syntax: public String repalce(char old, char new);


This method replace all the appearance of old character with a new character.
Ex: String str1=”JAVA” String str2=str1.repalce("J‟, ‟K‟);
Thismethod is also replace the old string to the new string.
String str1=”JAVA”
String str2=str1.replace("JAVA‟, "KAVA‟);

8. charAt:-syntax: public String charAt(int index);


This method returns a singlecharacter located at the specified index position with a string object.
Ex: String str1=”JAVA” ; Char c=str1.charAt(2); //output V

9. subString:-syntax: public String substring(int begin);


This method returns a string which is derived from the main string with the mentioned position.
Thiswillreturns the substring from the specified begin to end of the string.
Ex: String str1=”welcome to java programing”
String str2=str1.SubString(3);//output: come to java programing

Syntax2: String SubString(int begin, int end);


This will returns the specified begin to the specified end
Ex: String str1=”welcome t_o java
programing” String
str2=str1.SubString(3,10);//output: come t_

10. trim:-syntax: public String trim();


This method is used to remove the beginning and ending of the wide space in a given string.
Ex: String str1=” JAVA PROGRAMING ” String str2=str1.trim();

11.Start with S1.stratwith();


Check whether a string starts with specified character.

12.Ends with S1.endswith();


Check whether a string ends with specified character.

Write a program to perform all the string operation


import
java.lang.String;
import java.lang.*;
public class lab7
{
public static void main(String args[])
{
String s1="java";
String
s2="Programming";
String s3;

Prof. Bhairavi U N-Dept of MCA, CIT Mandya


Object Oriented using Java 22MCA22

System.out.println("string1 length="+s1.length());
System.out.println("strings
Concatination="+s1.concat(s2));if (s1.equals (s2))
System.out.println("String are
equal");else
System.out.println("String are NOT equal");
System.out.println("Strin1 UPERCASE
="+s1.toUpperCase()); System.out.println("Strin2 LOWER
CASE="+s2.toLowerCase()); System.out.println("Replaceing
string1 "+s1+"is="+s1.replace('j','k'));
System.out.println("Second charecter of 2nd string "+s2+"
is="+s2.charAt(1));System.out.println("String of "+s2+"String
is="+s2.substring(3,6));
}
}

Output

String1 length 4

javaProgramimn

g string are not

equalJAVA

programming

Replaceing string1 java is kava

Second character of 2nd string programming

is P String of programming string is ogra

String Buffer class


It creates string of flexible length that can be modifying in terms of both length and content. String
buffer class object as the rights to access all the methods of string classes but the object of string
classhas no rights toaccess the methods of string buffer class.

String buffer created as:


StringBuffer sb=new StringBuffer(“PES”)

Methods of string buffer class:


1. append(): This method is used to concatenating the two strings, It
is affected tothecurrent object.
Ex: StringBuffer s1=new
StringBuffer(“PES”);StringBuffer s2=new
StringBuffer(“college”);
System.out.println(“Append=”+s1.append(s2));
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

2. insert(): Insert the string s2 at the position „n‟ of the string s1.
Ex: StringBuffer s1=new
StringBuffer(“PES”);StringBuffer s2=new
StringBuffer(“College”); s1.insert(3,s2);

3. SetLength():This method is used to set the length from the


string to „n‟.Syntax: s1.SetLength(n);
Ex: StringBuffer s1=new
StringBuffer(“PES”);s1.setLngth(3);

4. SetcharAt(): This method is used to set the nth character to


the given newcharacter.
Syntax: s1.SetcharAt(n,char new); Ex: StringBuffer
s2=new StringBuffer(“java”);s2.setcharAt(0,‟k‟);//kava

5. reverse(): This method is used to reverse the character with in an


object of thestring buffer class.
Syntax: s1.reverse(); Ex: StringBuffer s1=new StringBuffer(“gcw”);s1.reverse();

Write a program to perform all the string buffer method

public class Ex
{
public static void main(String args[])
{
StringBuffer s1=new

StringBuffer(“gcw”); StringBuffer

s2=new StringBuffer(“college”);

System.out.println(“String str1=”+s1); System.out.println(“String


str2=”+s2); System.out.println(“Append=”+s1.append(s2));
System.out.println(“Insertd string=”+ S1.insert(3,s2));
System.out.println(“Set length of string2=”+ S2.setLength(3));
System.out.println(“Character at string s2=”+
S2.SetcharAt(3,m));System.out.println(“reversstring s2=”+ s2.reverse());
}
}

FILE in java

Java File class represents the files and directory pathnames in an abstract manner. This class is
usedforcreation of files and directories, file searching, file deletion, etc.

The File object represents the actual file/directory on the disk. Following is the list of constructors
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

tocreate aFile object.

1. File(File parent, String child) :-This constructor creates a new File instance from a
parent abstractpathname and a child pathname string.
2. File(String pathname):-This constructor creates a new File instance by converting
the givenpathname string into an abstract pathname.
3. File(String parent, String child):-This constructor creates a new File instance
from a parentpathname 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 pathname. Once you have File object in hand, then there is a list of helper
methods whichcan be usedto manipulate the files.

File methods

1. Public String getName():Returns the name of the file or directory denoted by this
abstractpathname.
2. Public String getParent():Returns the pathname string of this abstract pathnames parent, or
null ifthispathname does not name a parent directory.
3. Public File getParentFile():Returns the abstract pathname of this abstract pathnames
parent, ornullif this pathname does not name a parent directory.
4. Public String getPath():Converts this abstract pathname into a pathname string.
5. Public boolean isAbsolute():Tests whether this abstract pathname is absolute. Returns
true if thisabstract pathname is absolute, false otherwise.
6. Public String getAbsolutePath():Returns the absolute pathname string of this abstract
pathname.
7. Public boolean canRead():Tests whether the application can read the file denoted by this
abstract pathname. Returns true if and only if the file specified by this abstract pathname exists
and can be read bythe application; false otherwise.

8. Public boolean canWrite():Tests whether the application can modify to the file denoted by
this abstract pathname. Returns true if and only if the file system actually contains a file denoted
by thisabstractpathname and the application is allowed to write to the file; false otherwise.
9. Public boolean exists():Tests whether the file or directory denoted by this abstract
pathname exists.Returns true if and only if the file or directory denoted by this
abstract pathname exists; falseotherwise.
10. Public boolean isDirectory():Tests whether the file denoted by this abstract
pathname is adirectory. Returns true if and only if the file denoted by this abstract
pathname exists and is a directory; false otherwise. Package

Example Program

Import java.io.File;
Public class
FileDemo
{
Public static void main(String[] args)
{File f =null;
String[] strs = {“test1.txt”, “test2.txt”};Try
{ //for each string in string array
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

For(String s:strs ) {// create new fileF


= newFile(s);
// true if the file is executable
Boolean bool = f.canExecute();
// find the absolute path
String a = f.getAbsolutePath();
// prints absolute
path
System.out.print(a)
;
// prints
System.out.println(“ is executable: “+ bool);
}
} catch (Exception e) {// if any I/O error
occurse.printStackTrace();
}}}

this keyword in Java

In Java, this is a reference variable that refers to the current object.


Usage of Java this keyword

This can be used to refer current class instance variable.

If there is ambiguity between the instance variables and parameters, this keyword
resolves theproblem of ambiguity

This can be used to invoke current class method (implicitly)


by using the this keyword. If you don’t use the this keyword, compiler
automatically adds thiskeyword while invoking the method. You may invoke the
method of the current class

This() can be used to invoke current class constructor.


It is used to reuse the constructor. In other words, it is used for constructor chaining.

This can be passed as an argument in the method call.


It is mainly used in the event handling We can pass the this keyword in the constructor
also. It isuseful if we have to use one object in multiple classes

This can be passed as argument in the constructor call.


We can return this keyword as an statement from the method. In such case, return type of
the method mustbe the class type (non-primitive).

Example program
class Xyz
{
int x,y;
{
Prof. Bhairavi U N-Dept of MCA, CIT Mandya
Object Oriented using Java 22MCA22

this.x=a; this.y=b;
}
void display()
{
System.out.println(“X=”+x
);
System.out.println(“Y=”+y)
;}
}
public class Ex
{
public static void main(String args[])
{
Xyz obj1=new Xyz(10,20);
Xyz obj2=new
Xyz(100,200);
obj1.display();
obj2.display(); }
}

Prof. Bhairavi U N-Dept of MCA, CIT Mandya

You might also like