java 1 oral .pdf
java 1 oral .pdf
Java Tools
1. javac:- javac is the java compiler which compiles .java file into .class file(i.e.
bytecode). If the program has syntax errors, javac reports them. If the program is
error-free, the output of this command is one or more .class files.
Syntax: javac fileName.java
2. java:- This command starts Java runtime environment, loads the specified .class file
and executes the main method.
Syntax: java fileName
4 jdb: - jdb helps you find and fix bugs in Java language programs. This debugger has
limited functionality.
Syntax: jdb [ options ] [ class ] [ arguments ]
5.javap: - The javap tool allows you to query any class and find out its list of methods
and constants.
javap [ options ] class
Assignment 2
Wrapper classes : The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
BufferedReader
BufferedReader br = new BufferedReader ( new InputStreamReader (System.in));
For this,you will have write the following statement at the beginning:
import java.io.*;
Packages:
A package is a collection of related classes and interfaces. It provides a mechanism for
compartmentalizing classes. The Java API is organized as a collection of several
predefined packages. The java.lang package is the default package included in all java
programs. The commonly used packages are:
Creating a package :
To create a user defined package, the package statement should be written in the source
code file. This statement should be written as the first line of the program. Save the
program in a directory of the same name as the package.
Syntax :
package packageName;
Accessing a package
To access classes from a package, use the import statement.
Syntax :
import packageName.*; //importsallclasses
Assignment 3
The“super”keyword
It is used for three purposes:
i. Invoking superclass constructor-super(arguments)
ii. Accessing superclass members–super.member
iii. Invoking superclass methods–super.method(arguments)
Overriding methods
Redefining superclass methods in a subclass is called overriding. The signature of the
subclass method should be the same as the superclass method.
Dynamic binding
When over-riding is used ,the method call is resolved during run-time i.e. depending on
the object type, the corresponding method will be invoked.
Abstract class
An abstract class is a class which cannot be instantiated. It is only used to create
subclasses. A class which has abstract methods must be declared abstract.
An abstract class can have data members, constructors, method definitions and method
declarations
Syntax :
abstract class ClassName
Abstract method
An abstract method is a method which has no definition. The definition is provided by
the subclass.
Syntax :
abstract returnType method(arguments);
Interface
An interface is a pure abstract class i.e. it has only abstract methods and final variables.
An interface can be implemented by multiple classes.
Syntax :
interface InterfaceName
Marker Interface :
An interface that does not contain methods, fields, and constants is known as marker
interface. In other words, an empty interface is known as marker interface or tag interface. It
delivers the run-time type information about an object. It is the reason that the JVM and
compiler have additional information about an object.
The Serializable and Cloneable interfaces are the example of marker interface. In short, it
indicates a signal or command to the JVM. The declaration of marker interface is the same as
interface in Java but the interface must be empty.
Functional Interfaces
A functional interface in Java is an interface that contains only a single abstract
(unimplemented) method. A functional interface can contain default and static methods
which do have an implementation, in addition to the single unimplemented method.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.
It is a new feature in Java, which helps to achieve functional programming approach.
Syntax :
public interface MyFunctionalInterface();
lambda Expression
A Java lambda expression is thus a function which can be created without belonging to any
class. Java lambda expressions are commonly used to implement simple event listeners /
callbacks, or in functional programming with the Java Streams API.
Syntax :
lambda operator -> body
Assignment 4
Exception :
An exception is an abnormal condition that arises in a code at run time.
When an exception occurs.
throws keyword:
If the method cannot handle the exception, it must declare a list of exceptions it may cause.
This list is specified using the throws keyword in the method header.
All checked exceptions muct be caught or declared.
Exception Types:
There are two types of Exceptions,
1. Checked exceptions
2. Unchecked exceptions
Checked exceptions must be caught or rethrown. Unchecked exceptions do not have to be
caught.
User Defined Exceptions:
A user defined exception class can be created by extending the Exception class.
When that exception situation occurs, an object of this exception class can be created and
thrown.
java.io.File class
This class supports a platform-independent definition of file and directory names.
It also provides methods to list the files in a directory, to check the existence,
readability, writeability, type, size, and modification time of files and directories, to
make new directories, to rename files and directories, and to delete files and
directories.
Constructors :
public File(String path);
public File(String path, String name);
public File(File dir, String name);
Methods
▪ boolean canRead()- Returns True if the file is readable.
▪ boolean canWrite()- Returns True if the file is writeable.
▪ String getName()- Returns the name of the File with any directory names omitted.
▪ boolean exists()- Returns true if file exists
▪ String getAbsolutePath()- Returns the complete filename.
Directories
A directory is a File that contains a list of other files & directories. When you create a File
object and it is a directory, the isDirectory() method will return true. In this case list method
can be used to extract the list of other files & directories inside.
The forms of list() method is
public String[ ] list()
public String[ ] list(FilenameFilter filter)
Streams
A stream is a sequence of bytes. When writing data to a stream, the stream is called an output
stream. When reading data from a stream, the stream is called an input stream. If a stream has
a buffer in memory, it is a buffered stream. Binary Streams contain binary data. Character
Streams have character data and are used for storing and retrieving text.
The two main types of Streams are ByteStream and CharacterStream
1. ByteStrem -i)ByteStrea ii)ByteStrea
2.CharacterStrea – i)Reader ii)Writer
b. OutputStream Methods-
1.void close() - to close the OutputStream
2. void write (int b) - Writes a single byte to an output stream.
3. void write(byte buffer[ ]) - Writes a complete array of bytes to an output stream.
4.void write (byte buffer[ ], int offset, int numbytes) - Writes a sub range of numbytes
bytes from the array buffer, beginning at buffer[offset].
5. void flush() - clears the buffer.
CharacterStream Classes
Reader :
Reader is an abstract class that defines Java’s method of streaming character input.
All methods in this class will throw an IOException.
Methods in this class
1. int read () - Returns an integer representation of next available character from
invoking stream. -1 is returned at the stream end.
2. int read (char buffer[ ]) - Read up to buffer.length chacters to buffer & returns actual
number of characters that are successfully read. At the end returns –1.
3. int read(char buffer[ ], int offset, int numchars) - Attempts to read up to numchars
into buffer starting at buffer[offset]. Returns actual number of characters that are
read. At the end returns –1.
4. void close() - to close the input stream.
5. void mark(int numchars) - places a mark at current point in input stream & remain
valid till number of characters are read.
6. void reset() - Resets pointer to previously set mark/ goes back to stream beginning.
7. long skip(long numchars) - skips number of characters.
8. int available() - Returns number of bytes currently available for reading.
Writer :
Is an abstract class that defines streaming character output. All the methods in this
class returns a void value & throws an IOException.
Methods in this class-
1. void close() - to close the OutputStream
2. void write (int ch) - Writes a single character to an output stream.
3. void write(char buffer[ ]) - Writes a complete array of characters to an output stream.
4. void write (char buffer[ ], int offset, int numchars) - Writes a sub range of numchars from
the array buffer, beginning at buffer[offset].
5. void write(String str) - Writes str to output stream.
6. void write(String str, int offset, int numchars) - Writes a subrange of numchars from
string beginning at offset.
7. void flush() - clears the buffer
Methods :
1. position – Returns the current position
2. position(long) – Sets the position
3. read(ByteBuffer) – Reads bytes into the buffer from the stream
4. write(ByteBffer) – Writes bytes from the buffer to the stream
5. truncate(long) – Truncates the file (or other entity) connected to the stream
Assignment 5
Ready Reference
Graphical User Interface elements are implemented in two java packages – AWT and Swing.
Swing is the newer package and swing classes are based on AWT classes.
Swing Architecture:
The design of the Swing component classes is based on the Model-View-Controller
architecture, or MVC.
1. The model stores the data.
2. The view creates the visual representation from the data in the model.
3. The controller deals with user interaction and modifies the model and/or the
view.
Swing Classes:
The following table lists some important Swing classes and their description.
Layout Manager
The job of a layout manager is to arrange components on a container. Each container has a
layout manager associated with it. To change the layout manager for a container, use the
setLayout() method.
Syntax : setLayout(LayoutManager obj)
Important Containers:
1.JFrame
This is a top-level container which can hold components and containers like panels.
Constructors
JFrame()
JFrame(String title)
Important Methods
setSize(int width, int height) - Specifies size of the frame in pixels.
setLocation(int x, int y) - Specifies upper left corner
setVisible(boolean visible) -Set true to display the frame
setTitle(String title) - Sets the frame title
setDefaultCloseOperation(int mode) -Specifies the operation when frame is closed.
2.JPanel -
This is a middle-level container which can hold components and can be added to other
containers like frame and panels.
Constructors
public javax.swing.JPanel(java.awt.LayoutManager, boolean);
public javax.swing.JPanel(java.awt.LayoutManager);
public javax.swing.JPanel(boolean);
public javax.swing.Jpanel();
Important Components :
1. Label :
With the JLabel class, you can display unselectable text and images.
Constructors-
JLabel(Icon i)
JLabel(Icon I , int n)
JLabel(String s)
JLabel(String s, Icon i, int n)
JLabel(String s, int n)
Jlabel()
The int argument specifies the horizontal alignment of the label's contents within its
drawing area; defined in the SwingConstants interface (which JLabel implements):
LEFT (default), CENTER, RIGHT, LEADING, or TRAILING.
2. Button :
A Swing button can display both text and an image. The underlined letter in
each button's text shows the mnemonic which is the keyboard alternative.
Constructors-
JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)
3. Check boxes :
Class – JcheckBox
Constructors-
JCheckBox(Icon i)
JCheckBox(Icon i,booean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon I, boolean state)
4. Radio Buttons :
Class- JradioButton
Constructors-
JRadioButton (String s)
JRadioButton(String s, boolean state)
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
JradioButton()
5. Combo Boxes :
Class- JComboBox
Constructors-
JcomboBox()
6. List
Constructor-
Jlist(ListModel)
7. Text:
classes All text related classes are inherited from JTextComponent class
a. JTextField
Creates a text field. The int argument specifies the desired width in columns.
The String argument contains the field's initial text. The Document argument
provides a custom document for the field.
Constructors-
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
JTextField(Document, String, int)
b. JPasswordField
Creates a password field. When present, the int argument specifies the
desired width in columns. The String argument contains the field's initial
text. The Document argument provides a custom document for the field.
Constructors-
JPasswordField()
JPasswordField(String)
JPasswordField(String, int)
JPasswordField(int)
JPasswordField(Document, String, int)
c. JTextArea
Represents a text area which can hold multiple lines of text
Constructors-
JTextArea (int row, int cols)
JTextArea (String s, int row, int cols)
Methods-
void setColumns (int cols)
void setRows (int rows)
void append(String s)
void setLineWrap (boolean)
8.Dialog Boxes:
Types-
1. Modal- wont let the user interact with the remaining windows of
application
until first deals with it. Ex- when user wants to read a file, user must
specify file name before prg. can begin read operation.
2. Modeless dialog box- Lets the user enters information in both, the dialog
box & remainder of application ex- toolbar.
Swing has a JOptionPane class, that lets you put a simple dialog box.
Low-Level Events:
Low-level events represent direct communication from user.
A low level event is a key press or a key release, a mouse click, drag, move or
release, and so on.
2. High-Level Events:
High-level (also called as semantic events) events encapsulate
thePage 59 of 70meaning of a user interface component. These include following events.
Adapter Classes:
All high level listeners contain only one method to handle the high-level events. But most
low level event listeners are designed to listen to multiple event subtypes (i.e. the
MouseListener listens to mouse-down, mouse-up, mouse-enter, etc.). AWT provides a set of
abstract “adapter” classes, which implements each listener interface. These allow programs to
easily subclass the Adapters and override only the methods representing event types they are
interested in, instead of implementing all methods in listener interfaces.