Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduction to
Programming Methodology
By:-A.W.Burange
Classes
Class can be defined as the collection of data member
and member function .
Class can be defined as blue print for an object.
A class is user defined data type.
A class can be declared using the keyword “class”
followed by name of the class that we want to define.
class classname
{
instance variable;
member function; (Parameter)
body of the method;
}
AWB
2
A class can contain any of the following variable types.
Local variables: Variables defined inside methods, constructors or
blocks are called local variables. The variable will be declared and
initialized within the method and the variable will be destroyed
when the method has completed.
Instance variables: Instance variables are variables within a class
but outside any method. These variables are initialized when the
class is instantiated. Instance variables can be accessed from inside
any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a
class, outside any method, with the static keyword.
AWB
3
public class Dog
{
String breed ;
int age ;
String color ;
void barking() //method
{ } //body of the method
void hungry()
{ }
void sleeping()
{ }
A class can have any number of
methods to access the value of
various kinds of methods. In the
above example, barking(),
hungry() and sleeping() are
methods.
}
AWB
4
In this example, we have created a Student class that have two data members id
and name. We are creating the object of the Student class by new keyword
and printing the objects value.
class Student1
{
int id; //data member (also instance variable)
String name; //data member(also instance variable)
public static void main(String args[])
{
Student1 s1=new Student1(); //creating an object of Student
System.out.println(s1.id);
Output :
System.out.println(s1.name);
0
null
}
}
AWB
5
class circle
{
int Radius=10;
//instance member
double pi=3.14;
public void area() //member function
{
double area=pi*Radius*Radius;
System.out.println(“Area of circle ”+area);
}
}
class TestCircle
{
public static void main(String args[])
{
circle c=new circle(); //object creation of class
c.area();
}
}
AWB
6
Object
Object are defined as instances of a class. In java objects are
created using new operator.
new operator creates object of specified class and return a
reference to the object.
Objects are key to understanding object-oriented technology.
Real-world objects share two characteristics: They all
have state and behavior. Dogs have state (name, color, breed,
hungry) and behavior (barking, fetching, wagging tail).
AWB
7
Object
Bicycles also have state (current gear, current pedal cadence,
current speed) and behavior (changing gear, changing pedal
cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great
way to begin thinking in terms of object-oriented programming.
AWB
8
AWB
9
Creating an Object:
As mentioned previously, a class provides the blueprints for
objects. So basically an object is created from a class. In
Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name
with an object type.
e.g. Rectangle R;
Instantiation: The 'new' key word is used to create the
object.
e.g. Rectangle R=new Rectangle();
Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
AWB
10
Methods in java
A method is a set of code which is referred to by name and can be
called (invoked) at any point in a program simply by utilizing the
method's name.
Think of a method as a subprogram that acts on data and often
returns a value.
Each method has its own name. When that name is encountered in
a program, the execution of the program branches to the body of
that method.
When the method is finished, execution returns to the area of the
program code from which it was called, and the program continues
on to the next line of code.
AWB
11
For
ex.
public void area(int length, int breadth)
parameters
Modifier
return
type
Name of the method
AWB
12
Modifier : Modifier are access type of method.
We will discuss it in detail later.
Return Type : A method may return value. Data
type of value return by a method is declare in
method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that
defines what method does.
AWB
13
Compiling and Running a Program
Welcome.java
c:\example
chapter1
Welcome.class
Where are the files
stored in the
directory?
Welcome.java~
.
.
.
chapter2
Java source files and class files for Chapter 2
chapter19
Java source files and class files for Chapter 19
AWB
14
Anatomy of a Java Program
Comments
Package
Reserved
words
Modifiers
Statements
Blocks
Classes
Methods
The
main method
AWB
15
Comments
In Java, comments are
preceded by two slashes (//)
in a line, or enclosed
between /* and */ in one or
multiple lines. When the
compiler sees //, it ignores
all text after // in the
same line. When it sees /*,
AWB
16
Package
The second line in the program
(package chapter1;) specifies a
package name, chapter1, for the class
Welcome. Forte compiles the source
code in Welcome.java, generates
Welcome.class, and stores
Welcome.class in the chapter1 folder.
AWB
17
Reserved Words
Reserved words or keywords are
words that have a specific
meaning to the compiler and
cannot be used for other
purposes in the program. For
example, when the compiler sees
the word class, it understands
that the word after class is the
name for the class. Other
reserved words in Example 1.1
AWB
18
Modifiers
Java uses certain reserved words called
modifiers that specify the properties of the
data, methods, and classes and how they
can be used. Examples of modifiers are
public and static. Other modifiers are
private, final, abstract, and protected. A
public datum, method, or class can be
accessed by other programs. A private
datum or method cannot be accessed by
other programs. Modifiers are discussed in
Chapter 6, "Objects and Classes."
AWB
19
Statements
A statement represents an
action or a sequence of
actions. The statement
System.out.println("Welcome
to Java!") in the program in
Example 1.1 is a statement
to display the greeting
"Welcome to Java!" Every
statement in Java ends with
AWB
20
Blocks
A pair of braces in a program
forms a block that groups
components of a program.
public class Test {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
AWB
Class block
Method block
21
Classes
The class is the essential Java
construct. A class is a template
or blueprint for objects. To
program in Java, you must
understand classes and be able
to write and use them. The
mystery of the class will
continue to be unveiled
throughout this book. For now,
though, understand that a
AWB
22
Methods
What is System.out.println? It is a method:
a collection of statements that performs a
sequence of operations to display a
message on the console. It can be used
even without fully understanding the details
of how it works. It is used by invoking a
statement with a string argument. The
string argument is enclosed within
parentheses. In this case, the argument is
"Welcome to Java!" You can call the same
println method with a different argument to
AWB
23
Displaying Text in a Message
Dialog Box
you can use the showMessageDialog
method in the JOptionPane class.
JOptionPane is one of the many
predefined classes in the Java system,
which can be reused rather than
“reinventing the wheel.”
Source
Run
AWB
24
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome
to Java!",
"Example 1.2",
JOptionPane.INFORMATION_MESSAGE));
AWB
25
Method Overloading
It
can be defined as the method having same
name but different number of parameters or
parameters of different data-type.
Method overloading is a one way to achieve
polymorphism in java.
Whenever method is called name of the method
is matched & then the number & type of
arguments passed to method.
AWB
26
Constructors
Constructors
are used to initialize the objects.
Features:
1.They
have same name like class name.
2. They have no return type not even void.
They are invoked when object is created
automatically.
By default they are public.
They can be overloaded.
AWB
27
String class
Strings can be instantiated in two ways
i.
String x=“Hello”;
ii. String y= new String(“Hello”);
Line 1 shows that string literal being assigned to string
reference ‘x’.
Line 2 shows that creation of a string object with ‘new’
keyword & string literal is passed as an argument to the
constructor. Does it mean that in line 1, no object is
created?
In Line 1 object of class String is created implicitly & memory
is allocated from memory pool.
AWB
28
String class cont..
In line 2, object is created explicitly using ‘new’
keyword, so the memory required for the object is
allocated out of memory pool.
a
String a=“Hello”;
Hello
b
String b=“Hello”;
Hello
c
String c=new String (“Hello”);
d
String d=new String (“Hello”);
Hello
AWB
29
Methods
1. length(): This method is used to find number of characters that a string
contains.
Syntax: int length();
Eg. String s1=“hello”;
int l=s1.length();
System.out.println(“Length of string=”+l);
Above code prints the length 5.
String Comparison
To compare two strings we use equals().
Syntax: boolean equals(String str)
Here, ‘str’ is string object being compared with calling string object. It returns
‘true’ if string contains same characters in same order, otherwise false, it is case
sensitive. To perform a comparison that ignores case-differences , use
equalsIgnoreCase().
Syntax: boolean equalsIgnoreCase(String str)
AWB
30
compareTo(): This method can also be used to compare two
strings.
Eg. s1.compareTo(s2)
The method returns the value ‘0’ if s1 equal to s2, less than ‘0’ if
s1<s2 & greater than ‘0’ if s1>s2.
It returns difference between the ASCII value of two characters.
startsWith()
and endsWith()
startsWith () determines whether a given string begins with a
specified string, while endsWith() determine whether the string
ends with specified string
Syntax: boolean startsWith(“String literal”)
boolean endsWith(“String literal”)
It returns ‘true’ if string matches otherwise ‘false’.
AWB
31
StringBuffer class
It is a mutable class. A StringBuffer is like a string but
can be modified. It can be used wherever string is used.
It is more flexible than string. We can add, insert, append
new content to StringBuffer.
Syntax: StringBuffer s=new StringBuffer(“String”);
Eg. StringBuffer s=new StringBuffer(“Hello”);
Methods:
1. length():- The current length of a StringBuffer can be
retrieved by length() method.
Syn: int length();
Eg. StringBuffer s=new StringBuffer(“hello”);
System.out.println(“length of s”+s.length());
32
AWB
2. capacity(): Total allocated capacity can be retrived by
capacity() method.
Syn: int capacity();
Eg. System.out.println(“capacity of s=”+s.capacity());
Output: capacity of s=21.(Additional 16 bits are added to
StringBuffer object)
3.ensureCapacity():- To pre-allocate a space for a certain
number of characters after a StringBuffer class has been
constructed, we can use ensureCapacity().
Syn: void ensureCapacity(int capacity);
Eg. StringBuffer s1=new StringBuffer(“Hello”);
System.out.println(“capacity of s1=”+s1.ensureCapacity(100));
o/p: capacity of s1=100.
AWB
33
4. setLength():- To set length of buffer within a string
object, we can use setLength() method.
Syn: void setLength(int len);
where ‘len’ specifies length of buffer. When we
increase size of buffer null characters are added to the
end of existing StringBuffer. If we set value less than
current value, then characters stored beyond length are
lost.
Eg. StringBuffer s1= new StringBuffer(“hello”);
System.out.println(“new string=”+ s1.setLength(3));
o/p: new string= hel
AWB
34
charAt() & setCharAt()
The value of a single character can be obtained from a
charAt() method.
We can set the value of character using setCharAt()
method.
Syntax: char charAt (int index);
void setCharAt(int index, char ch);
Eg. StringBuffer s1=new StringBuffer(“hello”);
System.out.println(“character at 1=”+s1.charAt(1));
S1.setCharAt(4, ‘x’);
System.out.println(s1);
o/p- character at 1= e
hellx
35
AWB