Vous êtes sur la page 1sur 102

Basic Java

Introduction
 Developed by Sun Microsystems.
 Java – an island in Indonesia where a lot
of coffee is grown.
 Designed with syntax similar to C++
syntax to help programmers in C++
migrate fast to Java.
Points about Java

 No pointers, structure and union,


operator overloading, preprocessors,
default arguments, global variables,
unsigned integers, goto, delete.
 The compilation of a program results in
byte code. (This enables the ‘write once
run everywhere’ feature of java.)
Byte code
Advantages

 Makes java byte code platform


independent. (Only JVM is implemented
differently for different OS’).
 Makes java program secure. JVM
doesn’t execute anything that might
cause a security issue.
Just In Time Compiler

 Disadvantages is that it is slower as it is


interpreted.
 JIT compiler that comes with Java 2 that
helps java byte code to compile java byte
code in small chunks.
Words associated with java

 Simple, secure, portable, object-oriented,


multithreaded, robust, distributed.
 Deprecated: should not used.
Primitive datatypes

 byte (1 byte), short ( 2 byte), int (4 byte),


long (8 byte)
 float (4 byte),double (8 byte)
 char ( 1 byte)
 boolean ( 1 bit)
Casting

 Automatic conversion:
byte->short->int->long->float->double
char
 char and boolean are not convertible to each
other via casting.
 Casting required when destination class is
smaller than the source class.
 Example int k=(double)3.14;
Class and Object
 Java is an object oriented language.
 What is an object ?
 What is a class? Class
Ball

green ball red ball blue ball Objects


 Object is an entity or thing that is
conceptual.
 Class is a template of an object.
Operators
+ - * / % ++ -- += -= *= /= %=
< > >= =< == != && || ! ?
instanceof

Example:
greenBall instanceof Ball : returns true/false

object
class
String

 It is a predefined class in java.


 It is not an array of characters.
 String literal example: "Welcome"
 String variables : String str="Welcome"
Arrays
 Arrays are data structure that hold
similar kind of data.

 int numbers[10];
 int numbers[]={1,2,3,4};

 retrieving data from the arrays:


numbers[2]
Points to bear in mind

 Java programs cannot exist without a class.


 You cannot have functions that are
standalone.
 No global variables in Java.
 The java file must have the same name as
the public java class in that file.
 This java file must be stored in a file called
"Welcome.java".
Conditional statements
if (condition) statement;
[else if (condition)
statement;]
[else statement;] n times

switch(expression){
[case value1:
statement
1 to n times
break;]
[deafult: default statement;]
}
Loops
while (condition) { statements }

do{ statements } while(condition)

for(initialization;condition;iteration){}

break

continue
Constructors and methods

new Student(“John”,”123”)
Constructors

 Named same as the class name and has no return value.


 Can have more than one constructor in a java program.
 If no constructors are provided then a default constructor
is assumed with no arguments and nothing done in the
method body.
 An object of a class can be created (instantiated) using
‘new’. For example:
Student stud= new Student(“John”, “123”);
 Arguments passing:
 1. Pass by value for primitive data type variables
 2. Pass by reference for objects.
Exercises
 Write a java code to print odd numbers.
 Write a java code to calculate sum of digits in
a given number.
 You have been given 10 number which are not
in sorted order. Write a java code to sort them.
 Write an Employee class with attributes –
name, age and salary. Write appropriate
constructors, getters and setters for this class.
Also include a ‘print’ method which prints the
details of an employee. In ‘main’ create two
employees and print their details.
Packages
 Group of similar classes that are created to carry out a
common objective can be placed inside a package.
 Packages help in creating namespace for each class.
 Java packages are implemented using file system directories.
Hence all the classes in java are placed in packages. If no
package is defined then '.’(current directory) is assumed.
 A (public) class defined in one package can be made available
to another class defined in another package using import
statements (provided it is available in the classpath).
 All classes inside the package java.lang which is shipped with
JDK are available by default to java programs. String class is
defined inside this package.
Classpath

 Classpath is an environment variable (like


path)
 Classpath contains a list of packages the
compiler searches during compilation.
 When a Java compiler encounters a class
(declared) it seacrhes the current directory
first and if it does not find it, it searches the
classpath.
Running

 current directory>javac Student.java


 current directory>java Student: Error occured: Exception
in thread "main" java.lang.NoClassDefFoundError:
Student (wrong name:college/Student)": JVM is trying to
look fot Student but we named the class as
college.Student.
 current directory>java college.Student: same error. JVM
is trying to find the class inside a folder college from the
current directory. But there is no folder college in the
current directory.
 current directory -1 >java college.Student: Eureka.
