Object Oriented Programming Through Java
Object Oriented Programming Through Java
Topics:
OBJECT ORIENTED THINKING: Need for object oriented programming paradigm, a way
of viewing world agents and Communities, messages, methods, responsibilities, Classes and
Instances, Class Hierarchies-Inheritance, Method Binding, Overriding and Exceptions.
JAVA BASICS: History of Java, Java buzzwords, JVM architecture, data types, variables,
scope and life time of variables, arrays, operators, control statements, type conversion and
casting, simple java program, constructors, methods, string and String Buffer handling
functions.
OBJECT ORIENTED PROGRAMMING (JAVA)
Java technology is both an Object Oriented programming language and a platform used f or
developing applications f or the internet.
Java was started by the following 5 people:
James Gosling, Patrick Naughton, Mike Sheridan, Chris Wrath, Ed Frank
These people designed a language called OAK in 1970s for consumer electronics. But OAK
was failure. The language OAK was enhanced with internet support and released in the
market in 1995 with the new name JAVA.
Important Features of JAVA:
Object Oriented Programming language.
Secure
Multi threaded
Portable
Architecture neutral
No More Functions
No More Multiple Inheritance
No More Goto Statement s
No More Operator Over loading
No More Pointers
Programming in JAVA
In java the programs are generally divided into 2 categories.
Applications
Applets
Application: An application i s normal program that runs on an individual system.
Applet : An applet i s a program designed in Java and will be placed on the server ,the
applet will be downloaded from the server to the client along with the HTML document and
runs in the client s WEB browser . i .e. , an applet will run as a part of WEB document .
First Java program
Example: First.java
// it displays the text First Java Program.
class First
{
public static void main(String args[])
{
System.out.println("First Java Program");
}
}
Compiling a JAVA program: Whenever we compile a java program, the compiler creates an
intermediate file, which contains the byte code of the program.
D: \>javac First . java
Creates First. class -> Byte code
To run, the java interpreter should be used, which reads the instructions from the byte code
and executes them.
D: \> java First
OUTPUT
First Java Program
Your first program, First.java, will simply display "First Java Program". To create this
program, you will:
Create a source file. A source file contains text, written in the Java programming language,
that you and other programmers can understand. You can use any text editor to create and
edit source files.
Compile the source file into a bytecode file. The compiler, javac, takes your source file and
translates its text into instructions that the Java Virtual Machine (Java VM) can understand.
The compiler converts these instructions into a bytecode file.
Run the program contained in the bytecode file. The Java interpreter installed on your
computer implements the Java VM. This interpreter takes your bytecode file and carries out
the instructions by translating them into instructions that your computer can understand.
Operators in Java:
Assignment Operators: =
Arithmetic operation and then assignment: +=, -=, *=, /=, %=
Bitwise operation and then assignment: &=, |=, ^=
Shift operations and then assignment: <<=, >>=, >>>=
Increment & Decrement Operators: ++ and -Logical Operators: &&, ||, !
Boolean Operators: & | ^
Comparison Operators :<,>, <=, >=, ==,! =
Bitwise Operators: ~, &, |, ^, <<, >>, >>>
Conditional Operator:?:
Class and Object Operators:
Class Test Operator: instanceOf
Class Instantiation: new
Class Member Access:. (dot)
Method invocation: ( )
Control Statements:
Selection Statements: if, switch
Loop Statements: while, do while, for
Jump Statements: break, continue, return
Data types in Java
Keywords
abstract
catch
do
final
implements
native
public
switch
true
assert
char
double
finally
import
new
return
synchronized
try
boolean
class
else
float
instanceof
null
short
this
void
break
const
enum
for
int
package
static
throw
volatile
byte
continue
extends
goto
interface
private
strictfp
throws
while
case
default
false
if
long
protected
super
transient
If we don t assign or read the values for remaining locations, by default they will be filled
with 0s.
Example
int arr [ ] = new int [5] ;
int [ ]arr = new int [5] ;
Length property : Each array contains the length property, which contains the no. of element
s in the array.
Ex: System.out.println (arr.length); / /displays the no. of location i .e.,5 for the above
Initializing the array and display the elements
class OneDArrIni
{
public static void main(String args[])
{
int a[]={10,20,30,40,50},i;
for(i=0;i<a.length;i++)
System.out.println("value of a["+i+"] is: "+a[i]);
}
}
Assigning elements into the array and display the elements
class OneDArr
{
public static void main(String args[])
{
int a[],i;
a=new int[5];
a[0]=10;
a[1]=20;
for(i=0;i<a.length;i++)
{
System.out.println("value of a["+i+"] is: "+a[i]);
}
}
}
Two Dimensional Arrays: In Java, in a 2-d array all the rows need not contain the same
no. of columns.
int a[ ] [ ] ;
a = new int [3] [ ];
a[0] = new int [4] ;
a[1] = new int [3] ;
Program
Define a class and create an instance for the class, and access the member data and member
functions of the class through the instance.
class Student
{
int sno; String sname;
void assign()
{
sno=10;
sname="Sateesh";
}
void display()
{
System.out.println("\n Student no. : "+sno+"\n Student name: +sname);
}
}
class ClassandObj
{
public static void main(String args[])
{
Student s;
s= new Student();
s.assign();
s.display();
Student t= new Student();
t.assign();
t.display();
}
}
Constructors
A constructor is a special member function which is called automatically whenever an
instance of the class is created. The name of the constructor should be equal to the name of
the class. Constructors are generally used for initializing the variables of the class. A
constructor may or may not take any argument s, but a constructor will not return any value.
class Vals
{
int x,y;
Vals(int p,int q) // Constructor
{
x=p;
y=q;
}
void dispx()
{
System.out.println("\n val of X: "+x);
}
void dispy()
{
System.out.println("\n val of Y: "+y);
}
}
Overloading Constructors
To refer to the variables of the current class. & constructor over loading, 1st constructor
doesnt contain arguments and 2nd constructor contain two arguments.
class Student
{
int sno;
String sname;
Student() // 1st constructor , used when no arguments specified
{
sno=11;
sname="Raj";
}
Output:
Student no: 11
Student name: Raj
Student no. : 22
Student name: Sanju
Student no. : 33
Student name: Sateesh
Static members: Whenever a variable is specified as static such variable will be created only
once in the memory f or al l the instances of the class. Al l the instances of the class will
share the same value of the static variable. A static variable of a class can also be accessible
using the name of the class.
/ / Example: StaticMember . java
class Vals
{
int x,y;
static int z=77;
}
class StaticMember
{
public static void main(String args[])
{
System.out.println("\n Val of Z: "+Vals.z);
Vals s = new Vals();
Vals t = new Vals();
s.x=10; s.y=20; s.z=99;
t.x=50; t.y=60;
System.out.println("\n Val of Z: "+Vals.z);
System.out.println("\n Val of s.x : "+s.x+"\n Val of s.y : "+s.y+"\n Val of s.z :
"+s.z);
System.out.println("\n Val of t.x : "+t.x+"\n Val of t.y : "+t.y+"\n Val of t.z :
"+t.z);
System.out.println("\n Val of Z: "+Vals.z);
}
}
Out put:
Val of z : 77
Val of z : 99
Val of s.x : 10
Val of s.y : 20
Val of s.z : 99
Val of t.x : 50
Val of t.y : 60
Val of t.z : 99
Val of z : 99
Static methods : A static function of a class can be accessible using the name of the class
also. A static function can access only other static member of the class.
/ / Example: StaticMethod.java
class Vals
{
int x,y;
String Handling
String Class: The String class is used f or managing String data. It is containing constructors
and methods to deal with the String data.
Constructors:
String ( ): Creates a String without any data.
String (char arr [ ] ) : Creates a String with characters in the given array.
Ex: char arr [ ] = { a, b, c } ;
O/P
abc
public StringTokenizer (String arg, String delimit): Create a StringTokenizer based on String,
using the individual characters in delimit as delimiters.
public StringTokenizer (String arg, String delimit, boolean ret): As above, but if ret is true,
then Individual delimiters count as tokens also.
StringTokenizer Methods:
int countTokens( ) : Return the number of tokens remaining.,The countTokens() method
starts with the total number of tokens the String has been broken into. countTokens() will
report one less token.
boolean hasMoreTokens( ) : Return true if there are more tokens.
String nextToken( ) : Return the next token. , Each time nextToken() is called, one token
(starting with the first) is consumed.
The StringTokenizer class is found in java.util, which must be imported for the program to
compile.
// File name: StrTok1.java
import java.io.*;
import java.util.*;
public class StrTok1
{
public static void main (String [] args ) throws IOException
{
BufferedReader
stdin
=new
BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a string:");
String data = stdin.readLine();
StringTokenizer tok = new StringTokenizer (data );
while ( tok.hasMoreTokens() )
System.out.println ( tok.nextToken() );
}
}
Output:
Enter a string: This is a book
This
is
a
book