java introduction started by 5 people called james gosling, patrick naughton, mike sheridan,chris...
TRANSCRIPT
JAVA Introduction
Started by 5 people called James Gosling, Patrick Naughton, Mike Sheridan,Chris Warth ,Ed Frank.
. Object Oriented
. Internet Supported
. Allow us to design Applications and Applets
. Supports Distributed and Network Applications
. Supports Multimedia
. Compiler and Interpret based
. Platform independent and secure
. Multi threaded and Dynamic
Features removed from JAVA
Type definitions and preprocessor directives
Structures and unions
Multiple inheritance and goto statements
Operator overloading and pointers
Functions and Enums
First Java Program
Class First{
public static void main(String args[]){
System.out.println (“Welcome”);}
}
Save File as First.javaCompile as javac First.javaRun as java First
Java Platform
compilerJava program
Byte code
JVM
Machine Dependent Code
Comments in JAVA
// Double slashes
/* C – Style slashes */
/* ------------------------------
------------------------------ */
Built in Data Types in JAVA. Short short integer 16 bit
. Int integer 32 bit
. Float single precision 32 bit
. Long long integer 64 bit
. Double double precision 64 bit
. Boolean true or false 1 bit
. String (derived) all types of data
Classes and Objectspublic class Employee{
String eName;String eAdd;public Employee(){
eName = “pradeep”;eAdd = “Vizag”;
}public void display(){
System.out.println(“Name is : “+eName);System.out.println(“Address is : “+eAdd);
}public static void main(String args[]){
Employee e = new Employee();e.display();
}}
Parameter passing method to function
public class Employee{
float annsal = 40000f;public void incsal(int bonus){
annsal = annsal+bonus;}public static void main(String args[]){
Employee e = new Employee();e.incsal(1000);System.out.println(e.annsal);
}}
Using if statementPublic class Employee{
int age;public boolean checkage(){
if (age > 60)return false;
elsereturn true;
}public static void main(String args[]){
Employee e = new Employee();e.age = 78;if (e.checkage()== false){
System.out.println(“Employee retired”);}
}}
Arrays and For loop demo
class oneDarr{
public static void main(String args[]){
int a[] = {10,20,30},i;// int a[];// a = new int[3];// a[0] = 10;// a[1] = 20;// a[2] = 30;for(i = 0;i < a.length;i++){System.out.println(“value is : “+a[i]);}
}
class twoDarr{
public static void main(String args[]){
int a[] [] = {{10},{10,11},{10,11,12}},I,k=10;// int a[] [];// a = new int[3] [];// a[0] = new int[1];// a[1] = new int[2];// a[2] = new int[3];/* for(i = 0;i < a.length;i++){for(j = 0;j < a[i].length;j++){a[i][j] = k;k++;} */}for(i = 0;i < a.length;i++){for(j = 0;j < a[i].length;j++){System.out.println(“value is : “+a[i][j]);}System.out.println();}
}}
Array and for loop demopublic class Employees{
Employee earr[];public Employees(){
earr = new Employee[2];for(int ctr = 0;ctr<earr.length;ctr++){
earr[ctr] = new Employee();}earr[0].eName = “pradeep”;earr[0].ePh = “9490074915”;
earr[1].eName = “srikanth”;earr[1].ePh = “9949252414”;
}public void display(){
for(int ctr = 0;ctr < earr.length;ctr++){
earr[ctr].display();}
}public static void main(String args[]){
Employees emp = new Employees();emp.display();
}}
Constructors Democlass Employee{
int eno;String ename;
Employee(int x, String y){
eno = x;ename = y;
}void dispeno(){
System.out.println(“Sno is :”+sno);}void dispename(){
System.out.println(“Name is :”+sname);}void display(){
this.dispeno();this.dispename();
}}class test{
public static void main(String args[]){
Employee e = new Employee(12,”pradeep”);e.display();
}}
Overloading Constructorsclass Employee{
int eno;String ename;
Employee(){
eno = 11;ename = “pradeep”;
}Employee(int x, String y){
eno = x;ename = y;
}void disp(){
System.out.println(“sno :”+sno+”\nsname :”+sname);}public static void main(String args[]){
Employee e = new Employee();e.disp();Employee e1 = new Employee(12,”srikanth”);e1.disp();
}}
Constructor to a Constructorclass Employee{
int eno;String ename;
Employee(){
this(11,”pradeep”);}Employee(int x, String y){
this.eno = x;this.ename = y;
}void disp(){
System.out.println(“sno :”+sno+”\nsname :”+sname);}public static void main(String args[]){
Employee e = new Employee();e.disp();Employee e1 = new Employee(12,”srikanth”);e1.disp();
}}
Static Members
class Demo{
int x,y;static int z=77;public static void main(String args[]){System.out.println(“val of z :”+Demo.z);Demo d = new Demo();d.x=10;d.y=20;d.z=99;
System.out.println(“val of x :”+d.x+”\nval of y :”+d.y+“\n val of z :”+d.z);Demo d1 = new Demo();System.out.println(“val of z :”+Demo.z);
System.out.println(“val of z :”+d1.z);
}
Static Member Functionsclass Demo{
int x,y;static int z=77;
void display(){
System.out.println(“val of x :”+d.x+”\nval of y :”+d.y);}static void print(){
System.out.println(“ val of z :”+d.z);}
public static void main(String args[]){System.out.println(“val of z :”+Demo.z);Demo d = new Demo();d.x=10;d.y=20;d.z=99;d.display();d.print();Demo d1 = new Demo();d1.display();d1.print();
}
Overloading Methodsclass Areas{
int b=10,h=20;void area(){
int res = (0.5*b*h);System.out.println(“Area of Triangle is : “+res);
}void area(int l){
int res = (l*b*h);System.out.println(“Area of Rectangle is : “+res);}public static void main(String args[]){
Areas a = new Areas();a.area();a.area(30);
}}
Call by value or referenceclass A{
int x,y;}class B{
public static void fun1(int x,int y){
x = x + 10;y = y + 20;
}public static void fun2(A a){
a.x = a.x + 10;a.y = a.y + 20;
}}class test{
public static void main(String args[]){
int x=10,y=20;A a = new A();a.x = 10;a.y = 20;
System.out.println(“Before :”+x+” “+y);System.out.println(“Before :”+a.x+” “+a.y);
B.fun1(x,y);B.fun2(a);
System.out.println(“Before :”+x+” “+y);System.out.println(“Before :”+a.x+” “+a.y);
}}
Objects as Parametersclass Time{
int h,m;Time(int x,int y){
h = x;m = y;
}Time addtime(Time x,Time y){
Time res = new Time();res.h = x.h + y.h;res.m = x.m + y.m;return res;
}void display(){
System.out.println(h+” : “+m);}public static void main(String args[]){
Time t1 = new Time(2,20);Time t2 = new Time(3,20);Time t3 = new Time();t3.addtime(t1,t2);t3.display();
}}
Inner Classesit is a class which will be defined in another classIf any changes made in the outer class those will be reflected in all its inner classes
class outer {
int outvar = 10;// the above value can be used in all inner classes and also in sub classes
void outfun(){
inner in = new inner1();in.infun();
}
class inner{
int invar = 100;// can be accessed only in this classvoid infun(){
System.out.println(“inner class function”);System.out.println(“Accessing outer var : “+outvar);
}}
}class test{
public static void main(String a[]){
outer out = new outer();out.outfun();
}}
Inheritance. Creation of classes from existed classes in order to reduce coding. Class which is ihherited is super and which inherting that is sub class. We are using extends key word to do this process. We may have multilevel but not multiple inheritance
class person{
int no;String name;
}class student extends person{
String scname;void accept(){
no = 10;name = “vinay”;scname = “St,peters school”;
}void display(){
System.out.println(“\n Student No : “+no+”\n Student Name : “+name+”\n School Name : “+scname);}
}class employee extends person{
String cname;void accept(){
no = 101;name = “Alex”;cname = “Webpros pvt”;
}void display(){
System.out.println(“\n Employee No : “+no+”\n Employee Name : “+name+”\n Company Name : “+cname);}
}class test{
public static void main(String a[]){
student s = new student();employee e = new employee();s.accept()s.display();e.accept();e.display();
}}
Access using Super keywordclass A{
int x;void display(){
System.out.println(“x value of A : “+x);}
}class B extends A{
int x;B(int a,int b){
super.x = a;this.x = b;
}void display(){
super.display();System.out.println(“x value of B : “+x);
}}class test{
public static void main(String a[]){
B b = new B(10,20);b.display();
}}
Constructors in Inheritance
. Super class constructors invoked first than sub class
. If there are no of super classes and then constructors will be executed in the order of the inheritance (from bottom to top)
. We can call super class constructors from sub class constructors using super keyword
. But we must call super constructor first in their order.
class A{
int x,y;A(int x,int y){
this.x = x;this.y = y;
}}class B extends A{
int z;B(int a,int b,int c){
super(a,b);this.z=c;
}void display(){
System.out.println(“values are : “+x+y+z);}
}class test{
public static void main(String a[]){
B b = new B(10,20,30);b.display();
}}
Overridden Methods. When super and sub class method are sharing the same name then those methods are
overriddenclass A{
void f1(){}
}class B extends A{
void f1(){}
}A a = new A();B b = new B();a.f1();b.f1();// both calls class A f1()// so we have reference technology using which we can access the individual functionsA rf;rf = a;rf.f1();rf = b;rf.f1();
Dynamic Method Dispatch
System.in.read() : which reads single char from keyboard and returns a ascii code of that
Ex : int ch = System.in.read();
System.out.println(ch);
And also we can apply type cast :
char ch = (char) System.in.read();
class person{
void accept(){}void display(){}
}class student extends person{
int sno;String sname,scname;void accept(){
sno = 10;sname = “vinay”;scname = “St,peters”;
}void display(){System.out.println(“Student Details : “+sno+” “+sname+” “+scname);}
}class employee extends person{
int eno;String cname;void accept(){
eno = 101;ename = “Alex”;
}void display(){
System.out.println(“\n Employee No : “+no+”\n Employee Name : “+name);}
}class test{
public static void main(String a[]){
char ch;person r;System.out.println(“Enter 1 : Student 2 : Employee\n”);ch = (char) System.in.read();if (ch==‘1’)r = new student();elser = new employee();r.accept();r.display();
}}
Final Keyword
Final keyword : the final can be used with members ,methods and classes
When used by the members they become constants we can’t update
Final methods can’t be override
Final classes can’t be extended to any other classes
Abstract Classes and Methods
When a function of a super class is used only for overriding purpose but it does’t contains any statements then those can be prefixed by the keyword called abstract
When a class contains at least one abstract fun then that class must be made as abstract
When a class is extending any abstract class then it must override all the abstract methods of that class
We can’t create objects to abstract class but we can create reference var
abstract class AC{
abstract void f1();abstract void f2();
}class demo extends AC{
void f1(){
System.out.println(“Hi”);}void f2(){
System.out.println(“Hello”);}
}class test{
public static void main(String a[]){
demo d = new demo();d.f1();d.f2();
AC r;r = new demo();r.f1();r.f2();
}}
interface common{
void f1(); void f2();
}class demo implements common{
public void f1(){
System.out.println(“Hi”);}public void f2(){
System.out.println(“Hello”);}
}class test{
public static void main(String a[]){
demo d = new demo();d.f1();d.f2();
common r;r = new demo();r.f1();r.f2();
}}
Multiple implementsinterface A{
abstract void f1();}interface B{
abstract void f2();}
class demo implements A,B{
public void f1(){
System.out.println(“Hi”);}public void f2(){
System.out.println(“Hello”);}
}class test{
public static void main(String a[]){
demo d = new demo();d.f1();d.f2();
A a;a = new demo();a.f1();B b;b = new demo();b.f2();
}}
Extended Interfacesinterface A{
abstract void f1();}interface B extends A{
abstract void f2();}
class demo implements B{
public void f1(){
System.out.println(“Hi”);}public void f2(){
System.out.println(“Hello”);}
}class test{
public static void main(String a[]){
demo d = new demo();d.f1();d.f2();
A a;a = new demo();a.f1();B b;b = new demo();b.f2();
}}
Exception Handling
. Exception is error which comes at run time
. When ever run time error occurs corresponding object will be created and it will be thrown we have to handle it by using keywords like
1.Try 2.catch 3.throw 4.finally 5.throws
. All the statements should be written in try block and when ever exception is occurred it should be caught by catch block, each catch can handle one type of exception
Syntax try{
statements}catch (exception-type name){
statements}finally{
statements}
try - catch blocksclass Trycatch{
static int arr[]={10,20,30};public static void main(String ar[]){
display(0);display(1);display(2);display(5);
}static void display(int n){
try{
System.out.println(“Value is : “+arr[n]);}catch (ArithmeticException ex){
System.out.println(“Arithmetic Error”);}catch (ArrayIndexOutOfBoundsException ex){
System.out.println(“invalid index passing as parameter”);}catch (ArrayStoreException ex){
System.out.println(“Invalid array”);}
}}
Types of Exceptions
. Enforced and checked exceptions
. Checked exceptions are those which compiler forces to catch (IOExceptions)
. And forced exceptions are thrown at run time ex. Invalid logic or input
. Non recoverable are errors (out of memory ) and recoverable are exceptions (file not found, null pointer exception
. We can have multiple catches to handle multiple exceptions
Example try-throw-catchclass ttc{
static void f1(int n){
if(n == 0)throw new ArithmeticException();if(n < 0)throw new NegativeArraySizeException();
elseSystem.out.println(“OK”);}public static void main(String a[]){
try{
f1(2);f1(-1);f1(0);
}catch(AritameticException ex){
System.out.println(“Arithmetic error occured”);}catch(NegativeArraySizeException ex){
System.out.println(“invalid size of array”);}
}}
Instanceof keyword
class ttc{
static void f1(int n){
if(n == 0)throw new ArithmeticException();if(n < 0)throw new NegativeArraySizeException();
elseSystem.out.println(“OK”);}public static void main(String a[]){
try{
f1(2);f1(-1);f1(0);
}catch(Exception ex){
if(ex instanceof ArithmeticException)
System.out.println(“Arithmetic error”);
else if(ex instanceof NegativeArraySizeException)
System.out.println(“invalid array index”);
}}
}
Finally blockIt can placed immediately after try or after all the catch blocks
Used to execute statements even if an exceptions is thrown or not
try try{ {} }finally() catch() { }{ catch() { }} finally() { }
throws can be used to throw all types of exceptions and we have write this after parameter passing of method and we may have multiple classes separated by comma with this
Ex : public static void main(String a[]) throws Exception,IOException
User defined Exceptionsclass myex extends Exception{
String msg;myex(){
msg = “Array Exception”;}public String sam(){
return msg;}
}class ttc{
static void f1(int n){
if(n < 0)throw new myex();
elseSystem.out.println(“OK”);}public static void main(String a[]){
try{
f1(2);f1(-1);f1(0);
}catch(myex ex){
System.out.println(ex);}
}}
Application vs Applet
Application
Hard DiskInternal Memory (RAM )
Applet
Remote system
Local System
Types of ApplicationsCUI
GUI
About Applet
Applet : An Applet is a program designed in java and will be placed on the server. The applet will be downloaded from remote system to local and then it will be interpreted and it will run as a part of
web program in the browsers like internet explorer 4.0 or netscape navigator
AWT : (Abstract Window Toolkit )Is a collection of classes which provides graphical components like buttons,
textboxes and many more
To create an applet we need to extend applet class into another class
About Applet
When ever applet program is being loaded in the web browser , the browser calls the following methods of applet .we can override those methods when ever we needed
1. public void init() : will be called when applet is loaded for first time in the browser
2. public void start() : called after init ,this will be called every time when doc containing that applet is loaded
3. public void stop() : when next doc is loaded
4. public void destroy() : called when corresponding browser is closed
5. public void paint (Graphics g) : will be called when output must be redrawn, accepts graphic class as parameter
Simple AppletImport java.applet.*;Import java.awt.*;
public class sapplet extends Applet{
public void init(){
setBackground(Color.red);}public void paint(Graphics g){
g.setFont(new Font(“Arial”,Font.BOLD,20);g.setColor(Color.white);g.drawString(“Simple Applet Demo”,100,100);}
}
The above program should be saved as sapplet.java and following code should be written inorder view this applet on browser
<html><applet code=“sapplet.class” width=400 height=400></applet></html>
The code should be written in a file and saved as sapplet.html
Draw a shape on Applet
Import java.applet.*;Import java.awt.*;
public class shape extends Applet{
public void init(){
setBackground(Color.black);}public void paint(Graphics g){Dimention d = getsize();int w = d.width;int h = d.height;
g.setColor(Color.red);g.drawRect(4,4,w-4,h-4);g.drawOval(8,8,w-16,h-16);g.setFont(new Font(“Arial”,Font.BOLD,20);g.setColor(Color.white);g.drawString(“Simple Applet Demo”,100,100);}
}
AWT( Abstract Window Toolkit )
Component class : it is a super class for all types of components and by using which we can create different components and we can place them on applet directly
ComponentButtonText component
– Text field– Text area
LabelCheck boxScrollbarChoiceListContainer
– Panel– Window
» Frame» Dialog box
Component class methods
void setBackground(Color color)
void setForeground(Color color)
void setEnable(Boolean enables)
void setVisible(Boolean visible)
void setSize(int width,int height)
Creating User InterfaceImport java.applet.*;Import java.awt.*;
public class ui extends Applet{
Label l1,l2,l3;TextField t1,t2;Button b1,b2;Checkbox cb1,cb2;CheckboxGroup gen = new CheckboxGroup();Choice c1;public void init(){
setBackground(Color.black);l1 = new Label(“First Name”);l2 = new Label(“Last Name”);l3 = new Label(“Cource”);c1 = new Choice();c1.add(“c lang”);c1.add(“c++ lang”);t1 = new TextField(35);t2 = new TextField(35);cb1 = new Checkbox(“Graduate”);cb2 = new Checkbox(“Post Graduate”);Checkbox o1 = new Checkbox(“Male”,gen,true); Checkbox o2 = new Checkbox(“Female”,gen,true);b1 = new Button(“Submit”);b2 = new Button(“Clear”);
add(l1); add(t1); add(l2);add(t2);add(l3);add(c1);add(cb1)add(cb2);add(o1);add(o2);add(b1);add(b2);
}}
Scrollbar Demo
Used to select a value from given range of values
Scrollbar() : creates vertical scrollbar
Scrollbar(int style) : The style may be Scrollbar.HORIZONTAL or Scrollbar.VERTICAL
Scrollbar (int style ,int initial value,int thumb size,int min,int max)
void setValues(int initial,int thumb size,int min,int max)
int getValue : returns the selected value
void setValue(int val) : moves thumb to a specified value
It can be handled by using AdjustmentListener interface.it contains
public void adjustmentValueChanged(AdjustmentEvent e)
import java.awt.*;import java.applet.*;import java.awt.event.*;
public class scrolldemo extends Applet implements AdjustmentListener{
Scrollbar red = new Scrollbar(Scrollbar.HORIZONTAL,0,100,0,355);Scrollbar green = new Scrollbar(Scrollbar.HORIZONTAL,0,100,0,355);Scrollbar blue = new Scrollbar(Scrollbar.HORIZONTAL,0,100,0,355);
Label l1 = new Label();
public void init(){
setLayout(new GridLayout(4,1));
add(l1);add(red);add(green);add(blue);
red.addAdjustmentListener(this);green.addAdjustmentListener(this);blue.addAdjustmentListener(this);
}public void adjustmentValueChanged(AdjustmentEvent e){
int r = red.getValue();int g = green.getValue();int b = blue.getValue();
Color nc = new Color(r,g,b);l1.setBackground(nc);showStatus("RED : "+r+"GREEN : "+g+"BLUE : "+b);
}}
Layout Management
It specifies how the components should be aligned, sized, positioned
AWT supports five types of layouts . Flow Layout. Border Layout. Grid Layout. Card Layout. Grid Bag Layout
Based on the requirement we have to choose them
Flow Layout
Components are arranged in row order if there is no space in the current row then they will be placed in next row
This is a default layout for applets and panels
FlowLayout()
FlowLayout(int align)//FlowLayout.CENTER is default
FlowLayout(int style,int vspace,int hspace);
Border Layout
In this when ever we are adding a component we have to specify its direction
BorderLayout contains default as CENTER
If u want to changeBorderLayout.EASTBorderLayout.WESTBorderLayout.NORTHBorderLayout.SOUTH
Default layout for frames and dialogs
Grid Layout : in this total area is divided into rows and columns each component is kept at each cell
GridLayout(int rows,int cols)
GridLayout(int r,int c,int vs,int hs)
Panel Layout : in general it can be used as container of components and also some other panels
Each panel can have diff background color
And can have diff layout for each panel
Card Layout
We may no of cards with different layouts and with different controls
They are overlapped one on another
Selected card should be shown and it is identified by its card name
Grid Bag Layout
Best and accurate than other layouts
Uses GridBagConstraints to set height, width, positions of each component
Total area is divided into rows columns and each component can occupy more cells
gbl.setConstraints(<component>,gbc)