You are on page 1of 18

-Sun Microsystems

VYAS M. SANZGIRI (HEAD)


Intro (Why JAVA?)
Free to download & use,fast,platform independent,uses OOPM,memory management,auto memory dealocation,multitasking,exceptional
conditions,no pointers,many pre defined classes & functions,open source,many discussion forums,can run in LAN,TCP/IP
environment,policies,digital certificates,swing & jfc components.
Java checks code at compilation time & run time.It generates bytecode that resembles the machine code & are no specific to any processor.

Concept Of OOPS(Object Oriented Programming Structure)


Controlling access to code.
Class & Object – Class is user defined datatype containing group of other datatypes.Object is a variable of type class.
Encapsulation – Restrictive access to data & functions
Inheritance – Acquiring prop. of other classes,reusable code

ANIMAL

MAMMAL REPTILE

DOG CAT

Polymorphism – different behavior in diff. conditions


+ can be used for addition of nos. & strings
Dynamic Binding – Run time linking of codes
Message Passing – Invoking an operation on an object
Function Overloading – Func.having same name diff. parameters

Developing JAVA Programs


JAVA Source file is created in a plain text editor or an editor which saves files in plain ASCII format without formatting
characters.eg.UNIX systems-vi,pico editors are used,WINDOWS-Notepad,EDIT dos editor is used.
It consists of two main parts-class definition enclosing the entire prog.& main that contains the body.It is saved as .java
file,compiled as javac filename.java,run as java filename.

Datatypes
Integer
TYPE SIZE RANGE
byte 8 bits -128 to 127
short 16 bits -32768 to 32767
int 32 bits -2^32 to 2^32 -1
long 64 its -2^64 to 2^64 -1
Float
Character
Boolean

Operators
Arithmetic operators + - * / % can be used.
class ari
{
public static void main(String args[])
{
int x=10,y=20;
float z=25.98f;
System.out.println(+(x+y) +” “+(z-y) +” “+(x*y) +” “+(z/y) +” “+(z%y));

2
}
}
Output: 30 5.98 200 1.299 5.98

Assignment Operators
EXPRESSION MEANING
x+=y x=x+y
x-=y x=x-y
x*=y x=x*y
x/=y x=x/y
x%=y x=x%y
++a a=a+1,use a
a++ use a,a=a+1
--a a=a-1,use a
a-- use a,a=a-1

Comparison Operators
Operators Meaning Example
== Equal u = = 45
!= Not equal u != 75
< Less than u < 85
> Greater than u > 68
<= Less than or equal u <= 53
>= Greater than or equal u >= 64

Logical Operators
AND && returns true only if both are true
OR || returns true even if one is true
XOR ^ returns true if both operands are true or both false.

Bitwise Operators
OPERATORS MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>>> Zero fill right shift
~ Bitwise Complement
<<= Left Shift Assignment
>>= Right Shift Complement
>>>= Zero fill right shift assignment
x&=y AND assignment
x|=y OR assignment
x^=y XOR assignment
class bitop
{
public static void main(String args[])
{
int a=1,b=2,c=3;
a=a|4;
b>>=1;
c<<=1;
a=a^c;
System.out.println(“a=”+a+” b=”+b+” c=”+c);
}
}
Output: a=3 b=1 c=6

3
Operator Precedence
OPERATOR NOTES
[ ] ,( ), . [] for arrays,() group expressions,dot used to access methods & variables in
objects & classes
++,--,!,-,instance of returns t or f based on whether object is instance of named class or its super
class
new(type) used to create class instances
*,/,% mult,div,mod
+,- add,sub
<<,>> itwise left,right shift
<,>,<=,>= relational comparison tests
==,!= equal to,not equal to
& AND
^ XOR
| OR
&& logical AND
|| logical OR
?: ternary operator
=,+=,-=,*=,/=,%=,^= assignment

If…else & Ternary Operator ?:


Prog:
class cond
{
public static void main(String args[])
{
int i=10,j=20,z=0;
if (i>j) //if…else
System.out.println(+i+” is greater”);
else if(i<j)
System.out.println(+j+” is greater”);
else
System.out.println(”Both nos. are equal”);
z=i>=j?i:j; //ternary operator test?pass:fail
System.out.println(+z+” is greater”);
}
}

While Loop
while(condition)
{
body of loop;
}
Prog:
class fibo
{
public static void main(String args[])
{
int max=25,prev=0,next=1,sum;
while(next<=max)
{
System.out.print(+next+” “);
prev=next;
next=sum;
}
}
}
Output: 1 1 2 3 5 8 13 21

For Loop
4
for(initialization;termination;expression)
{
body of loop;
}
Prog:
class even
{
public static void main(String args[])
{
for(int i=0;i<10;i+=2)
if((i%2)==0)
System.out.print(+i+” “);
}
}
Output: 0 2 4 6 8

Switch…case
It is used as multiple if…else statement.
switch(test)
{
case value1: body;
break;
case value2: body;
break;
default: default result;
}
Prog:
class swidemo
{
public static void main(String args[])
{
int v=4;
switch(v)
{
case 1:
case 2:System.out.println(“No. is 1 or 2);
break;
case 3:
case 4:System.out.println(“No. is 3 or 4”);
break;
default:System.out.println(“No.is not 1,2,3,4);
}
}
}

Break & Continue


Break halts the execution of curr. loop & forces control out of the loop.Continue starts the next iteration of the loop.
Prog:
class contdemo
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.println(+i+” “);
if(i%2==0)
continue;
System.out.println(“ “);
}
}
}
5
Output: 0 1
23
45
67
89

Class
Class is the basic element of OOP which defines the user-defined datatype.Instance (variable) of class is called object.The instance
variables can be accessed using the dot operator.
Prog:
class one
{
int a;
int b;
public static void main(String args[])
{
one a1;
a1.a=2;
a1.b=3;
System.out.println(“a1.a=”+a1.a+” a1.b=”+a1.b);
}
}
one a1
a=2
b=3

New Operator
Used to create single instance of named class.
When object is no longer referred to by any variable,Java automatically reclaims memory used by that object.This is called garbage
collection.
Prog:
class abc
{
int a=b=20;
public static void main(String args[])
{
abc a1=new abc(); //a1 points to the object & doesn’t contain it
System.out.println(“a=”+a+” b=”+b);
}
}

Methods
Prog: illustrates use of methods,passing arguments,this keyword
class point1
{
int x,y;
void init(int x,int y) //passing args
{
this.x=x; //this means curr class
this.y=y;
}
void disp() //no args
{
System.out.println(“x=”+x+”y=”+y);
}
}
class point
{
public static void main(String args[])
{

6
point1 pp=new point1();
pp.init(4,3);
pp.disp();
}
}

Command Line Arguments


Arguments can be directly appended when Java progs. are run.Java stores them in a array of strings.
Prog:
class Arg
{
public static void main(String args[])
{
System.out.println(“The first argument is “+args[0]);
}
}

Overloading Methods
In this case different methods are created with same name but different argument list. The return type & variable name in argument list
doesn’t matter but the number & type of arguments decide the function that is called. If functions have same name & argument list but
different return type then compiler gives error.
Prog:
class Load
{
int a,b;
void get()
{
a=0;
b=0;
}
void get(int x,int y)
{
a=x;
b=y;
}
void disp()
{
System.out.println(a+” “+b);
}
public static void main(String args[])
{
Load loads=new Load();
loads.get();
loads.disp();
loads.get(16,1);
loads.disp();
}
}

Output: 0 0
16 1