Naming Convention
 Class: should begin with uppercase
 Variables/Objects: should begin with
lower case
 Method: should begin with lower case
 If x is member variable then, getter
methods should begin with getX() and
setters should begin with setX()
 Packages: should begin with lower case
Important access specifiers

 public, private, protected and


unspecified/no modifier (default)
 All of these are applicable to members
of a class.
 protected access specifier will be dealt
with in the later course.
Some pointers
 A class can be defined as either public or
default access.
 A public class and the file name must same.
 The main method should be defined in the
public class.
 There can be any number of class in a java
file but only one public class.
 main() method must be public so that JVM
can call the main() method.
Recommended practice
 Have all the variables declared as private.
 Create getters and setters for variables
where ever necessary. These variables
should then be accessed only through their
getters and setters.
 Create a constructor that can set values for
all the necessary attributes (those attributes
which will be set at the same point of time).
Static

 Applicable only to members.


 Also called class member variables and methods
 Can be accessed even without instantiation of the class.
 ClassName.staticMethod(), object.staticMethod()
 Static methods cannot access not static members of a
class, this and super().
 The main() method has to be declared as static -- guess
why?
 Can constructors be static ?
Example: counter
package myjava;

public class Counter {

private static int count;

public static int increment(){return ++count;}

public int getCount() { return count; }

public static void main(String args[]){


System.out.println(Counter.increment());
Counter c1= new Counter();
System.out.println(c1.increment());
}
}
final

 member variables or methods can be


final.
 final member variable means it is a
constant.
 final member methods cannot be
overridden.
 Can constructors be final?
Object Arrays

 Arrays are implemented as objects in


java. It means that the arrays are passed
by reference and not by value.
 Length of an array is obtained by
accessing its 'length' instance variable.
public class Student{
private String name;
private int regNo;
public String getName(){ return name; }
public int getRegNo(){ return regNo; }
public void setName(String nm){ name=nm; }
public void setRegNo(int reg){ regNo=reg; }
public Student(String nm, int reg){
setName(nm);
setRegNo(reg);
}
public static void main(String args[]){
Student studs[] = new Student[2];
studs[0]=new Student(“Arun”,1);
studs[1]= new Student(“Anita”,2); }
}
User class developed by us
 This is a convenient class developed by
us for of getting data from console.
 The methods are:
public static String inputString(String prompt)
public static int inputInt(String prompt)
public static float inputFloat(String prompt)
public static double inputDouble(String prompt)
public static long inputLong(String prompt)
public static byte inputByte(String prompt)
public static short inputShort(String prompt)
public static boolean inputBoolean(String prompt)
EXERCISES
 Write a student class whose attributes are
name, regno, marks and grade. (Follow the
recommended practice. ) Grade is calculated
as follows:
80-100: HD (high distinction)
70-80: D (distinction)
70-60: S (satisfactory)
40-50: P (pass)
below 40: F (fail)
 Accept the details of ‘n’ no. of students
from console. Accept the value of ‘n’ also
from console.
 Sort the students based on the marks
obtained from highest to lowest.
 Display the results.
Inheritance
 An object oriented feature.
 Inheritance is a relationship between two
classes.
 One class will be called the super class,
other subclass.
 The subclass will have features that are
an extension or restriction of a super
class.
Super Class
Ball

Specialization Generalization

Class
football

table tennis ball lawn tennis ball objects

objects objects

Subclass Class
Subclass Class Subclass Class
Java inheritance
 In java a class can inherit only from one class.
 keyword: extends
 All the methods available in super class is
available to subclass. A subclass can redefine
them if required. When a subclass redefines a
method inherited from super class, it is said to
have overridden that method.
 Subclass cannot redefine a method to have
lesser access privilege than what was
originally defined. That is, if a method is
defined as public in super class, it cannot be
defined as protected or anything lower than
that in subclass.
 Casting: A subclass can be converted to its
parent class without explicit casting. But for a
super class to be converted to subclass
explicit casting is required.
Polymorphism – dynamic binding

Class Student Student s= new UGStudent();


print(s);
void print() ..
Student s= new PGStudent();
print(s);
UGStudent’s print method is called at run-time

static void print(Student s)


Class UGStudent Class PGStudent { …
s.print();
void print() void print()
…}

overridden Which print() will be called is determined at run-time


 Polymorphism: An ability of a code to
determine which method to call at the run-time.
 All the methods we have seen so far were
statically bound to a particular type of class. In
other words, which method is to be called is
determined at compile time.
 In case of polymorphism, which method to be
called is determined only at run-time. This is
called dynamic binding.
Constructors

 When a child class is created its


