Beruflich Dokumente
Kultur Dokumente
Java
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Console input in Java :Java provides a package named IO which contains two important classes
named BufferedReader and InputStreamReader which is responsible
to accept input from standard input device I,e; keyboard.
In order to create object of these classes to read date from console input
iopackage must required to be explicitly import in the user program.
import java.io.*;
BufferedReader
<object>=new
InputStreamReader(System.in));
BufferedReader(new
Step 2:- Read the data in the local variables using BufferedReader
method readLine() in the following format.
<Variable>=<BufferedReader Object>.readLine();
Note:- readLine() converts the data in to the String. String in java is an
object of class Strings
-: The Simple Data Types :Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers.
Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false
values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers. Many
other computer languages, including C/C++, support both signed and unsigned integers.
However, Javas designers felt that unsigned integers were unnecessary. Specifically,
they felt that the concept of unsigned was used mostly to specify the behavior of the highorder bit, which defined the sign of an int when expressed as a number.
Name
Width
Range
Long
64
9,223,372,036,854,775,808
int
32
2,147,483,648
short
16
byte
to 9,223,372,036,854,775,807
to
2,147,483,647
32,768
to
32,767
128
to
127
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square root, or
transcendentals such as sine and cosine, result in a value whose precision requires a floatingpoint type.
Name
Width in Bits
Approximate Range
Double
64
4.9e324 to 1.8e+308
float
32
1.4e045 to 3.4e+038
Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware:
char in Java is not the same as char in C or C++. In C/C++, char is an integer type that is 8
bits wide. This is not the case in Java. Instead, Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all of the characters
found in all human languages
Here is a program that demonstrates char variables:
Booleans
Java has a simple type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, such as a <
b. boolean is also the type required by the conditional expressions that govern the control
statements such as if and for.
Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Javas atomic types, or the name of a class or interface. The identifier is the
name of the variable. You can initialize the variable by specifying an equal sign and a value
to declare more than one variable of the specified type, use a comma-separated list.
Here are several examples of variable declarations of various types. Note that some include
an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
-:Control Statement:Java supports three type of control statement for controlling the set of
statements. These are:
1. Selection Statement
2. Looping Statement
3. Jump Statement
1.Selection Statement :Java supports two type of selection statement, if and switch. These
statements allow controlling the flow of our programs execution based
upon conditions known only during run time.
if construct:-
(a)
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
(b)
Nested if construct:-
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
else
{
<Set of statements>;
}
}
else
{
<Set of statements>;
if(<Boolean expression>)
{
<Set of Statements>;
}
}
(c)
If-else-if construct:-
Syntax
if(<Boolean expression>)
{
<Set of Statements>;
Switch case:-
Syntax
switch (choice)
{
case 1:
<Set Of Statements>;
break;
case 2:
<Set Of Statements>;
break;
case 3:
<Set Of Statements>;
break;
default:
<Set Of Statements>;
}
Note: Only constraint numeric and character value are allowed with case
statements.
Variable or expression is allowed within the parenthesis of switch case.
Default is optional and can be used if required.
Break within switch can be used to break the control of execution and
continue on resume it just very next close curly braces encountered.
The switch case is internally working on numeric constant.
Maximum of 33 switch structure can be a target of another switch.
Example
import java.io.*;
public class SwitchCase
{
public static void main(String arg[])throws IOException
{
BufferedReader
obj=new
BuggeredReader(new
InputStreamReader(System.in));
int dno;
System.out.println(Enter day Number);
dno=Integer.valueOf(obj.readLine()).intValue();
switch(dno)
{
case 1:
System.out.println(SunDay);
break;
case 2:
System.out.println(MonDay);
break;
case 3:
System.out.println(TuesDay);
break;
case 4:
System.out.println(WedDay);
break;
..
case 7:
System.out.println(SaturDay);
10
break;
default :
System.out.println(Invalid Day Number);
break;
}
}
}
2.Looping Statement :-
Syntax
while (expression)
{
<Set of statement(s)>;
< Increment /Decrement>;
}
NOTE:
11
DoWhile loop:In some conditions in java, you need to run some statements and
processes once at least. For that you have to use the do while loop in after
that check the condition then we use the do-while loop statement. dowhile loop is same as the while loop statement but while loop checks the
certain condition is first and if condition is true then statements or
processes are executed otherwise all the statements written under the
while loop is ignored by the interpreter but do - while loop executes all the
statements first at once and then check the condition if the condition is
true then all the statements are also executed in second times otherwise
second times ignored all the statements.
Syntax
do
{
<Set of statement(s)>;
< Increment /Decrement>;
}while(condition);
NOTE:
For loop:The for statement provides a compact way to iterate over a range of
values. Programmers often refer to it as the "for loop" because of the way in which it
repeatedly loops until a particular condition is satisfied.
Syntax
for (initialization; termination; increment)
{
<Set of statement(s)>;
}
NOTE:-
12
The initialization expression initializes the loop; it's executed once, as the loop begins.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
Example
public class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}
}
3.Jump Statement :Java support four jump statements; break, continue, return an exit(). These
statements transfer control to another part of program.
Break:
The break statement is used in many programming languages such as c,
c++, java etc. Sometimes we need to exit from a loop before the
completion of the loop then we use break statement and exit from the loop
and loop is terminated. The break statement is used in while loop, do while loop, for loop and also used in the switch statement.
Break statement is used in java for jump the control very next close curly
braces. And execute continue the program.
Syntax
break;
13
Continue:
The continue statement is used in many programming languages such as
C, C++, java etc. Sometimes we do not need to execute some statements
under the loop then we use the continue statement that stops the normal
flow of the control and control returns to the loop without executing the
statements written after the continue statement. There is the difference
between break and continue statement that the break statement exit
control from the loop but continue statement keeps continuity in loop
without executing the statement written after the continue statement
according to the conditions.
Syntax
continue;
Return :
The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method. As
such, it is categorized as a jump statement. A brief look at return is
presented here.
At any time in a method the return statement can be used to cause
execution to branch back to the caller of the method. Thus, the return
statement immediately terminates the method in which it is executed.
Syntax
return;
or
return(var/const/expression);
exit() :
exit() is a control statement. Which is used to exit from JVM(Java Virtual
Machine). It is a method of System class of Java.lang package.
Syntax
System.exit(int const.);
14
15
Java Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, .., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. .
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
dataType[ ] arrayRefVar;
Example: The following code snippets are examples of this syntax:
double[] myList;
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar. Declaring
an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
dataType[ ] arrayRefVar =new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[ ] arrayRefVar ={value0, value1,..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[ ] myList =new double[10];
16
-: Class & Object :Class:A class defines the behaviors of an object. A class is a user-defined
data type with a template that serves to define its properties. Once the
class type has been defined we can create variables of those types using
declarations that are similar to the basic type declarations. In java these
variables are termed as instances of classes which are the actual objects.
The basic form of a class definitionis:A class has data members (Attributes) and member functions
(methods). The data members and methods of a class body,in java braces
({ }) are marks the beginning and end of the methods or class. Braces are
also used to delimit blocks of object in loops and iterative statements.
17
}
}
Note:1) A class name is mandatory and must be given while declaring a class. The
class name is referred to the class and to create instance of the class.
2) The class keyword is used to create class.
3) The access specifier and modifier is optional and are covered later in this
section.
Step 1.
At first allocate object reference variable in the following format.
<Object
type/Class
name>Object_refference_variable1,
Object_refference_variable2,..;
Step2.
Finally new operator must be used in the following format to
physically allocated the object of define type and return the reference to
the object reference variable.
Object_refference_variable = new <Object type/Class name>;
18
Object_refference_variable=
new
Example
public class Cube1
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;
19
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
public static void main(String[] args)
{
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println(Volume
cubeObj1.getVolume());
of
Cube1
is
System.out.println(Volume
cubeObj2.getVolume());
of
Cube1
is
}
}
Rules for a constructor:1. A constructor has the same name as that of the class for which it is declare
since called automatically when an object is created.
2. A constructor does not have return type. As we do not call the constructor
explicitly. We can not use the return value anyway.
3. Basically java support two type of constructor. I,e:
Default constructor
Parameterized constructor
20
Default constructor
If you don't define a constructor for a class, a default
parameterless constructor is automatically created by the compiler. The
default constructor calls the default parent constructor (super()) and
initializes all instance variables to default value (zero for numeric types,
null for object references, and false for booleans).
Example
public class Cube1
{
int length;
int breadth;
int height;
public int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;
breadth = 10;
height = 10;
}
21
of
Cube1
is
}
}
Parameterized constructor
At the time of creating object(instance) we will passed
the argument/parameter. In that condition the parameterized constructor
will be called for passing arguments.
Notes:1) Subclass can only inherit public and protected members but not private
members.
22
2) You can only inherit from single class. (Single inheritance).That is means
there is no multiple inheritance in Java. But as a solution to the multiple
inheritance java supported class types called interfaces.
Example
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
23
The inherited fields can be used directly, just like any other fields.
You can declare a field in the subclass with the same name as the one in
the superclass, thus hiding it (not recommended).
You can declare new fields in the subclass that are not in the superclass.
24
You can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.
You can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
You can declare new methods in the subclass that are not in the
superclass.
You can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
1)
Single Inheritance:-
25
there is only a sub class and it's parent class. It is also called single
inheritance or one level inheritance.
Simple Inheritance
2)
Multilevel Inheritance:-
Multilevel Inheritance
Multiple Inheritances
The mechanism of inheriting the features of more than one base class into
a single class is known as multiple inheritances. Java does not support
26
27
Now you can refer to the Button class by its simple name.
Buttonbtn1 = new Button (Button1);
This approach works well if you use just a few members from the awt
package. But if you use many types from a package, you should import the
entire package.
The asterisk in the import statement can be used only to specify all the
classes within a package, as shown here. It cannot be used to match a
subset of the classes in a package. For example, the following does not
match all the classes in the awt package that begin with A.
import awt.A*;
28
Creating a Package
To create a package, you choose a name for the package and put a
package statement with that name at the top of every source file that
contains the types (classes and interfaces) that you want to include in the
package.
The package statement (for example, package graphics;) must be the first
line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.
Note: If you put multiple types in a single source file, only one can be
public, and it must have the same name as the source file. For example,
you can define public class Circle in the file Circle.java, define public
interface Draggable in the file Draggable.java, define public enum Day in
the file Day.java, and so forth.
29
You can include non-public types in the same file as a public type (this is
strongly discouraged, unless the non-public types are small and closely
related to the public type), but only the public type will be accessible from
outside of the package. All the top-level, non-public types will be package
private.
If you put the graphics interface and classes listed in the preceding section
in a package called graphics, you would need six source files, like this:
AWT
The Abstract Window Toolkit (AWT) was introduced in Chapter 19 because
it provides support for applets. This chapter begins its in-depth
examination. The AWT contains numerous classes and methods that allow
you to create and manage windows. A full description of the AWT would
easily fill an entire book.
Therefore, it is not possible to describe in detail every method, instance
variable, or class contained in the AWT. However, this and the following
two chapters explain the techniques needed to effectively use the AWT
when creating your own applets or stand-alone programs. From there, you
will be able to explore other parts of the AWT on your own.
In this chapter, you will learn how to create and manage windows, manage
fonts, output text, and utilize graphics. Chapter 22 describes the various
controls, such as scroll bars and push buttons, supported by the AWT. It
also explains further aspects of Javas event-handling mechanism. Chapter
23 examines the AWTs imaging subsystem and animation.
Although the main purpose of the AWT is to support applet windows, it can
also be used to create stand-alone windows that run in a GUI environment,
such as Windows. Most of the examples are contained in applets, so to run
them, you need to use an applet viewer or a Java-compatible Web browser.
Class
Description
AWTEvent
AWTEventMulticaster
BorderLayout
use five
30
components
Button
Canvas
CardLayout
The card layout manager. Card layouts
emulate
index cards. Only the one on top is showing.
Checkbox
CheckboxGroup
CheckboxMenuItem
Choice
Creates a pop-up list.
Color Manages colors in a portable, platform-independent
fashion.
Component
components.
Container
components.
Cursor
Dialog
Dimension
Specifies the dimensions of an object. The
width is
stored in width, and the height is stored in height.
Event
Encapsulates events.
EventQueue
Queues events.
FileDialog
selected.
FlowLayout
The flow
positions
Components left to right, top to bottom.
Font
FontMetrics
font.
layout
manager.
Flow
layout
31
Graphics
Encapsulates the graphics context. This context is
used by the various output methods to display
output in a window.
GraphicsDevice
or printer.
SWINGS
Swing is a set of classes that provides more powerful and flexible
components than are possible with the AWT. In addition to the familiar
components, such as buttons, check boxes, and labels, Swing supplies
several exciting additions, including tabbed panes, scroll panes, trees, and
tables. Even familiar components such as buttons have more capabilities
in Swing. For example, a button may have both an image and a text string
associated with it. Also, the image can be changed as the state of the
button changes.
Unlike AWT components, Swing components are not implemented by
platform-specific code. Instead, they are written entirely in Java and,
therefore, are platform-independent. The term lightweight is used to
describe such elements. The number of classes and interfaces in the Swing
packages is substantial, and this
chapter provides an overview of just a few. Swing is an area that you will
want to explore further on your own. The Swing component classes that
are used in this book are shown here:
Class Description
AbstractButton -
ButtonGroup
buttons.
ImageIcon
- Encapsulates an icon.
JApplet
JButton
JCheckBox
32
JComboBox
drop-down
JLabel
JRadioButton
JScrollPane
JTabbedPane
JTable
JTextField
JTree
DEVELOPMENT
USING JAVA
JApplet
Event-Driven Programs
Your actions when youre using the GUI for a window-based program or an
appletclicking a menu item or a button, moving the mouse, and so on
are first recognized by the operating system. For each action, the
operating system determines which of the programs currently running on
33
your computer should know about it and passes the action on to that
program. When you click a mouse button, its the operating system that
registers this and notes the position of the mouse cursor on the screen. It
then decides which application controls the window where the cursor was
when you pressed the button, and communicates the mouse button-press
to that program. The signals that a program receives from the operating
system as a result of your actions are called events. The basic idea of how
actions and events are communicated to your program code.
A program is not obliged to respond to any particular event. If you just
move the mouse, for example, the program need not invoke any code to
react to that. If it doesnt, the event is quietly disposed of. Each event that
the program does recognize is associated with one or more methods, and
when the event occurswhen you click a menu item, for examplethe
appropriate methods will be called automatically.
A window-based program is called an event-driven program because
the sequence of events created as a result of your interaction with the GUI
drives and determines what happens in the program.
Event
Class Description
ActionEvent
Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
AdjustmentEvent
ComponentEvent
resized,
or becomes visible.
ContainerEvent
removed
from a container.
FocusEvent
keyboard focus.
InputEvent
classes.
ItemEvent
Generated when a check box or list item is clicked;
also
occurs when a choice selection is made or a checkable
menu item is selected or deselected.
KeyEvent
34
MouseEvent
Generated when the mouse is dragged, moved,
clicked,
pressed, or released; also generated when the mouse enters
or exits a component.
MouseWheelEvent
(Added by
Java 2, version 1.4)
TextEvent
changed.
35
window
is
activated,
closed,