Access Specifiers
They define the security(restrictions) of variables & functions.
1.public
All functions & variable declared here are visible to class. It has widest possible visibility. Any class can use it.
2.package
It has increased protection & narrow visibility & is the default protection when none has been specified.
3.protected
All matter declared here can be inherited as private.Narrower visibility compared to public.
4.private
7
Most secure.Cant be inherited.
private No modifier protected public
Same class Yes Yes Yes Yes
Same package No Yes Yes Yes
sub class
Same package No Yes No Yes
non sub class
Diff.package sub No No Yes Yes
class
Diff.package non No No No Yes
sub class

Java Class Library


It provides a large set of readymade classes for any Java commercial environment. JDK comes with documentation describing each
class,variables,methods etc.
e.g.
java.lang:It includes the Object,String,System class & also some primitive types int,char,float.
java.util:Utility class like Date,simple collection classes like Vector & Hashable are declared.
java.io:Input,Output classes for writing to & reading from streams & for file handling.
java.net:Classes for network support like Socket & URL.
java.awt: (Abstract Window Toolkit)classes used to implement graphical user interface & processing images like Window,Menu,Button
Font,Checkbox.
java.applet:Classes to implement Java applets including Applet class & Audioclip interface.

Importing classes
Classes external to the program can be included using import keyword.eg. import classname
To import Date class the code is import java.util.Date
It is also possible to import all classes that belong to a package using the * symbol.e.g. import java.awt.*

Constructors & Finalizers


Constructors are called when objects of that class are created. They are used for initialization & memory allocation. Constructors can also
be overloaded.
Finalizers are used to destroy objects, optimize removal of objects & reclaim memory.
Prog:
class point
{
int x,y;
point(int x,int y)
{
this.x=x;
this.y=y;
}
point() //overloading constructors
{
this(-1,-1);
}
public static void main(String args[])
{
point p=new point();
System.out.println(“x=”+p.x+”,y=”+p.y);
}
}

Output: x=-1,y=-1

Inheritance
import java.io.*;
class numeral
{
public int x;

8
void getint()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter no to find square”);
String s=br.readLine();
x=Integer.parseInt(s);
}catch(IOException e){}
}
}

import java.io.*;
class square extends numeral
{
int retsq()
{
int y=(x*x);
System.out.println(Square is”+y);
return y;
}
public static void main(String args[])
{
square s=new square();
s.getint();
s.retsq();
}
}

protected part of base class becomes private part to inherited derived class.

Overriding Methods & super


class a
{ …
public:
void f1(){
..
}
}

class b extends a
{ …
public:
void f1(){
..
super.f1(); //calls f1 function of a (higher class)
}
public static void main(String args[]){
b var1=new b();
b.f1(); //calls f1 function of b (own class)
}
}

Dynamic Method Dispatch


import java.io.*;
class sphere
{
protected int r;
final float p=3.14f;
sphere()
{
r=0;
9
}
void get()
{
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter radius”);
String aut=br.readLine();
r=Integer.parseInt(aut);
}catch(IOException e){}
}
float volume()
{
float v=(4*p*r*r*r)/3;
System.out.println(“Volume of Sphere is ”+v);
return v;
}
}

class hemisphere extends sphere


{
hemisphere()
{
super()
}
float volume()
{
float h=(2*p*r*r*r)/3;
System.out.println(“Volume of Hemisphere is ”+h);
return h;
}
public static void main(String args[])
{
sphere s=new hemisphere();
s.get();
s.volume();
}
}

Object of type sphere is created.Reference is stored in instance of class hemisphere.

Abstract Classes
They are classes whose objects cannot be created since the objects will not contain full details.eg. of inheritance.

Array handling
class MulArray
{
int i=j=0;
int coor[][]=new int[3][3];
void set()
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
coor[i][j]=j;
}
void show
{
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
System.out.println(coor[i][j]+” “);
System.out.println(“ “);
}
10
}
public static void main(String args[])
{
MulArray c=new MulArray();
c.set();
c.show();
}
}

Strings
 String name[]={“Ashwin”,”Anand”,”Aditya”,”Anirudh”};
printed by name[i]
 Char chars={‘a’,’b’,’c’};