parent's class's constructor is called first.
 If the child class does not call the
super() method explicitly, super() method
without any arguments is called.

protected
 A protected member of a class can be accessed by all its subclasses.
final revisited

 To stop overriding a class can be


defined as final.
Object

 All classes by default inherit from a predefined


java class Object.
 Two important methods in Object class:
-- boolean equals(Object obj): Determines if
one object is equal to another object.
-- String toString(): Returns a string describing
the object.
String

 Creating string objects :


1. String str= new String();
2. String str= new String("XYZ");
3. String str="XYZ";
4. String str1=new String(str);
String

 String concatenation: + (overloaded)


String a="XYA";
int b=2;
System.out.println(a+b);
String

 Conversion of other data types to String

static String valueOf([any primitive


datatype] d)

static String valueOf(Object o)


String
 Other important methods:
char charAt(int i)
boolean equalsIgnoreCase(String str)
boolean startsWith(String str)
boolean endsWith(String str)
String substring(int startIndex, [int endIndex])
String replace(char original, char replacement)
String trim()
String toUpperCase()
String toLowerCase()
int length()
int compareTo(String str)
int compareToIgnoreCase(String str)
Difference between == &
equals() in case of objects

 Lets us work with Strings


 == compares two object references
(addresses) to see if they are same
references
 equals() compares the value -- the
actual characters in the String.
Exercises
 For the student class created in the
previous exercise, accept 10 students in
unsorted order and sort them by their
names.
 We have two types of employees
working for an company – temporary and
permanent. We need to maintain the
following information:
a. For every employee name, empId and
designation are maintained.
b. Temporary Employee: The salary for
temporary employee is calculated
based on the number of days he/she
has worked.
c. Permanent Employee: The salary for
permanent employee is fixed for every
designation. Manager gets Rs.50,000,
 Project Leader gets Rs. 40,000
 Team Leader gets Rs. 30,000
 Programmer gets Rs. 20,000.
Write a menu driven program which does
following:
1. Add permanent employee
2. Add temporary employee
3. Print list of all employees entered so far with
salaries.
AWT
AWT (abstract window toolkit)
 Used to provide GUI for java applications.
 We will be creating stand alone java applications using
AWT.
 We begin by looking at how to create windows, labels,
textboxes and buttons
 After this we shall look at event driven programming.
 Then we will learn basic layout managers.
 Note that we will be delivering only a minimal set that
will make enable us to write a resonable stand-alone
java program.
Class hierarchy
Abstract class, has all the methods that a control that
appears on the should have. Component

Generict class, that can have components added on them.


Container

Window Panel

A Frame is a top-level window with Frame


a title and a border.

A Window object is a top-level Panel is the simplest container


window with no borders and no class. A panel provides space in
menubar. which an application can attach
any other component, including
other panels.

java.awt package
Creating windows for a stand-
alone application
 Frame class is used to create window for a
stand-alone application.
 Constructors and methods:
Frame()
Frame(String title)
void setSize(int width, int height)
void setVisible(boolean flag)
void setTitle(String title)
void setMenuBar(MenuBar mb)
void removeAll()
void remove(Component c)
Component add(Component comp)
public void setResizable(boolean resizable)
Frame layout
public void add(Component comp, Object constraints)
 constraints are : BorderLayout.NORTH,
BorderLayout.SOUTH, BorderLayout.EAST,
BorderLayout.WEST, and
BorderLayout.CENTER.
 We shall deal with BorderLayout class later.
public void validate()
 AWT uses validate to cause a container to lay
out its subcomponents again after the
components it contains have been added to
or modified.
 public void setBackground(Color c)
 Example: setBackground(Color.RED);
Color
 static Color black , static Color BLACK
 static Color blue , static Color BLUE
 static Color cyan , static Color CYAN
 static Color DARK_GRAY ,static Color darkGray
 static Color gray , static Color GRAY
 static Color green ,static Color GREEN
 static Color LIGHT_GRAY, static Color lightGray
 static Color magenta ,static Color MAGENTA
 static Color orange ,static Color ORANGE
 static Color pink , static Color PINK
 static Color red , static Color RED
 static Color white ,static Color WHITE
 static Color yellow ,static Color YELLOW

 Color(float r, float g, float b)


Example
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame()
{
super("New Title");
setSize(300,300);
show();
}
public static void main(String str[]){
new MyFrame();
}
}
Panel
 Panel is the simplest container class.
 A panel provides space in which an application
can attach any other component, including
other panels.
 A panel is genarally place on a frame or other
panels so that we can group components to
have visual effects.
void removeAll()
void remove(Component c)
Component add(Component comp)
public void setBackground(Color c)
AWT Controls
 Label
 TextField
 TextArea
 Checkbox
 Choice
 List
 Button
 MenuBar and Menu
