You are on page 1of 16

UNIT-1

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.

Programming support for internet.


Robust programming language.
Support networking, distributed programming.
Support s multimedia.
Platform independent.
Interpreted

Secure
Multi threaded
Portable
Architecture neutral

Features Removed from C and C++ :


No More Typedefs, Defines, or Preprocessor
No More Structures or Unions
No Enums

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.

Java Virtual Machine


Java Virtual Machine. An abstract computing machine, or virtual machine, JVM is a
platform-independent execution environment that converts Java byte code into machine
language and executes it. Most programming languages compile source code directly into
machine code that is designed to run on a specific microprocessor architecture or operating
system, such as Windows or UNIX.

The Java Platform


A platform is the hardware or software environment in which a program runs. Most platforms
can be described as a combination of the operating system and hardware. The Java platform
differs from most other platforms in that it's a software-only platform that runs on top of
other hardware-based platforms.
The Java platform has two components: The Java Virtual Machine (JavaVM)
The Java Application Programming Interface (Java API)
.
Java APIs are libraries of compiled code that you can use in your programs. They let you add
ready-made and customizable functionality to save you programming time. The Java API is
grouped into libraries of related classes and interfaces; these libraries are known as package

Comments in Java Code


Code comment s are placed in source f i les to describe what is happening in the code to
someone who might be reading the f i le, to comment -out lines of code to isolate the source
of a problem f or debugging purposes, or to generate API documentation.
To these ends, the Java language support s three kinds of comment s:
Double slashes, C-style and doc comments.
Double Slashes: Double slashes ( / / ) are used in the C++ programming language, and tell the
compiler to treat everything from the slashes to the end of the line as text .

Ex: / /A Very Simple Example class


C-Style Comments: Instead of double slashes, you can use C- style comments (/ * * /) to
enclose one or more lines of code to be treated as text.
Ex: / * These are C-style comment s*/
Doc Comments: To generate documentation for your program, use the doc comments (/ * * *
/) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc
comments embedded in source files and uses that comment s to generate API documentation.
Ex: / * * This class displays student details at * /.

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

Notes: -- The goto keyword is not used.


-- const is also not used.
-- assert is a new keyword added with Java 1.4
-- enum is a new keyword added with Java 5.0.
Java is case sensitive so in principle you could use these words if you change any character to
uppercase.
Arrays
An array is a collect ion of values all are belonging to the same data type and referred with
the same name to access any element of an array its position should be given which i s known
as index .
In java array indexing starts from 0.
Syntax: data type variable name[ ] ;
Ex: int arr [ ] ;
In the above statement the array will be created without any size. We should allocate memory
using the new operator before accessing the array.
arr = new int [5] ;
arr [0] = 10;
arr [1] = 20;

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] ;

a[2] = new int [5] ;


a[0] [0] = 10;
a[0] [0] = 10;
a[0] [1] = 20;

int a[ ] [ ] = new int [3] [5] ;


int [ ] [ ]a = new int [3] [5] ;
Class
A class is a collection of Data members (variables) that contain information necessary to
represent the class and Methods (functions) that perform operations on the data members of
the class. . Once a class i s created, any no. of instances of the class can be created in the
program. The definition of a class creates a user-defined data type and names the members of
the class. It does not allocate memory for any objects of that type! That is done by operator
new.
Object
Object: Object is an instance of the class or an object is the basic run- time entity.

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";
}

Student(int stno,String stname) //2nd constructor,used when arguments


specified
{
this.sno=stno;
this.sname=stname;
}
void accept(int stno, String stname)
{
this.sno=stno;
this.sname=stname;
}
void display()
{
System.out.println("\n Student no. : "+sno+"\n Student name:
"+sname);
}
}
class Constructor2
{
public static void main(String args[])
{
Student s = new Student(); //calls the 1st constructor
Student t= new Student(22,"Sanju"); //calls the 2nd constructor
s.display();
t.display();
s.accept(33,"Sateesh");
s.display();
}
}

Output:
Student no: 11
Student name: Raj
Student no. : 22
Student name: Sanju
Student no. : 33
Student name: Sateesh

Static members & Static methods

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;

static int z=77;


void display()
{
System.out.println("\n Values are: "+x+"\t"+y+"\t"+z);
}
static void print()
{
System.out.println("\n Value is : "+z);
}
}
class StaticMethod
{
public static void main(String args[])
{
Vals.print();
Vals s = new Vals();
Vals t = new Vals();
s.x=10; s.y=20; s.z=99;
t.x=50; t.y=60;
s.display();
t.display();
s.print();
t.print();
Vals.print();
}
}
Out -put:
Value is: 77
Values are: 10 20 99
Values are: 50 60 99
Value is: 99
Value is: 99
Value is: 99
Static Blocks
If a class contains static blocks all such blocks will be executed first whenever the class is
loaded.
/ / Example: Static Blocks. java
class StaticBlocks
{
static
{
System.out.println("First Static Block");
}
public static void main(String args[])
{
System.out.println("In the main program");
}
static
{

System.out.println("Second Static Block");


}
}
Out- put:
First Static Block
Second Static Block
In the main program
Access Specifiers
In Java, we accomplish encapsulation through the appropriate use of visibility modifiers (a
modifier i s a Java reserved word that specifies particular characteristics of a method or data
value).
Access specifiers can be:
Public: when anyone can call this method (public methods are al so called service methods;
A method created simply to assist a service method i s called a support method).
Private: when only methods in the same class are permitted to use this method.
Protected: when methods in this class and methods in any subclasses may use this method.
Object References:
An object reference holds the memory address of an object.
Class a = new Class ( );
Class b;
For object references, assignment copies the memory location:
b = a;
Two or more references that refer to the same object are called aliases of each other

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