String s=new String(chars);
System.out.println(s); //output is abc
 String(char chars[],int stratIndex,int numchars[])
char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String s=new String(chars,2,3);
System.out.println(s);
Hash Table
It is used to store Strings in a manner that allows quick info search.
Prog:
class hash
{
public static void main(String args[])
{
String s1=”hello”; //99162322
String s2=”Hello”; //69609650
System.out.println(“hash code for “+s1+” is “+s1.hashCode());
System.out.println(“hash code for “+s2+” is “+s2.hashCode());
}
}

String Methods
METHOD USE
length() no of chars in string
charAt() char at location in string
getChars(),getBytes() copy chars,bytes in external array
toCharArray() produces char[] containing char in string
equals(),equalsIgnoreCase() equality check on contents of strings
compareTo() returns 0,+ve,-ve depending on diff. in ASCII values of 1st non matching
char.Case sensitive.
regionMatches() Boolean result
startsWith() indicates whether string starts with argument
endsWith() indicates if string ends with argument
indexOf(),lastIndexOf() returns index where argument starts otherwise -1,lastIndexOf starts from end.
substring() returns new string of specified char set
concat() returns new string containing specified char set
replace() returns new string with replacements made.Returns old string if no match.
toLowerCase(),toUpperCase() returns new string with changes made.
trim() returns new string with white spaces removed from end else returns old string
if no changes.
valueOf() returns string containing char representation of argument
intern() produces one & only one string handle for each unique character sequence
toString() creates string from StringBuffer
length() gives char in StringBuffer
capacity() returns no of chars allocated
ensureCapacity() makes StringBuffer hold atleast desired no of spaces
setLength() Truncates or Expands previous char string

11
charAt() returns char location in buffer
setCharAt() modifies value at location
getChars() copy char in ext. array
Append() argument converted to string & appended to end of curr.buffer increasing
buffer if necessary
insert() 2nd argument converted to string & inserted in the curr.buffer beginning at
offset increasing size if necessary
reverse() order of chars in buffer is reversed

Exception Handling
Object

Throwable

Error Exception

IOException Runtime
Exception

