|
à 2 2
2
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.
¦ 2
2
½o 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.)
|
u
2
2
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.
à
2
2
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.
è
2
2
Simple, secure, portable, objectoriented, multithreaded, robust, distributed. Deprecated: should not used.
¦
2
2 2 2
byte (1 byte), short ( 2 byte), int (4 byte), long (8 byte) float (4 byte),double (8 byte) char ( 1 byte) boolean ( 1 bit)
2
2 2 2
uutomatic 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;
2 2 2
Java is an object oriented language. What is an object ? What is a class?
green ball
red ball
blue ball
£
2
2
Object is an entity or thing that is conceptual. Class is a template of an object.
+ - * / % ++ -- += -= *= /= %= < > >= =< == != && || ! ? instanceof Example: greenBall instanceof Ball : returns true/false
object class
2 2 2 2
It is a predefined class in java. It is not an array of characters. String literal example: "Welcome" String variables : String str="Welcome"
u 2
urrays are data structure that hold similar kind of data.
2
int numbers[10]; int numbers[]={1,2,3,4};
2
2
retrieving data from the arrays: numbers[2]
¦ 2 2 2 2 2
Java programs cannot exist without a class. You cannot have functions that are standalone. ½o 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".
if (condition) statement; [else if (condition) statement;] [else statement;] switch(expression){ [case value1: statement break;] [deafult: default statement;] }
÷
÷
while (condition) { statements } do{ statements } while(condition) for(initialization;condition;iteration){} break continue
÷ ÷ ÷
½amed same as the class name and has no return value. 2 Can have more than one constructor in a java program. 2 If no constructors are provided then a default constructor is assumed with no arguments and nothing done in the method body. 2 un object of a class can be created (instantiated) using µnew¶. For example: Student stud= new Student(³John´, ³123´); 2 urguments passing: 2 1. Pass by value for primitive data type variables 2 2. Pass by reference for objects. 2
2 2 2
2
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. ulso include a µprint¶ method which prints the details of an employee. In µmain¶ create two employees and print their details.
¦ 2 2 2
2
2
ë ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ÷ ! ÷ ÷ ÷
2 2 2
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.
Ú 2 2
2
2
current directory>javac Student.java current directory>java Student: Error occured: Exception in thread "main" java.lang.½oClassDefFoundError: 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.
½ 2 2 2 2
2
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
à
2
2
2
public, private, protected and unspecified/no modifier (default) ull of these are applicable to members of a class. protected access specifier will be dealt with in the later course.
2 2 2 2 2
u class can be defined as either public or default access. u 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.
Ú
2 2
2
wave 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).
2 2 2 2 2 2 2
upplicable only to members. ulso called class member variables and methods Can be accessed even without instantiation of the class. Class½ame.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 ?
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()); } }
2 2 2 2
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?
u 2
2
urrays 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); } }
ñ 2 2
This is a convenient class developed by us for of getting data from console. The methods are:
public public public public public public public public
static static static static static static static static
String inputString(String prompt) int inputInt(String prompt) float inputFloat(String prompt) double inputDouble(String prompt) long inputLong(String prompt) byte inputByte(String prompt) short inputShort(String prompt) boolean inputBoolean(String prompt)
Ú à Write a student class whose attributes are name, regno, marks and grade. (Follow the recommended practice. ) Grade is calculated as follows: 80-100: wD (high distinction) 70-80: D (distinction) 70-60: S (satisfactory) 40-50: P (pass) below 40: F (fail) 2
2
2
2
uccept the details of µn¶ no. of students from console. uccept the value of µn¶ also from console. Sort the students based on the marks obtained from highest to lowest. Display the results.
à 2 2 2 2
un 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.
Ball
"
÷
ë÷ "
÷
football table tennis ball
lawn tennis ball
2
2 2
In java a class can inherit only from one class. keyword: extends ull the methods available in super class is available to subclass. u subclass can redefine them if required. When a subclass redefines a method inherited from super class, it is said to have overridden that method.
2
2
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: u 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.
¦
Student s= new UGStudent();
Class Student
print(s); void print()
.. Student s= new PGStudent(); print(s); #ë÷ ÷ ÷ static void print(Student s)
Class UGStudent Class PGStudent void print()
void print()
{
«
s.print(); «}
÷
è ÷ ÷ ÷
2
2
2
Polymorphism: un ability of a code to determine which method to call at the runtime. ull 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.
2
2
2
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.
2
u protected member of a class can be accessed by all its subclasses.
2
To stop overriding a class can be defined as final.
2
2
ull 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.
2
Creating string objects : 1. String str= new String(); 2. String str= new String("XYZ"); 3. String str="XYZ"; 4. String str1=new String(str);
2
String concatenation: + (overloaded) String a="XYu"; int b=2; System.out.println(a+b);
2
Conversion of other data types to String static String valueOf([any primitive datatype] d) static String valueOf(Object o)
2
£ther 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)
2 2
2
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.
2
2
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. b.
c.
For every employee name, empId and designation are maintained. Temporary Employee: The salary for temporary employee is calculated based on the number of days he/she has worked. Permanent Employee: The salary for permanent employee is fixed for every designation. Manager gets Rs.50,000,
Project Leader gets Rs. 40,000 2 Team Leader gets Rs. 30,000 2 Programmer gets Rs. 20,000. Write a menu driven program which does following: 1. udd permanent employee 2. udd temporary employee 3. Print list of all employees entered so far with salaries. 2
uWT
uè 2 2 2 2 2 2
Used to provide GUI for java applications. We will be creating stand alone java applications using uWT. We begin by looking at how to create windows, labels, textboxes and buttons ufter this we shall look at event driven programming. Then we will learn basic layout managers. ½ote that we will be delivering only a minimal set that will make enable us to write a resonable stand-alone java program.
ubstract 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 u Frame is a top-level window with a title and a border.
Frame u Window object is a top-level window with no borders and no menubar.
java.awt package
Panel
Panel is the simplest container class. u panel provides space in which an application can attach any other component, including other panels.
2
2
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)
M public void add(Component comp, £bject constraints)
2
2
constraints are : BorderLayout.½ORTw, BorderLayout.SOUTw, BorderLayout.EuST, BorderLayout.WEST, and BorderLayout.CE½TER. We shall deal with BorderLayout class later.
public void validate()
2
2 2
uWT 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);
2
static static static static static static static static static static static static static
2
Color(float r, float g, float b)
2 2 2 2 2 2 2 2 2 2 2 2
Color Color Color Color Color Color Color Color Color Color Color Color Color
black , static Color BLACK blue , static Color BLUE cyan , static Color CYAN DARK_GRAY ,static Color darkGray gray , static Color GRAY green ,static Color GREEN LIGHT_GRAY, static Color lightGray magenta ,static Color MAGENTA orange ,static Color £RANGE pink , static Color PINK red , static Color RED white ,static Color WHITE yellow ,static Color YELL£W
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(); } }
¦ 2 2
2
Panel is the simplest container class. u panel provides space in which an application can attach any other component, including other panels. u 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)
uè 2 2 2 2 2 2 2 2
Label TextField Texturea Checkbox Choice List Button MenuBar and Menu
2
2
2
Component used to place text in a container. u label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly.
Label() 2 Label(String text) 2 Label(String text, int alignment) Alignment:B£TT£M_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, T£P_ALIGNMENT 2
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(); }}
M 2
2
u 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)
M 2 2 2 2 2 2
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();}}
u 2
2 2 2 2 2 2
u Texturea 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)
u 2 2 2 2 2 2 2 2 2 2 2 2
SCROLLBuRS_BOTw, SCROLLBuRS_VERTICuL_O½LY, SCROLLBuRS_wORIZO½TuL_O½LY, SCROLLBuRS_½O½E. 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 £ne 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();} }
| 2 2 2 2 2 2 2
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();} }
Ú 2
The constructors of Checkbox class with CheckboxGroup class as argument are used to achieve the radio button controls.
2 Checkbox(String label, boolean state, 2
CheckboxGroup group) Checkbox(String label, CheckboxGroup group, boolean state)
2
The CheckboxGroup class is used to group together a set of Checkbox buttons. Constructor:
2
public CheckboxGroup()
2
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();} }
2 2 2 2 2 2 2 2 2 2 2
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)
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. 2 Constructors List() List(int rows) List(int rows,boolean multipleMode) 2
2 2 2 2 2 2 2 2 2 2
Methods: public public public public public public public public public
void add(String item) String getItem(int index) int getItemCount() int[] getSelectedIndexes() String[] getSelectedItems() void remove(int position) void remove(String item) void removeAll() 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();}}
| 2 2 2 2 2
2 2
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()
© |© 2
MenuBar: Constructor and Method
2
public MenuBar() public Menu add(Menu m)
2
Menu: Constructors and methods
2
2 2 2 2 2 2 2 2 2 2 2
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)
© à
2 2 2 2 2 2 2
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 wandling
© Source(Button)
Registers itself to receive events
Generates events
Event object
Listener (Window) Sends event object
Source delegates the responsibility of event handling to Listener.
2 2
2
un object that generates events. ull the components generate some or other events. General form of method to register a listener:
addë Listener(ë Listener t) Where ë Mouse events.(addMouseListner(MouseListener e))
2 2
2
Listener is an object that wants to be notified of the event occurance. uny 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.
2 2 2 2 2
un 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
© 2 2 2 2 2 2 2
2 2 2 2
Listener class: MouseListener Methods void void void void void
mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent e) mousePressed(MouseEvent e) 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();} }
è 2 2 2 2 2 2 2 2 2
è ÷ $ ÷ % void void void void void void void
windowActivated(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowDeactivated(WindowEvent e) windowDeiconified(WindowEvent e) windowIconified(WindowEvent e) window£pened(WindowEvent e)