Label
 Component used to place text in a
container.
 A label displays a single line of read-only
text.
 The text can be changed by the
application, but a user cannot edit it
directly.
Constructors and methods
 Label()
 Label(String text)
 Label(String text, int alignment)

Alignment:BOTTOM_ALIGNMENT, CENTER_ALIGNMENT,
LEFT_ALIGNMENT, RIGHT_ALIGNMENT,
TOP_ALIGNMENT
Example
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("New Title");
setSize(300,300);
setVisible(true);
Panel p= new Panel();
p.add(new Label("Name"));
p.add(new Label("ID"));
add(p,BorderLayout.CENTER);
validate(); }
public static void main(String str[]){
new MyFrame();
}}
TextField
 A TextField object is a text component
that allows for the editing of a single line
of text.
 Constructors :
TextField()
TextField(int columns)
TextField(String text)
TextField(String text, int columns)
TextFields methods
 void isEditable(boolean edit)
 boolean isEditable()
 void setEchoChar(char ch)
 char getEchoChar()
 String getText()
 void setText(String t)
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("New Title");
setSize(200,100);
setResizable(false);
setVisible(true);
Panel p= new Panel();
p.add(new Label("Login"));
p.add(new TextField(10));
p.add(new Label("Password"));
TextField password= new TextField(10);
password.setEchoChar('*');
p.add(password);
add(p,BorderLayout.CENTER);
validate();}
public static void main(String str[]){
new MyFrame();}}
TextArea
 A TextArea object is a multi-line region that
displays text. It can be set to allow editing or to
be read-only.
 Constructors:
 TextArea()
 TextArea(int rows, int columns)
 TextArea(String text)
 TextArea(String text, int rows, int columns)
 TextArea(String text, int rows, int columns,
int scrollbars)
TextArea scrollbars values
 SCROLLBARS_BOTH,
 SCROLLBARS_VERTICAL_ONLY,
 SCROLLBARS_HORIZONTAL_ONLY,
 SCROLLBARS_NONE.
 Methods:
 void isEditable(boolean edit)
 boolean isEditable()
 public void append(String str)
 String getText()
 void setText(String t)
 public void setColumns(int columns)
 public void setRows(int rows)
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("Text Area Demo");
setSize(500,200);
setResizable(false);
setVisible(true);
Panel p= new Panel();
String str="An EJB module is used to assemble one or more
enterprise beans into a single deployable unit.\n An EJB
module is stored in a standard Java archive (JAR) file.\n
An EJB module contains the following:\n One or more
deployable enterprise beans.\n deployment descriptors ";
TextArea ta= new TextArea(5,50);
ta.setText(str);
p.add(ta);
add(p,BorderLayout.CENTER);
validate();}
public static void main(String str[]){
new MyFrame();}
}
Check Boxes
 Constructor & Methods
 Checkbox()
 Checkbox(String label)
 Checkbox(String label, boolean state)
 public void setState(boolean state)
 public boolean getState()
 public void setCheckboxGroup(CheckboxGroup g)
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("Checkbox Area Demo");
setSize(200,100);
setResizable(false);
setVisible(true);
Panel p= new Panel();
p.add(new Checkbox("Red"));
p.add(new Checkbox("Blue"));
p.add(new Checkbox("Green"));
add(p,BorderLayout.CENTER);
validate();}
public static void main(String str[]){
new MyFrame();}
}
Radio buttons
 The constructors of Checkbox class with
CheckboxGroup class as argument are
used to achieve the radio button
controls.
 Checkbox(String label, boolean state,
CheckboxGroup group)
 Checkbox(String label, CheckboxGroup group,
boolean state)
CheckboxGroup
 The CheckboxGroup class is used to
group together a set of Checkbox buttons.
 Constructor:
 public CheckboxGroup()
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("Checkbox Area Demo");
setSize(200,100);
setResizable(false);
setVisible(true);
Panel p= new Panel();

CheckboxGroup cbg=new CheckboxGroup();


p.add(new Checkbox("Red",true,cbg));
p.add(new Checkbox("Blue",false,cbg));
p.add(new Checkbox("Green",false,cbg));
add(p,BorderLayout.CENTER);
validate();}

public static void main(String str[]){


new MyFrame();}
}
Choice
 Constructor and methods
 Choice()
 public void add(String item)
 public String getItem(int index)
 public int getItemCount()
 public int getSelectedIndex()
 public String getSelectedItem()
 public void remove(int position)
 public void remove(String item)
 public void removeAll()
 public void select(int pos)