String st r = new String (ar r);


O/P
abc
String (String str) : Creates a String from another String.
Methods:
int length( ) : Returns the length of the String.
char charAt ( int index ) : Returns the character at the specified index .
Ex: String str = Testing;
System.out .println(st r . length( ) ) ; 7
System.out .println(st r . charAt (3) ) ; t
Boolean equals (String s2) : If the current String is s1, s1 will be compared with s2 and
returns true if both are equal , otherwise false.
Ex: String s1 = abc;
String s2 = new String (abc);
String s3 = s1;
i f ( s1 == s2 ) f al se, because == operator compares with the references i .e, hash codes
i f ( s1 == s3 ) true
i f ( s3 == s1 )
i f ( s1.equal s(s2 ) true
i f ( s1.equal s(s3) ) true
i f ( s2.equal s(s3) ) true
boolean equalsIgnoreCase(String s2 ) : Compares the String without case sensitiveness.
int compare To(String s2 ) : I f current String is s1, s1 will compare with s2 and returns a
value from the following table.
return value if
< 0 s1 < s1
> 0 s1 > s2
= 0 s1.equals (s2) = = t rue
Comparison depending on ASCI I values.
String toUpperCase( ) : Returns the String to the upper case
Note: In any of the String functions the source will not be modified. Only the return value
contains the modified data.
Ex: String st1 = Hello;
String st2 = st1. toUpperCase( ) ;

System.out .println(st1) ; Hel lo No change in source


System.out .println(st2) ; HELLO Modified value
String toLowerCase( ) : Returns the String to the lowercase.
String trim( ) : Removes the leading and trailing spaces.
Ex: st1 = abc xyz ;
st2 = st1. trim( ) ;
O/P
abc x yz

boolean startsWith(String st) : Compares the beginning portions of the String


boolean endsWith(String st) : Compares the beginning portions of the String

Ex: String st = This is to test;


if ( st . startsWith( This ) ).
if ( st .endsWith( Test ) )
O/P
Both are true
String subString ( int start Index, int endIndex ) : Extract s a portion of the String from start
index to end index -1.
String subString ( int startIndex ) : Extract s from start index to ending of the String.
StringBuffer: A StringBuffer object holds a String of characters that can be changed by
appending characters at the end and by inserting characters. However, unlike a char array, a
StringBuffer comes with many methods convenient f or character manipulation. A
StringBuffer automatically grows in length as needed.
Constructors:
public StringBuffer ( ) : Constructs a string buffer with no characters in it and an initial
capacity of 16 characters.
public StringBuffer ( int capacity) : Constructs a string buffer with no characters in it and an
initial
capacity specified by the length argument.
public StringBuffer (String st ) : create a StringBuffer containing the characters from String.

As with arrays, StringBuffer indexes start at 0 and go up to length-1. Some StringBuffer


methods are:
Methods:
StringBuffer append (char c): Appends to the end of the StringBuffer.
StringBuffer append (int i): Convert in to characters and then append them to the end of the
StringBuffer, same for other primitive data types.
StringBuffer append (String s ) : Append the characters in s to the end of the StringBuffer.
int capacity ( ) : Return the current capacity (capacity will grow as needed) .
char charAt (int index ) : Get the character at index .
StringBuffer insert (int index, char c): Insert character c at index (old characters move over to
make room) .
StringBuffer insert (int index, String st): Insert characters from st starting at position i.
StringBuffer insert (int index, int i): Convert it o characters, then insert them starting at index,
same f or other data types.
int length ( ): Return the number of characters.
StringBuffer reverse (): Reverse the order of the characters.
void setCharAt (int index, char c) : Set the character at index to c.
String toString ( ): Return a String object containing the characters in the StringBuffer.
StringTokenizer Class:
Tokens and Delimiters
Often an input String contains several groups of characters, where each group acts as a unit
that has significance. Such a group is called a token. Tokens are separated from each other by
delimiter characters.
For example, say that you need to add up the following numbers:
12 8 5 32
You automatically group these characters to form four integers separated by spaces. The
tokens in these cases are 12 and 8 and 5 and 32. These tokens are delimited by the space
character. The StringTokenizer class aids in breaking a String into tokens. You can use the
default delimiters, or specify your own. The default delimiters are: space, tab, newline, and
carriage return.
StringTokenizer constructors:
public StringTokenizer (String arg ) : Create a StringTokenizer based on String, using the
default delimiters.

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

You might also like