Prog:
import java.io.*;
class test
{
public static void main()
{
int i[]={100,200,300,400,500};
System.out.println(“Enter array index…type end to exit”);
try{
String n;
int x;
BufferedReader d=new BufferedReader(new InputStreamReader(System.in));
while((n=d.readLine())!=null)
{
if(n.equals(“end”)) break;
else{
try{
x=Integer.parseInt(n);
System.out.println(“Array element: “+i[x]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}catch(NumberFormatException e){
System.out.println(e);
}catch(NegativeArraySizeException e){
System.out.println(e);
} //catch
} //else
} //while
}catch(IOException e){}
finally{
System.out.println(“Executes after all try…catch statements”);
}
}
}

Graphics class
Methods used:

12
init():Used for initialization
start():executed after init().Used to run & reload applet
stop():Halts running of applet
destroy():Frees memory space occupied by variables & objects in applet
paint():Used for drawing, writing, creating coloured background or image on applet.
repaint():Calls update() method to clear contents of screen.update() calls paint() to redraw current frame
Prog:
import java.awt.*;
import java.applet.*;
public class shape extends Applet
{
//for drawing bytes & chars
byte b[]={100,114,97,119,66,121,116,101,115};
char c[]={‘d’,’r’,’a’,’w’,’b’,’y’,’t’,’e’,’s’};
String s=”drawString example”;
//this is for polygon
int xs[]={40,49,60,70,57,40,35};
int ys[]={260,310,315,280,260,270,265};
//this is for fill polygon
int xss[]={140,150,180,200,170,150,140};
int yss[]={260,310,315,280,260,270,265};
public void paint(Graphics g)
{
g.drawString(“Some drawing objects”,40,20);
g.drawLine(40,30,200,30);
g.drawRect(40,60,70,40);
g.fillRect(140,60,70,40);
g.drawRoundRect(240,60,70,40,10,20);
g.fillRoundRect(40,120,70,40,10,20);
g.draw3DRect(140,120,70,40,true);
g.drawOval(240,120,70,40);
g.fillOval(40,180,70,40);
g.drawArc(140,180,70,40,0,180);
g.fillArc(240,180,70,40,0,-180);
g.drawPolygon(xs,ys,7);
g.fillPolygon(xss,yss,7);
}
}

The Font & Color class


Prog:
import java.applet.*;
import java.awt.*;
public class fonts extends Applet
{
Font f,f1,f2;
int style;
String s,name;
Image img;
public void init()
{
name=getParameter(“name”);
if(name==null) name=”friend”;
else name=”Have a nice day “+name;
f=new Font(“Helvetica”,Font.BOLD,20);
f1=new Font(“TimesRoman”,Font.BOLD+Font.ITALIC,10);
f2=new Font(“Courier”,Font.ITALIC,20);
img=getImage(getCodeBase(),”clouds.bmp”);
}
public void paint(Graphics g)
{
13
g.setColor(Color.gray);
g.setFont(f);
g.drawString(name,0,0);
style=f.getStyle();
if(style==Font.PLAIN) s=”PLAIN”;
else if(style==Font.BOLD) s=”BOLD”;
else if(style==Font.ITALIC) s=”ITALIC”;
else s=”BOLD & ITALIC”;
g.drawString(“Font name :”+f.getName()+” size is “+f.getSize()+” style is “+s+” family is “+f.getFamily(),30,30);
g.setColor(Color.blue);
g.setFont(f1);
g.drawString(“Font name:TimesRoman”,30,80);
g.setFont(f2);
g.drawString(“Font name:Courier”,30,130);
g.drawString(“Ascent: “+g.getFontMetrics().getAscent()+” Descent: “+g.getFontMetrics().getDescent(),30,180);
g.drawString(“Height: “+g.getFontMetrics().getHeight()+” Leading: “+g.getFontMetrics().getLeading(),30,250);
g.drawImage(img,30,270,this);
}
}

Color Name RGB Value Color Name RGB Value


Color.gray 128,128,128 Color.red 255,0,0
Color.green 0,255,0 Color.blue 0,0,255
Color.yellow 255,255,0 Color.magenta 255,0,255
Color.pink 255,175,175 Color.cyan 0,255,255
In addition,setBackground(),setForeground() , getBackground() , getForeground() can also be used.

Threads
It means line of execution.Using threads more than 2 parts of prog. can be executed simultaneously.
Prog:
import java.awt.*;
import java.applet.*;
public class MovingBall extends Applet implements Runnable
{
Thread mythread=null;
int pos=0;
public void start()
{
mythread=new Thread(this); //this refers to applet
mythread.start();
}
public void run()
{
while(true)
{
for(pos=0;pos<getSize().width;pos+=5){
repaint();
try{ mythread.sleep(80); }
catch(InterruptedException e){};
}
}
}
public void stop()
{
mythread.stop();
mythread=null;
}
public void paint(Graphics g)
{
g.setColor(Color.yellow);

14
g.fillOval(pos,50,30,30);
g.setColor(Color.black);
g.fillOval(pos+6,58,5,5);
g.fillOval(pos+20,58,5,5);
g.drawLine(pos+15,58,pos+15,68);
g.drawLine(pos+12,68,pos+15,68);
g.drawArc(pos,45,30,30,-50,-70);
}
}

Mouse Events
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class mousetest extends Applet implements MouseListener,MouseMotionListener{
public void init(){
addMouseListener(this);
addMouseMotionListener(this);

}
public void mouseClicked(MouseEvent e){
showStatus(“Mouse Clicked At “+e.getX()+”,”+e.getY());
}

public void mouseEntered(MouseEvent e){


showStatus(“Mouse Entered At “+e.getX()+”,”+e.getY());
for(int i=0;i<1000000;i++);
}
public void mouseExited(MouseEvent e){
showStatus(“Mouse Exited At “+e.getX()+”,”+e.getY());
}
public void mousePressed(MouseEvent e){
showStatus(“Mouse Pressed At “+e.getX()+”,”+e.getY());
}
public void mouseReleased(MouseEvent e){
showStatus(“Mouse Released At “+e.getX()+”,”+e.getY());
}
public void mouseDragged(MouseEvent e){
showStatus(“Mouse Dragged At “+e.getX()+”,”+e.getY());
}
public void mouseMoved(MouseEvent e){
showStatus(“Mouse Moved At “+e.getX()+”,”+e.getY());
}
}

Keyboard Events
Prog:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class keytest extends Applet implements KeyListener{
public void init(){
Label l=new Label(“Enter char”);
add(l);
TextField tf=new TextField(20);
tf.addKeyListener(this);
add(tf);
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){
15
showStatus(“Recently typed char in text field is “+e.getKeyChar());
}
}

Accepting values in applet


Prog:
import java.awt.*;
import java.applet.*;
public class accept extends Applet
{
TextField tf[];
int s[],t,avg;
public void init()
{
tf=new TextField[10];
s=new int[10];
for(int x=0;x<10;x++)
{
tf[x]=new TextField(2);
add(tf[x]);
}
}
public void paint(Graphics g)
{
g.drawString(“Enter scores”,5,120);
for(int x=0;x<10;x++)
{
String str=tf[x].getText();
g.drawString(tf[x].getText(),5+x*20,135);
s[x]=Integer.parseInt(str);
}
g.drawString(“Average is “,5,150);
for(int x=0;x<10;x++)
t+=s[x];
avg=t/10;
g.drawString(String.valueOf(avg),150,150);
}
public boolean action(Event event,Object arg)
{
repaint();
return true;
}
}

Buttons
import java.awt.*;
import java.applet.*;
public class button extends Applet
{
Button b1,b2,b3;
public void init()
{
b1=new Button(“Button 1”);
b2=new Button(“Button 2”);
b3=new Button(“Button 3”);
add(b1);
add(b2);
add(b3);
}
public boolean action(Event e,Object o)

16
{
if(e.target instanceof Button)
HandleButton(o);
return true;
}
protected void HandleButton(Object label)
{
if(label==”Button 1”)
b1.setLabel(“1 nottuB”);
else if(label==”Button 2”)
b2.setLabel(“2 nottuB”);
else if(label==”Button 3”)
b3.setLabel(“3 nottuB”);
else
{
b1.setLabel(“Button 1”);
b2.setLabel(“Button 2”);
b3.setLabel(“Button 3”);
}
}
}

Checkbox
import java.awt.*;
import java.applet.*;
public class check extends Applet
{
Checkbox c1,c2,c3;
public void init()
{
c1=new Checkbox(“Option 1”,null,true);
c2=new Checkbox(“Option 2”,null,false);
c3=new Checkbox(“Option 3”,null,false);
add(c1);
add(c2);
add(c3);
}
public boolean action(Event e,Object arg)
{

if(e.target instanceof Checkbox)


ChangeLabel(e);
return true;
}
protected void ChangeLabel(Event e)
{
Checkbox t=(Checkbox)e.target;
String l=t.getLabel();
if(l==”Option 1”)
t.setLabel(“Changed 1”);
else if(l==”Option 2”)
t.setLabel(“Changed 2”);
else if(l==”Option 3”)
t.setLabel(“Changed 3”);
else
{
c1.setLabel(“Option 1”);
c2.setLabel(“Option 2”);
c3.setLabel(“Option 3”);
}
}
17
}
This reference is taken from JAVA HANDBOOK & JAVA 2 COMPLETE REFERENCE
Download latest JAVA from java.sun.com
For any queries contact at ejvyas@rediffmail.com
For books,references,discussion forums visit orforum.cjb.net, java.sun.com, groups.yahoo.com/group/pvpprules

18

You might also like