List
 The List component presents the user with a
scrolling list of text items. The list can be set
up so that the user can choose either one item
or multiple items.
 Constructors

List()
List(int rows)
List(int rows,boolean multipleMode)
         
 Methods:
 public void add(String item)
 public String getItem(int index)
 public int getItemCount()
 public int[] getSelectedIndexes()
 public String[] getSelectedItems()
 public void remove(int position)
 public void remove(String item)
 public void removeAll()
 public void select(int pos)
import java.awt.*;
public class MyFrame extends Frame{
public MyFrame(){
super("List Area Demo");
setSize(200,100);
setResizable(false);
setVisible(true);
Panel p= new Panel();
List lst = new List(4, true);
lst.add(“Sun");
lst.add(“Moon");
lst.add("Earth");
lst.add(“Star");
p.add(lst);
add(p,BorderLayout.CENTER);
validate();}
public static void main(String str[]){
new MyFrame();}}
Button
 Constructors and methods
 Button()
 Button(String label)
 public void setActionCommand(String command)
 Sets the command name for the action event
fired by this button. By default this action
command is set to match the label of the
button.

 public void setLabel(String label)


 public String getLabel()
MenuBar, Menu
 MenuBar: Constructor and Method
 public MenuBar()
 public Menu add(Menu m)
 Menu: Constructors and methods
 Menu()
 Menu(String label)
 public MenuItem add(MenuItem mi)
 public void add(String label)
 public int countItems()
 public MenuItem getItem(int index)
 public void insert(MenuItem menuitem,int index)
 public void insert(String label,int index)
 public void remove(int index)
 public void removeAll()
 public void setEnabled(boolean b)
MenuItem
 MenuItem()
 MenuItem(String label)
 public boolean isEnabled()
 public void setEnabled(boolean b)
 public void setLabel(String label)
 public String getActionCommand()
 public void setActionCommand(String
command)
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame{
public MyFrame(){
super("List Area Demo");
setSize(200,100);
setResizable(false);
setVisible(true);
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu edit = new Menu("Edit");
MenuItem item1,item2,item3;
edit.add(item1=new MenuItem("Cut"));
edit.add(item2=new MenuItem("Paste"));
item1.setShortcut(new MenuShortcut(KeyEvent.VK_A));

mb.add(edit);
}
public static void main(String str[]){
new MyFrame();}}
Event Handling
The Delegation Event Model

Registers itself to receive events


Source(Button)

Generates events

Event
object
Listener (Window)
Sends event
object

Source delegates the responsibility of event handling to Listener.


Source
 An object that generates events.
 All the components generate some or
other events.
 General form of method to register a
listener:
addTypeListener(TypeListener t)
Where Type is the kind of event that component
generates. For example, all componets generates
Mouse events.(addMouseListner(MouseListener e))
Listeners
 Listener is an object that wants to be
notified of the event occurance.
 Any component can be a listener
provided it implements the appropriate
Listener class.
 For a listener to receive events it must
also register itself with the source that
generates events.
Event object
 An event object describes the event that has
occurred.
 Each event is associated with an event type.
 For example, a mouse event generates an
object of type MouseEvent.
 We will learn following event handling during this
course:
 Mouse events, window events, action events,
adjustment events, text events, item events, key
events
Mouse event handling
 Listener class: MouseListener
 Methods
 void mouseClicked(MouseEvent e)
 void mouseEntered(MouseEvent e)
 void mouseExited(MouseEvent e)
 void mousePressed(MouseEvent e)
 void mouseReleased(MouseEvent e)
 Event: MouseEvent
 Methods
 public int getX()
 public int getY()
import java.awt.*;
import java.awt.event.*;
public class MouseHandling extends Frame implements
MouseListener{
int x=0,y=0;
Label l;
public MouseHandling(){
super("List Area Demo");
setSize(300,300);
setResizable(false);
setVisible(true);
Panel p= new Panel();
l= new Label();
p.add(l);
add(p,BorderLayout.CENTER);
validate();
// adds the current window as a listener to the mouse event
generated on the panel.
p.addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
x=e.getX();
y=e.getY();
l.setText("Mouse Clicked at " + x + " , "+ y);
validate();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public static void main(String str[]){


new MouseHandling();}
}
Window event handling
 WindowListener
 Methods:
 void windowActivated(WindowEvent e)
 void windowClosed(WindowEvent e)
 void windowClosing(WindowEvent e)
 void windowDeactivated(WindowEvent e)
 void windowDeiconified(WindowEvent e)
 void windowIconified(WindowEvent e)
 void windowOpened(WindowEvent e)

Vous aimerez peut-être aussi