Oops M1
Oops M1
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.
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.
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.
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).
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).
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.
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:
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.
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.
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
class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and print variable in java. */ int i=10; System.out.println(i);
}
}
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.
Identifier: Identifier is case sensitive names given to variable, methods, class, object, packages ,etc
Separators: They are character used to group and arrange Java source code into segments.
Java uses 6 types of separators:
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.
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
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.
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.
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.
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
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+
(y+1);
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
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with
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);
}
}
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:
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.
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.
// 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.
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
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
Simple if
statment Syntax:
If(expression)
{
Statements;
}
if (i > 15)
System.out.println("10 is less than 15");
Output:
I am Not in if
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.
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 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.
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.
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.
default:
System.out.println("i is greater than 2.");
}
}}
Output:
i is greater than 2.
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.
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.
Output:
1
2
3
for loop is another entry–controlled loop that provides a more concise loop control structure.
Syntax:
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.
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()
{
Example:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
METHOD OVERLOADING
If a class has having same name but different in parameters, it is known as Method Overloading.
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.
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 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.
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 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.
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
dataType arrayRefVar[ ][ ];
(or) dataType [ ]arrayRefVar[
];
} }
Output:
123
245
445
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.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
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.
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.
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();
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
{
}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
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();
}
}
Output:
Bike is created
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
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.
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
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.
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.
String str2=str1.toUpperCase();
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
equalJAVA
programming
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);
public class Ex
{
public static void main(String args[])
{
StringBuffer s1=new
StringBuffer(“gcw”); StringBuffer
s2=new StringBuffer(“college”);
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
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
If there is ambiguity between the instance variables and parameters, this keyword
resolves theproblem of ambiguity
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(); }
}