Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Programming Quick Reference: Classes, Methods, and Exceptions, Papers of Computer Science

A quick reference for java programming, including class declarations, member variables, method declarations, essential exception classes, and methods of various java classes such as thread, inputstream, outputstream, file, and graphics. It also covers creating applets, labels, checkboxes, and radio buttons.

Typology: Papers

Pre 2010

Uploaded on 08/19/2009

koofers-user-j9o
koofers-user-j9o 🇺🇸

10 documents

1 / 11

Toggle sidebar

Partial preview of the text

Download Java Programming Quick Reference: Classes, Methods, and Exceptions and more Papers Computer Science in PDF only on Docsity! Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Syntax for a standalone application in Java: class <classname> { public static void main(String args[]) { statements; ————————; ————————; } } Steps to run the above application: 1. Type the program in the DOS editor or notepad. Save the file with a .java extension. 2. The file name should be the same as the class, which has the main method. 3. To compile the program, using javac compiler, type the following on the command line: Syntax: javac <filename.java> Example: javac abc.java 4. After compilation, run the program using the Java interpreter. Syntax: java <filaname> (without the .java extension) Example: java abc 5. The program output will be displayed on the command line. Java reserved words: abstract default if package this boolean do implements private throw Break double import protected throws Byte else instanceof public transient case extends int return null try Const for new switch continue while goto synchronized super Catch final interface short void char finally long static volatile class float native Java naming conventions: Variable Names: Can start with a letter, ‘$’ (dollar symbol), or ‘_’ (underscore); cannot start with a number; cannot be a reserved word. Method Names: Verbs or verb phrases with first letter in lowercase, and the first letter of subsequent words capitalized; cannot be reserved words. Example: setColor() Class And Interface Names: Descriptive names that begin with a capital letter, by convention; cannot be a reserved word. Constant Names: They are in capitals. Example: Font.BOLD, Font.ITALIC Java Comments: Delimiters Use // Used for commenting a single line /* ————— */ Used for commenting a block of code /** —————*/ Used for commenting a block of code. Used by the Javadoc tool for generating Java documentation. Primitive datatypes in Java: DataType Size Default Min Value Max Value byte (Signed -128 integer) 8 bits 0 +127 short (Signed -32,768 integer) 16 bits 0 +32,767 int (Signed -2,147,483,648 integer) 32 bits 0 +2,147,483,647 long -9, 223, 372,036,854, (Signed 775,808, Integer) +9,223,372,036, 64 bits 0 854, 775, 807 float 32 bits 0.0 1.4E-45 (IEEE 754 3.4028235E38 floating-point) double 64 bits 0.0 4.9E-324 (IEEE 754 1.7976931348623157E308 floating-point) char 16 bits \u0000 \u0000 (Unicode character) \uFFFF boolean 1 bit false Variable Declaration: <datatype> <variable name> Example: int num1; Variable Initialization: <datatype> <variable name> = value Example: double num2 = 3.1419; Escape sequences: Literal Represents \n New line \t Horizontal tab \b Backspace \r Carriage return 1 3 2 4 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. \f Form feed \\ Backslash \” Double quote \ddd Octal character \xdd Hexadecimal character \udddd Unicode character Arrays: An array which can be of any datatype, is created in two steps – array declaration and memory allocation. Array declaration <datatype> [] <arr ```````````ayname>; Examples int[] myarray1; double[] myarray2; Memory Allocation The new keyword allocates memory for an array. Syntax <arrayname> = new <array type> [<number of elements>]; Examples myarray1 = new int[10]; Myarray2 = new double[15]; Multi-dimensional arrays: Syntax: <datatype> <arrayname> [] [] = new <datatype> [number of rows][number of columns]; Example: int mdarray[][] = new int[4][5]; Flow Control: 1. If……..else statements Syntax: if(condition) { statements; } else { statements; } 2. For loop Syntax: for(initialization; condition; increment) { statements; } 3. While loop Syntax: while(condition) { statements; } 4. Do….While loop Syntax: do { statements; } while(condition); 5. Switch statement Syntax: switch(variable) { case(value1): statements; break; case(value2): statements; break; default: statements; break; } Class Declaration: A class must be declared using the keyword class followed by the class name. Syntax class <classname> { ———— Body of the class A typical class declaration is as follows: <modifier> class <classname> extends <superclass name> implements <interface name> { —————Member variable declarations; —————Method declarations and definitions } Member variable declarations: <access specifier> <static/final/transient/ volatile> <datatype> <variable name> Example public final int num1; Method declarations: <access specifier> <static/final> <return type> <method name> <arguments list> { Method body; } Example public static void main(String args[]) { } Interface declaration: Create an interface. Save the file with a.java extension, and with the same name as the interface. Interface methods do not have any implementation and are abstract by default. Syntax interface <interface name> { void abc(); void xyz(); } Using an interface: A class implements an interface with the implements keyword. 5 7 6 8 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. StringReader Character stream that reads from a string StringWriter Character stream that writes to a StringBuffer that is later converted to a String The java.io.InputStream class: The InputStream class is at the top of the input stream hierarchy. This is an abstract class which cannot be instantiated. Hence, subclasses like the DataInputStream class are used for input purposes. Methods of the InputStream class: Method Description available() Returns the number of bytes that can be read close() Closes the input stream and releases associated system resources mark() Marks the current position in the input stream mark Supported() Returns true if mark() and reset() methods are supported by the input stream read() Abstract method which reads the next byte ofdata from the input stream read(byte b[]) Reads bytes from the input stream and stores them in the buffer array skip() Skips a specified number of bytes from the input stream The java.io.OutputStream class: The OutputStream class which is at the top of the output stream hierarchy, is also an abstract class, which cannot be instantiated. Hence, subclasses like DataOutputStream and PrintStream are used for output purposes. Methods of the OutputStream class: Method Description close() Closes the output stream, and releases associated system resources write(int b) Writes a byte to the output stream write(byte b[]) Writes bytes from the byte array to the output stream flush() Flushes the ouput stream, and writes buffered output bytes java.io.File class: The File class abstracts information about files and directories. Methods of the File class: Method Description exists() Checks whether a specified file exists getName() Returns the name of the file and directory denoted by the path name isDirectory() Tests whether the file represented by the pathname is a directory lastModified() Returns the time when the file was last modified l length() Returns the length of the file represented by the pathname listFiles() Returns an array of files in the directory represented by the pathname setReadOnly() Marks the file or directory so that only read operations can be performed renameTo() Renames the file represented by the pathname delete() Deletes the file or directory represented by the pathname canRead() Checks whether the application can read from the specified file canWrite() Checks whether an application can write to a specified file Creating applets: 1. Write the source code and save it with a .java extension 2. Compile the program 3. Create an HTML file and embed the .class file with the <applet> tag into it. 4. To execute the applet, open the HTML file in the browser or use the appletviewer utility, whch is part of the Java Development Kit. The <applet> tag: Code, width, and height are mandatory attributes of the <applet> tag. Optional attributes include codebase, alt,name, align, vspace, and hspace. The code attribute takes the name of the class file as its value. Syntax: <applet code = “abc.class” height=300 width=300> <param name=parameterName1 value= value1 > <param name=parameterName2 value= value2 > </applet> Using the Appletviewer: Appletviewer.exe is an application found in the BIN folder as part of the JDK. Once an HTML file containing the class file is created (eg. abc.html), type in the command line: Appletviewer abc.html java.applet.Applet class: Methods of the java.applet.Applet class: Method Description init() Invoked by the browser or the applet viewer to inform that the applet has been loaded start() Invoked by the browser or the applet viewer to inform that applet execution has started stop() Invoked by the browser or the applet viewer to inform that applet execution has stopped 17 19 18 20 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. destroy() Invoked by the browser or the appletviewer to inform that the applet has been reclaimed by the Garbage Collector getAppletContext() Determines the applet context or the environment in which it runs getImage() Returns an Image object that can be drawn on the applet window getDocumentBase() Returns the URL of the HTML page that loads the applet getCodeBase() Returns the URL of the applet’s class file getParameter() Returns the value of a named applet parameter as a string showStatus() Displays the argument string on the applet’s status java.awt.Graphics class: The Graphics class is an abstract class that contains all the essential drawing methods like drawLine(), drawOval(), drawRect() and so on. A Graphics reference is passed as an argument to the paint() method that belongs to the java.awt.Component class. Methods of the Graphics class: Method Description drawLine() Draws a line between (x1,y1) and (x2,y2) passed as parameters drawRect()/fillRect() Draws a rectangle of specified width and height at a specified location drawOval()/fillOval() Draws a circle or an ellipse that fills within a rectangle of specified coordinates drawString() Draws the text given as a specified string drawImage() Draws the specified image onto the screen drawPolygon() /fillPolygon() Draws a closed polygon defined by arrays of x and y coordinates setColor() Sets the specified color of the graphics context setFont() Sets the specified font of the graphics context java.awt.Component class: The Component class is an abstract class that is a superclass of all AWT components. A component has a graphical representation that a user can interact with. For instance, Button, Checkbox, TextField, and TextArea. Methods of the Component class: Method Description paint(Graphics g) Paints the component. The Graphics context g is used for painting. setBackground() Sets the background color of the component setForeground() Sets the foreground color of the component SetSize() Resizes the component setLocation() Moves the component to a new location setBounds() Moves the component to specified location and resizes it to the specified size addFocusListener() Registers a FocusListener object to receive focus events from the component addMouseListener() Registers a MouseListener object to receive mouse events from the component addKeyListener() Registers a KeyListener object to receive key events from the component getGraphics() Returns the graphics context of this component update(Graphics g) Updates the component. Calls the paint() method to redraw the component. AWT Components: Many AWT classes like Button, Checkbox, Label, TextField etc. are subclasses of the java.awt.Component class. Containers like Frame and Panel are also subclasses of components, but can additionally hold other components. Label: Constructors · Label() - Creates an empty label · Label(String s) - Creates a label with left justified text string · Label (String s, int alignment) - Creates a label with the specified text and specified aligment. Possible values for alignment could be Label.RIGHT, Label.LEFT, or Label.CENTER Methods of the Label class: Method Description getAlignment() Returns an integer representing the current alignment of the Label. 0 for left, 1 for center, and 2 for right alignment. setAlignment() Sets the alignment of the Label to the specified one getText() Returns the label’s text as a string setText() Sets the label’s text with the specified string Button: Constructors Button() - Creates a button without a label Button(String s) - Creates a button with the specified label 21 23 22 24 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Methods of the Button class: Method Description addActionListener() Registers an ActionListener object to receive action events from the button getActionCommand() Returns the command name of the action event fired by the button. Returns the button label if the command name is null. GetLabel() Returns the button’s label SetLabel() Sets the button’s label to the specified string Checkbox: Constructors · Checkbox() - Creates a checkbox without any label · Checkbox(String s) - Creates a checkbox with a specified label · Checkbox(String s, boolean state) - Creates a checkbox with a specified label, and sets the specified state · Checkbox(String s, boolean state, CheckboxGroup cbg) - Creates a checkbox with a specified label and specified state, belonging to a specified checkbox group Methods of the Checkbox class: Method Description addItemListener() Registers an ItemListener object to receive item events from the checkbox getCheckboxGroup() Returns the checkbox’s group getLabel() Returns the checkbox’s label getState() Determines if the checkbox is checked or unchecked setLabel() Sets the label of the check box with the specified string setState() Sets the specified checkbox state Creating Radio Buttons (Mutually exclusive checkboxes): · First create a CheckboxGroup instance – CheckboxGroup cbg = new CheckboxGroup(); · While creating the checkboxes, pass the checkbox group object as an argument to the constructor - Checkbox (String s, boolean state, CheckboxGroup cbg) Choice: Constructors Choice() - Creates a new choice menu, and presents a pop- up menu of choices. Methods of the Choice class: Method Description add() Adds an item to a choice menu addItem() Adds an item to a choice menu addItemListener() Registers an ItemListener object to receive item events from the Choice object getItem() Returns the item at the specified index as a string getItemCount() Returns the number of items in the choice menu getSelectedIndex() Returns the index number of the currently selected item getSelectedItem() Returns the currently selected item as a string insert() Inserts a specified item at a specified index position remove() Removes an item from the choice menu at the specified index TextField: Constructors · TextField() - Creates a new text field · TextField(int cols) - Creates a text field with the specified number of columns · TextField(String s) – Creates a text field initialized with a specified string · TextField(String s, int cols) - Creates a text field initialized with a specified string that is wide enough to hold a specified number of columns Methods of the TextField class: Method Description isEditable() Returns a boolean value indicating whether or not a text field is editable setEditable() Passing True enables text to be edited, while False disables editing. The default is True. addActionListener() Registers an ActionListener object to receive action events from a text field getEchoChar() Returns the character used for echoing getColumns() Returns the number of columns in a text field 25 27 26 28 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. keyTyped() Invoked whenever a key is typed MouseListener interface: Implemented by a class handling mouse events. It comprises of five methods invoked when a MouseEvent object is generated. Its corresponding adapter class is the MouseAdapter class. Method Description mouseClicked() Invoked when mouse is clicked on a component mouseEntered() Invoked when mouse enters a component mouseExited() Invoked when mouse exits a component mousePressed() Invoked when mouse button is pressed on a component mouseReleased() Invoked when mouse button is released on a component MouseMotionListener interface: Implemented by a class for receiving mouse-motion events. Consists of two methods – mouseDragged() and mouseMoved(), which is invoked when a MouseEvent object is generated. MouseMotionAdapter is its corresponding adapter class. Method Description mouseDragged() Invoked when the mouse is pressed on a component and dragged mouseMoved() Invoked when mouse is moved over a component WindowListener interface: Implemented by a class to receive window events. It consists of seven different methods to handle the different kinds of window events, which are invoked when a WindowEvent object is generated. Its corresponding adapter class is the WindowAdapter class. Method Description windowOpened() Invoked when the window is made visible for the first time windowClosing() Invoked when the user attempts to close the window from the Windows system menu windowClosed() Invoked when the window has been closed as a result of calling the dispose() method windowActivated() Invoked when the window is made active i.e. the window can receive keyboard events windowDeactivated() Invoked when the window is no longer the active window i.e. the window can no longer receive keyboard events windowIconified() Invoked when a normal window is minimized windowDeiconified() Invoked when a minimized window is changed to normal state java.sql.Driver interface: Implemented by every driver class. Methods of the Driver interface: Method Description acceptsURL() Returns a Boolean value indicating whether the driver can open a connection to the specified URL connect() Tries to make a database connection to the specified URL getMajorVersion() Returns the driver’s major version number getMinorVersion() Returns the driver’s minor version number jdbcCompliant() Tests whether the driver is a genuine JDBC compliant driver java.sql.Connection interface: Represents a session with a specific database. SQL statements are executed within a session and the results are returned. Methods of the Connection interface: Method Description Close() Immediately releases the database and JDBC resources commit() Makes all changes since the last commit/rollback permanent, and releases the database locks held by the connection createStatement() Creates and returns a Statement object. It is used for sending SQL statements to be executed on the database getMetaData() Returns a DatabaseMetaData object that represents metadata about the database isReadOnly() Checks whether the connection is a read-only connection prepareCall() Creates and returns a Callable Statement object, 37 39 39 4 Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. Java Programming Guide - Quick Reference © 1999, Pinnacle Software Solutions Inc. prepareCall() Creates and returns a CallableStatement object (used for calling database stored procedures) prepareStatement() Creates and returns a PreparedStatement object (used for sending precompiled SQL statements to the database) rollback() Discards all the changes made since the last commit/rollback and releases database locks held by the connection setAutoCommit() Enables or disables the auto commit feature. It is disabled by default java.sql.DriverManager class: Responsible for managing a set of JDBC drivers. It attempts to locate and load the JDBC driver specified by the getConnection() method. Methods of the DriverManager class: Method Description getConnection() Attempts to establish a database connection with the specified database URL, and returns a Connection object getLoginTimeout() Returns the maximum number of seconds a driver can wait when attempting to connect to the database registerDriver() Registers the specified driver with the DriverManager setLoginTimeout() Sets the maximum number of seconds a driver can wait when attempting to connect to the database getDrivers() Returns an enumeration of all the drivers installed on the system getDriver() Returns a Driver object that supports connection through a specified URL
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved