Java Content2
Java Content2
OR
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
List
5
The List component presents the user with a scrolling list of text items.
TextField
6
A TextField object is a text component that allows for the editing of a single line of text.
TextArea
7 A TextArea object is a text component that allows for the editing of a multiple lines of
text.
Choice
8 A Choice control is used to show pop up menu of choices. Selected choice is shown on
the top of the menu.
Canvas
9 A Canvas control represents a rectangular area where application can draw something or
can receive inputs created by user.
Image
10
An Image control is superclass for all image classes representing graphical images.
ScrollBar
11 A Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Dialog
12 A Dialog control represents a top-level window with a title and a border used to take some
form of input from the user.
FileDialog
13
A FileDialog control represents a dialog window from which the user can select a file.
WINDOWS FUNDAMENTAL
The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level.
The two most common windows are those derived from Panel, which is used by
applets, and those derived from Frame, which creates a standard window.
Much of the functionality of these windows is derived from their parent classes.
Component
At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component.
All user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component.
It defines over a hundred public methods that are responsible for managing events,
such as mouse and keyboard input, positioning and sizing the window, and repainting.
A Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
Container
Panel
Window
Frame
Canvas
It is not part of the hierarchy for applet or frame windows. Canvas encapsulates a
blank window upon which you can draw.
After the applet, the type of window you will most often create is derived from
Frame.
You will use it to create child windows within applets, and top-level or child
windows
for applications. As mentioned, it creates a standard-style window.
Frame()
Frame(Stringtitle)
The first form
Creates a standard window that does not contain a title.
The second form Creates a window with the title specified by title. Notice that you cannot
specify the dimensions of the window. Instead, you must set the size of the window after it
has been created.There are several methods you will use when working with Frame windows.
Setting the Window’s Dimensions
The new size of the window is specified by newWidth and newHeight, or by the width
and height fields of the Dimension object passed in newSize.
The dimensions are specified in terms of pixels.
The getSize( ) method is used to obtain the current size of a window. Its signature
is shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width and
height fields of a Dimension object.
After a frame window has been created, it will not be visible until you call
setVisible( ). Its signature is shown here:
The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Window’s Title
You can change the title in a frame window using setTitle( ), which has this
general form:
When using a frame window, your program must remove that window from the
The coordinate system for the Java graphing window positions (0,0) in the upper left hand
corner. The grid is then numbered in a positive direction on the x-axis (horizontally to the
right) and in a positive direction on the y-axis (vertically going down).
We will now be using the methods contained within the Graphics Class in the package
java.awt.
g.drawRoundRect(35,45,25,35,10,10);
drawRoundRect(int x, int y, int width, int
Round Edge length, int arcWidth, int arcHeight)
Rectangle Used to draw a rounded edged rectangle.
The amount of rounding is controlled by
arcWidth and arcHeight.
g.drawOval(25, 35, 25, 35);
g.drawOval(25, 35, 25, 25); → circle
drawOval(int x, int y, int width, int length)
Oval / Circle
Used to draw an oval inside an imaginary
rectangle whose upper left corner is at (x,y).
To draw a circle keep the width and length
the same.
SAMPLE EXAMPLE
Drawing Rectangles
Type in the following program code and save it as a text file named "Rectangles.java". There
are two important parts to the name of this file. The first part (the "Rectangles" part) is the
name of the class which is saved in this file. The suffix (the "java" part) tells the computer
that yes, this file does contain Java code.
import java.applet.Applet;
import java.awt.*;
</applet>
</html>
Run this program.
Look at the applet that the code produced. In line 2, was the "70" used for the x position, the
y position, the height or the width of the rectangle?
How about the other values?
(Hint: pixel (0,0) is in the top-left corner of the window.)
Below is a picture of the rectangles. Match each rectangle to its line number by writing that
number beside the rectangle.
Type in the following program code and save it as a text file named "Ovals.java".
import java.applet.Applet;
import java.awt.*;
PAINT MODE
Syntax:
Syntax:
void setPaintMode()
Eg:-
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
{
int x=100,y=50;
{
g.setXORMode(Color.green);
g.drawLine(chsx-50,chsy,chsx+10,chsy);
g.setPaintMode();
}
}
FONTS
A font represents a combination of a font name (like Monospaced), font style (like bold) and
font size (like 20)
The Font constructor takes three parameters to create a Font object.
Syntax:
Font f1 = new Font(String fontName, int fontStyle, int fontSize);
Example:
Font newFont = new Font("Serif", Font.BOLD, 24);.
To give the font style as an integer value, the Font class comes with 3 symbolic constants.
public final static int PLAIN = 0;
AWT CONTROLS:
Controls Are components that allow a user to interact with your application in various
ways.
LayoutManager automatically positions within a container.
The appearance of a window is a combination of such controls and Layoutmanagers.
Control Fundamentals
Labels
Push Buttons
Check Boxes
Choice Lists
Lists
Scroll Bars
Text Editing
Create an instance of desired control and then add it to the window by calling add()
method.
Syntax:-
Component add(Component obj)
We can also remove our control from window by calling remove() method.
Syntax:-
Void remove(Component obj)
LABEL
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.LABEL
A label displays a single line of read-only text. However the text can be changed by the
application programmer but cannot be changed by the end user in any way.
Label()
1
Constructs an empty label.
Label(Stringtext)
2
Constructs a new label with the specified string of text, left justified.
Label(Stringtext,intalignment)
3
Constructs a new label that presents the specified string of text with the specified alignment.
Following are the fields for java.awt.Component class:
static int CENTER -- Indicates that the label should be centered.
static int LEFT -- Indicates that the label should be left justified.
static int RIGHT -- Indicates that the label should be right justified.
METHODS
addNotify
public void addNotify()
Creates the peer for this label. The peer allows us to modify the appearance of the
label without changing its functionality.
getAlignment
public int getAlignment()
Gets the current alignment of this label. Possible values are Label.LEFT,
Label.RIGHT, and Label.CENTER.
setAlignment
public synchronized void setAlignment(int alignment)
Sets the alignment for this label to the specified alignment. Possible values are
Label.LEFT, Label.RIGHT, and Label.CENTER.
Parameters:
alignment - the alignment to be set.
Throws: IllegalArgumentException
if an improper value for alignment is given.
getText
public String getText()
Gets the text of this label.
Returns:
the text of this label.
setText
public synchronized void setText(String text)
Sets the text for this label to the specified text.
Parameters:
text - the text that this label presents.
paramString
protected String paramString()
Returns the parameter string representing the state of this label. This string is useful
for debugging.
Returns:
the parameter string of this label.
BUTTON:
The java.awt package comes with many GUI components of which Button is the most
important and most frequently used. A button functionality (what for it is) can be known by
its label like OK or Cancel etc. A mouse click on the button generates an action. –
Any GUI component with event handling can be broadly divided into 8 steps.
1. Import java.awt and java.awt.event packages
2. Extending frame or applet and implementing appropriate listener interface that can
handle the events of the component successfully.
3. Set the layout.
4. Create components
5. Register or link the component with the listener interface
6. Beautification of the components (optional)
7. Adding the components to the frame or applet
8. Override all the abstract methods of the listener interface
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Button
Button()
Constructs a Button with no label.
Button(String)
Constructs a Button with the specified label.
METHODS
addActionListener(ActionListener)
Adds the specified action listener to receive action events from this button.
addNotify()
Creates the peer of the button.
getActionCommand()
Returns the command name of the action event fired by this button.
getLabel()
Gets the label of this button.
paramString()
Returns the parameter string representing the state of this button.
processActionEvent(ActionEvent)
Processes action events occurring on this button by dispatching them to any registered
ActionListener objects.
processEvent(AWTEvent)
Processes events on this button.
removeActionListener(ActionListener)
Removes the specified action listener so that it no longer receives action events from
this button.
setActionCommand(String)
Sets the command name for the action event fired by this button.
setLabel(String)
Sets the button's label to be the specified string.
MENUS:
A menu is a group of commands located in a menubar. A toolbar has buttons with some
common commands in the application.
AccessibleContextgetAccessibleContext()
6
Gets the AccessibleContext associated with this Menu.
MenuItemgetItem(intindex)
7
Gets the item located at the specified index of this menu.
intgetItemCount()
8
Get the number of items in this menu.
voidinsert(MenuItemmenuitem,intindex)
9
Inserts a menu item into this menu at the specified position.
voidinsert(Stringlabel,intindex)
10
Inserts a menu item with the specified label into this menu at the specified position.
voidinsertSeparator(intindex)
11
Inserts a separator at the specified position
booleanisTearOff()
12
Indicates whether this menu is a tear-off menu.
StringparamString()
13
Returns a string representing the state of this Menu.
voidremove(intindex)
14
Removes the menu item at the specified index from this menu.
voidremove(MenuComponentitem)
15
Removes the specified menu item from this menu.
voidremoveAll()
16
Removes all items from this menu.
voidremoveNotify()
17
Removes the menu's peer.
AdjustmentListener
8
This interface is used for receiving the adjusmtent events.
ContainerListener
9
This interface is used for receiving the container events.
MouseMotionListener
10
This interface is used for receiving the mouse motion events.
FocusListener
11
This interface is used for receiving the focus events.
APPLET
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
APPLET FUNDAMENTALS
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following:
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define
main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
Life Cycle of an Applet:
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
Lifecycle of an Applet:
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
Four methods in the Applet class give you the framework on which you build any serious
applet:
init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having
gone off to other pages.
stop: This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
For example:
<applet code="mypackage.subpackage.TestApplet.class"
width="320" height="120"
The HTML <applet> tag specifies an applet. It is used for embedding a Java applet within an
HTML document. It is not supported in HTML5.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML applet Tag</title>
</head>
<body>
<applet code="newClass.class" width="300" height="200">
</applet>
</body>
</html>
Here is the newClass.java file:
import java.applet.*;
import java.awt.*;
ALT = alternateText
This OPTIONAL attribute specifies any text that should be displayed if the browser
understands the APPLET tag but can't run Java applets.
NAME = appletInstanceName
This OPTIONAL attribute specifies a name for the applet instance, which makes it
possible for applets on the same page to find (and communicate with) each other.
WIDTH = pixels HEIGHT = pixels
These REQUIRED attributes give the initial width and height (in pixels) of the applet
display area, not counting any windows or dialogs that the applet brings up.
ALIGN = alignment
This OPTIONAL attribute specifies the alignment of the applet. The possible values
of this attribute are the same as those for the IMG tag: left, right, top, texttop, middle,
absmiddle, baseline, bottom, absbottom.
VSPACE = pixels HSPACE = pixels
These OPTIONAL attributes specify the number of pixels above and below the applet
(VSPACE) and on each side of the applet (HSPACE). They're treated the same way
as the IMG tag's VSPACE and HSPACE attributes.
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value> . . .
This tag is the only way to specify an applet-specific attribute. Applets access their
attributes with the getParameter() method.
Unit - IV
Inheritance Basics – Using Super – Creating a Multilevel Hierarchy – When Constructors are
called – Method Overriding – Dynamic Method Dispatch – Using Abstract Classes – Using
final with Inheritance – The Object Class.
Packages – Access Protection – Importing Packages – Interfaces.
Inheritance Basics
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new
class is called a subclass.
SAMPLE PROGRAM:
class Employee
{
float salary=40000;
}
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Using Super
The super keyword in java is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
Usage of java super Keyword
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
super Usage:
1) super.<variable_name> refers to the variable of variable of parent class.
2) super() invokes the constructor of immediate parent class.
3) super.<method_name> refers to the method of parent class.
Problem without super keyword
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Test it Now :Output:100
In the above example Vehicle and Bike both class have a common property speed.
Instance variable of current class is refered by instance bydefault, but I have to refer
parent class instance variable that is why we use super keyword to distinguish
between parent class instance variable and current class instance variable.
Solution by super keyword
//example of super keyword
class Vehicle{
int speed=50;
}
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
Test it Now
Output:50
inheritance a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance a subclass is derived from a derived class. One class inherits only
single class. Therefore, in multilevel inheritance, every time ladder increases by one. The
lower most class will have the properties of all the super classes’.
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
Constructor
A java constructor has the same name as the name of the class to which it belongs.
Java constructors are the methods which are used to initialize objects.
Constructor method has the same name as that of class, they are called or invoked
when an object of class is created and can't be called explicitly.
Attributes of an object may be available when creating objects if no attribute is
available then default constructor is called, also some of the attributes may be known
initially. It is optional to write constructor method in a class but due to their utility
they are used.
Java provides a default constructor which takes no arguments and performs no special
actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass
constructor using the super() call. Constructor arguments provide you with a way to
provide parameters for the initialization of an object.
class Programming {
//constructor method
Programming() {
System.out.println("Constructor method called.");
}
public static void main(String[] args) {
Programming object = new Programming(); //creating object
}
}
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
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 of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
}
}
This would produce the following result:
Animals can move
Dogs can walk and run
upcasting:
When parent class reference variable refers to child class object ,it is called upcasting
class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
void callme() // override callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
void callme() // override callme()
{
System.out.println("Inside C's callme method");
}
}
ABSTRACT CLASS
An abstract class is a class that is declared abstract—it may or may not include abstract
methods.
Abstract classes cannot be instantiated, but they can be subclassed.
Abstract classes are classes that contain one or more abstract methods. An abstract
method is a method that is declared, but contains no implementation. Abstract classes
may not be instantiated, and require subclasses to provide implementations for the
abstract methods.
}
Abstract Methods
An abstract class can have abstract methods. You declare a method abstract by adding
the abstract keyword in front of the method declaration. Here is how that looks:
public abstract class MyAbstractClass {
Using final:
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no
value it is called blank final variable or uninitialized final variable.
It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static block
only.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Test it Now
Output:running...
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
Here meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result.
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede
the class declaration with final.
Declaring a class as final implicitly declares all of its methods as final, too. As you
might expect, it is illegal to declare a class as both abstract and final since an abstract
class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Class methods
S.N. Method & Description
protected Object clone()
1
This method creates and returns a copy of this object.
boolean equals(Object obj)
2
This method indicates whether some other object is "equal to" this one.
protected void finalize()
3 This method is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
Class<?> getClass()
4 This method returns the runtime class of this Object.
int hashCode()
5
This method returns a hash code value for the object.
void notify()
6
This method wakes up a single thread that is waiting on this object's monitor.
void notifyAll()
7
This method wakes up all threads that are waiting on this object's monitor.
String toString()
8
This method returns a string representation of the object.
void wait()
9 This method causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
void wait(long timeout)
This method causes the current thread to wait until either another thread invokes the
10
notify() method or the notifyAll() method for this object, or a specified amount of time
has elapsed.
void wait(long timeout, int nanos)
This method causes the current thread to wait until another thread invokes the notify()
11
method or the notifyAll() method for this object, or some other thread interrupts the
current thread, or a certain amount of real time has elapsed.
Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and
annotations easier, etc.
A Package can be defined as a grouping of related types(classes, interfaces,
enumerations and annotations ) providing access protection and name space
management.
Package = directory. Java classes can be grouped together in packages. A package
name is the same as the directory (folder) name which contains the .java files. You
declare packages when you define your Java program, and you name the packages
you want to use from other libraries in an import statement.
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
Package declaration
The first statement, other than comments, in a Java source file, must be the package
declaration.
Following the optional package declaration, you can have import statements, which
allow you to specify classes from other packages that can be referenced without
qualifying them with their package.
Default package.
All Java classes are in a directory, it's possible to omit the package declaration. For
small programs it's common to omit it, in which case Java creates what it calls a
default package. Sun recommends that you do not use default packages.
Package declaration syntax
The statement order is as follows. Comments can go anywhere.
1. Package statment (optional).
2. Imports (optional).
3. Class or interface definitions.
Access protection:
Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
Visible to the package. the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Private Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed within
the declared class itself.
Public Access Modifier - public:
A class, method, constructor, interface etc declared public can be accessed from any other
class.
Protected Access Modifier - protected:
Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed by the
file system. Finally, you specify either an explicit classname or a star (*), which indicates that
the Java compiler should import the entire package.
This code fragment shows both forms in use:
importjava.util.Date;
import java.io.*;
Unit - II
Operators – Arithmetic operators – Bitwise operators – Relational operators – Relational
operators – Boolean operators – Logical operators – Assignment operators? Operators -
Control
statement – Selection statements – if, switch, iteration statements – while, do while, for,
nested
loops – jump statements, break, continue, return statements.
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
The Arithmetic Operators:
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication,
division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and
negation.
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Show Examples
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
Subtraction - Subtracts right hand operand from left hand A - B will give -
-
operand 10
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand and
% B % A will give 0
returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}
Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b =
13; now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:
Show Examples
Operator Description Example
(A & B) will give
Binary AND Operator copies a bit to the result if it exists in
& 12 which is 0000
both operands.
1100
(A | B) will give
| Binary OR Operator copies a bit if it exists in either operand. 61 which is 0011
1101
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one operand
^ 49 which is 0011
but not both.
0001
(~A ) will give -61
which is 1100
Binary Ones Complement Operator is unary and has the effect 0011 in 2's
~
of 'flipping' bits. complement form
due to a signed
binary number.
A << 2 will give
Binary Left Shift Operator. The left operands value is moved
<< 240 which is 1111
left by the number of bits specified by the right operand.
0000
Binary Right Shift Operator. The left operands value is moved A >> 2 will give
>>
right by the number of bits specified by the right operand. 15 which is 1111
Shift right zero fill operator. The left operands value is moved A >>>2 will give
>>> right by the number of bits specified by the right operand and 15 which is 0000
shifted values are filled up with zeros. 1111
public LogicalOperatorsDemo() {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x & y));
System.out.println("x && y : " + (x && y));
System.out.println("x | y : " + (x | y));
System.out.println("x || y: " + (x || y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("!x : " + (!x));
}
public static void main(String args[]) {
new LogicalOperatorsDemo();
}
}
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
Called Logical AND operator. If both the operands are non- (A && B) is
&&
zero, then the condition becomes true. false.
Called Logical OR Operator. If any of the two operands are
|| (A || B) is true.
non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state
!(A && B) is
! of its operand. If a condition is true then Logical NOT operator
true.
will make false.
The Assignment Operators:
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo {
public AssignmentOperatorsDemo() {
// Assigning Primitive Values
int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : " + j);
System.out.println("k is : " + k);
// Assigning References
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
i1 = i2;
System.out.println("i1 is : " + i1);
Control statement
Java Control statements control the order of execution in a java program, based on data
values and conditional logic. There are three main categories of control flow statements;
· Selection statements: if, if-else and switch.
· Loop statements: while, do-while and for.
· Transfer statements: break, continue, return, try-catch-finally and assert.
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true.
If the value is false, then the if block is skipped and execution continues with the rest of the
program.
You can either have a single statement or a block of code within an if statement.
Note that the conditional expression must be a Boolean expression.
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
OutPut
$ java Test
Well done
Your grade is a C
$
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
You can implement an infinite loop using the while statement as follows:
while (true)
{
// your code goes here
}
The Java programming language also provides a do-while statement, which can be expressed
as follows:
Do
{
statement(s)
} while (expression);
The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once, as shown in the following DoWhileDemo program:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
The for Statement
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. The general form of the for statement can be expressed as
follows:
for (initialization; termination;
increment) {
statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.
The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Nested Loops
Loop within another loop is nested loop
Example:
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
The break statement terminates the labeled statement; it does not transfer the flow of
control to the label.
Control flow is transferred to the statement immediately following the labeled
(terminated) statement.
The continue Statement
The continue statement skips the current iteration of a for, while , or do-while loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates the
boolean expression that controls the loop.
A labeled continue statement skips the current iteration of an outer loop marked with
the given label
Continue statement is used when we want to skip the rest of the statement in the body
of the loop and continue with the next iteration of the loop.
There are two forms of continue statement in Java.
1. Unlabeled Continue Statement
2. Labeled Continue Statement
Unlabeled Continue Statement
This form of statement causes skips the current iteration of innermost for, while or do while
loop.
For example,
for(int var1 =0; var1 < 5 ; var1++)
{
for(int var2=0 ; var2 < 5 ; var2++)
{
if(var2 == 2)
continue;
System.out.println(“var1:” + var1 + “, var2:”+ var2);
}
}
In above example, when var2 becomes 2, the rest of the inner for loop body will be skipped.
Labeled Continue Statement
Labeled continue statement skips the current iteration of the loop marked with the specified
label. This form is used with nested loops.
For example,
Outer:
for(int var1 =0; var1 < 5 ; var1++)
{
Unit - I
Internet – Overview –Internet Protocols – Internet address – Internet access – Applications –
Future of Internet and intranet related Applications. – Basic concepts of OOP – benefits of
OOP
– Object Oriented applications of OOP – Data types, variables and arrays – Programs with
input,
numeric input – type conversion and casting.
Internet – Overview
The Internet is a collection of computers connected by network cables or through
satellite links. Rather than connecting every computer on the Internet with every other
computer, individual computers in an organization are normally connected in a local
area network (LAN). One node on this local area network is physically connected to
the Internet. So the Internet is a network of networks . There are millions of
computing devices that are connected to this network either permanently or for a short
duration. These devices run network applications that communicate through copper or
fiber optic cables, radio or satellite transmission. The communication is governed by
protocols established by an international body.
Internet Protocols
Among the most common Internet protocols are FTP (File Transfer Protocol), HTTP
(Hypertext Transfer Protocol), TCP/IP (Transfer Control Protocol/Internet
Protocol), and SMTP (Simple Mail Transfer Protocol). A uniform set of rules that
enable two devices to connect and transmit data to one another.
Short for Internet Protocol. IP specifies the format of packets, also called datagrams,
and the addressing scheme. Most networks combine IP with a higher-level protocol
called Transmission Control Protocol (TCP), which establishes a virtual connection
between a destination and a source.
IP by itself is something like the postal system. It allows you to address a package and
drop it in the system, but there's no direct link between you and the recipient. TCP/IP,
on the other hand, establishes a connection between two hosts so that they can send
messages back and forth for a period of time.
The current version of IP is IPv4. A new version, called IPv6 or IPng, is under
development.
IP address
An Internet address uniquely identifies a node on the Internet. Internet address may
also refer to the name or IP of a Web site (URL). The term Internet address can also
represent someone's e-mail address.
An Internet Protocol address (IP address) is a numerical label assigned to each
device (e.g., computer, printer) participating in a computer network that uses the
Internet Protocol for communication. An IP address serves two principal functions:
host or network interface identification and location addressing.
Internet access
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
What Is an Interface?
An interface is a contract between a class and the outside world. When a class implements an
interface, it promises to provide the behavior published by that interface. This section defines
a simple interface and explains the necessary changes for any class that implements it.
What Is a Package?
A package is a namespace for organizing classes and interfaces in a logical manner. Placing
your code into packages makes large software projects easier to manage. This section
explains why this is useful, and introduces you to the Application Programming Interface
(API) provided by the Java platform.
Data type
Variables are nothing but reserved memory locations to store values.
This means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory.
By assigning different data types to variables, you can store integers, decimals, or
characters in these variables.
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by
the language and named by a keyword. Let us now look into detail about the eight primitive
data types.
byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50
short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally
the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char:
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'
Reference Data Types:
Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that cannot
be changed. For example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Variable
A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.
You must declare all variables before they can be used.
The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
There are three kinds of variables in Java:
Local variables
Instance variables
Class/static variables
There are three kinds of variables.
instance variables Any method in the class definition can access these variables
parameter variables Only the method where the parameter appears can access these
variables. This is how information is passed to the object.
local variables Only the method where the parameter appears can access these
variables. These variables are used to store intermediate results.
Local variables:
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor or block.
Local variables are implemented at stack level internally.
There is no default value for local variables so local variables should be declared and
an initial value should be assigned before the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
Instance variables:
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However
visibility for subclasses can be given for these variables with the use of access
modifiers.
Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during
the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name inside the
class. However within static methods and different class ( when instance variables are
given accessibility) should be called using the fully qualified name .
ObjectReference.VariableName.
Example:
import java.io.*;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
The scope of a variable defines the section of the code in which the variable is visible.
As a general rule, variables that are defined within a block are not accessible outside that
block. The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables
when declaring it. Scope refers to the range of code where you can access a variable.
method body scope Variable is accessible in method body only (local variables,
parameters)
class definition scope Variable is accessible i class definition (instance variables)
Lifetime refers to the amount of time a variable (or object) exists. Since object variables are
both a box (holding a handle) and an object, the lifetimes may differ. An object variable
could disappear (for example, a local variable disappears once you exit the method where the
local variable is declared), yet the object still exists.
We can divide lifetime into categories too:
method body lifetime Exists on method body entry, disappears on method body exit.
(local variables, parameters)
class definition lifetime Exists as long as object is around (instance variables)
Arrays
Note:Program refer claswork note
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed. You
have seen an example of arrays already, in the main method of the "Hello World!"
application. This section discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its numerical
index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
or
Multidimensional Array
The element type followed by a pair of square brackets
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string "+s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer "+a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float "+b);
}
}
i = b;
System.out.println("b is " + b);
System.out.println("i is " + i);
}
}
The output:
b is 10
i is 10
Unit - III
Class fundamentals – Declaring Objects – Assigning Object Reference Variables –
Introducing
methods – Constructors – The this keyword – Garbage collection – The finalize () method.
Overloading Methods – Objects as Parameters – Arguments Passing – Returning Objects –
Recursion – Access Control – Static – Final – Arrays – Nested and Inner Classes – String
Class –
Command Line Arguments.
CLASS FUNDAMENTAL
The most important thing to understand about a class is that it defines a new data type.
Once defined, this new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class.
Because an object is an instance of a class, you will often see the two words object
and instance used interchangeably.
1. A class is declared by use of the class keyword.
2. The general form of a class definition is shownhere:
class classname {
type instance-variable1;
type instance-variable2;
// ..
type instance-variableN;
type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list) {
//body of method
}
//..
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined with a class are called instance variables.
The code is contained within methods. Collectively, the methods and variables
defined within a class are called members of the class.
In most classes, the instance variables are acted upon and accessed by the methods
defined for that class. Thus, it is the methods that determine how a class’ data can be used.
Variables defined within a class are called instance variables because each instance of
the class (that is, each object is separate and unique from the data for another.
All methods have the same general form as main (), which we have been using thus
far. However, most methods will not be specified as static or public.
Declaring objects
In object is created from a class. In Java, the new key word is used to create new objects.
There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Example of creating an object is given below:
public class Puppy{
class RectangleDemo {
public static void main(String args[]) {
r1.length = 10;
r2.length = 20;
}
}
Output :
C:Priteshjava>java RectangleDemo
Value of R1's Length : 20.0
Value of R2's Length : 20.0
class Rectangle {
double length;
double breadth;
class RectangleDemo {
public static void main(String args[]) {
r1.length = 10;
System.out.println("Before Function Length : " + r1.length);
r1.setLength(20);
System.out.println("After Function Length : " + r1.length);
}
}
Output :
C:Priteshjava>java RectangleDemo
Before Function Length : 10.0
After Function Length : 20.0
(OR)
class Test
{
double item1;
double item2;
double item3;
void value()
{
System.out.println(“value is”);
System.out.println( item1 + item2 + item3);
}
}
class Testdemo()
{
public static void main (String args[])
{
Test test1 = new test();
Test test2 = new test();
test1.item1 = 10;
test1.item2 = 20;
test1.item3 = 15;
test2.item1 = 3;
test2.item2 = 6;
test2.item3 = 9;
test1.value();
test2.value();
}
}
Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Class Student11{
int id;
String name;
Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing.
This method is defined in Object class as:
protected void finalize()
{
}
When we use final specifier with a method, the method cannot be overridden in any of
the inheriting classes. Methods are made final due to design reasons.
Since private methods are inaccessible, they are implicitly final in Java. So adding
final specifier to a private method doesn’t add any value. It may in-fact cause
unnecessary confusion.
class Base {
For example, both ‘program 1′ and ‘program 2′ below produce same compiler error “foo()
has private access in Base”.
Program 1
// file name: Main.java
class Base {
private final void foo() {}
}
Overloading method
Method Overloading in Java
1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion
If a class have multiple methods by same name but different parameters, it is known as
Method Overloading.
If we have to perform only one operation, having same name of the methods increases
the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behaviour of the method because its name differs. So,
we perform method overloading to figure out the program quickly.
}
}
Test it Now
Output:30
40
Java Constructor Overloading Examples
Like method overloading we can overload constructors also. Along with default constructor,
we can have constructors with parameters. The no of parameters can be same, and it can have
different datatypes. Below example gives sample code for constructors overloading.
Java Constructor Overloading Sample Code
Code:
package com.myjava.constructors;
public MyOverloading(){
System.out.println("Inside default constructor");
}
public MyOverloading(int i){
System.out.println("Inside single parameter constructor with int value");
}
public MyOverloading(String str){
System.out.println("Inside single parameter constructor with String object");
}
public MyOverloading(int i, int j){
System.out.println("Inside double parameter constructor");
}
The only point that needs to be taken care of is that when objects are passed to a
method, they are always passed via call be referance. So, any changes made to the
object values in the method would be reflected in the passed object values too.
Class Rectangle {
int length;
int width;
Rectangle(int l, int b) {
length = l;
width = b;
}
class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
r1.area(r1);
}
}
ARGUMENT PASSING
All parameters to methods in Java are pass-by-value.
// Method definition
public int mult(int x, int y)
{
return x * y;
}
RETURNING OBJECTS’
In Java Programming A method can return any type of data, including class types that you
create.
For example, in the following program, the getRectangleObject( ) method returns an object.
import java.io.File;
import java.io.IOException;
class Rectangle {
int length;
int breadth;
Rectangle(int l,int b) {
length = l;
breadth = b;
}
Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
}
class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;
ob2 = ob1.getRectangleObject();
System.out.println("ob1.length : " + ob1.length);
System.out.println("ob1.breadth: " + ob1.breadth);
}
}
Output of the Program :
ob1.length : 40
ob1.breadth: 50
ob2.length : 10
ob2.breadth: 20
RECURSION:
Java supports recursion. Recursion is the process of defining something in terms of
itself. As it relates to java programming, recursion is the attribute that allows a method to call
itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. for
example, 3 factorial is 1×2×3, or 6. Here is how a factorial can be computed by use of a
recursive method.
class Factorial {
int fact(int n) {
int result;
if ( n ==1) return 1;
result = fact (n-1) * n;
return result;
}
}
class Recursion {
public static void main (String args[]) {
Factorial f =new Factorial();
System.out.println(“Factorial of 3 is “ + f.fact(3));
System.out.println(“Factorial of 3 is “ + f.fact(4));
System.out.println(“Factorial of 3 is “ + f.fact(5));
}
}
The output from this program is shown here:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
If you are unfamiliar with recursive methods, then the operation of fact() may seem a
bit confusing. Here is how it works. When fact() is called with an argument of 1, the
function returns 1; otherwise it returns the product of fact(n-1)*n. to evaluate this expression,
fact() is called with n-1. this process repeats until n equals 1 and the calls to the method
begin returning.
To better understand how the fact() method works, let’s go through a short example.
When you compute the factorial of 3, the first call to fact() will cause a second call to be
made with an argument of 2. this invocation will cause fact() to be called a third time with an
argument of 2. This call will return 1, which is then be called a third time with an argument
of 1. This call will return1, which is then multiplied by 2 (the value of n in the second
invocation). This result (which is 2) is then returned to the original invocation of fact() and
multiply by 3 ( the original value of n). This yields the answer, 6. You might find it
interesting to insert println() statements into fact() which will show at what level each call is
and what the intermediate answers are.
When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start. A
recursive call does not make a new copy of the method. Only the arguments are new. As each
recursive call returns, the old local variables and parameters are removed from the stack, and
execution resumes at the point of the call inside the method. Recursive methods could be said
to “telescope” out and back.
Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls. Many recursive
calls to a method could cause a stack overrun. Because storage for parameters and local
variables, it is possible that the stack could be exhausted. If this occurs, the java run-time
system will cause an exception. However, you probably will not have to worry about this
unless a recursive routine runs wild.
The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives. For example, the
QuickSort sorting algorithm is quite difficult to implement in an iterative way.
ACCESS CONTROL
As you know, encapsulation links data with the code that manipulates it. However,
encapsulation provides another important attribute: access control. Through encapsulation,
you can control what parts of a program can access the members of a class. By controlling
access, you can prevent misuse. For example, allowing access to data only through a well-
defined set of methods, you can prevent the misuse of that data. Thus, when correctly
implemented, a class creates a “black box” which may be used, but the inner workings of
which are not open to tampering. However, the classes that were presented earlier do not
completely meet this goal. For example, consider the Stack class shown at the end of the
Recursion article. While it is true that the methods push() and pop() do provide a controlled
interface to the stack, this interface is not enforced. That is, it is possible for another part of
the program to bypass these methods and access the stack directly. Of course, in the wrong
hands, this could lead to trouble. In this section you will be introduced to the mechanism by
which you can precisely control access to the various members of a class.
The access specifier that modifies its declaration determines how a member can be
accessed. Java supplies a rich set of access specifiers. Some aspects of access control are
static {
System.out.println(“Static block initialized.”);
B = a *4;
}
public static void main (String args[]){
mech(42);
}
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is
set to 3, then the static block executes (printing a message), and finally, b is initialized to a*4
or 12. Then main() is called, which calls meth(), passing 42 to x. the three println() statements
refer to the two static variables a and b, as well as to the local variable x.
It is illegal to refer to any instance variables inside of a static method.
Here is the output of the program:
Static block initialized.
x = 42
a=3
b =12
Outside of the class in which they are defined, static methods and variables can be
used independently of any object. To do so, you need only specify the name of their class
followed by the dot operator. For example, if you wish to call a static method from outside its
class, you can do so using the following general form:
classname.method()
Here, classname is the name of the class in which the static method is declared. As
you can see, this format is similar to that used to call non-static methods through object-
reference variables. A static variable can be accessed in the same way by use of the dot
operator on the name of the class. This is how java implements a controlled version of global
functions and global variables.
Here is an example. Inside main(), the static method callme() and the static variable b
are accessed outside of their class.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println(“a = “ + a);
}
}
class StaticByName {
public static void main (String args[]) {
StaticDemo.callme();
System.out.println(“b =” + StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99
System.out.println(“length of a1 is “ + a1.length);
System.out.println(“length of a1 is “ + a1.length);
System.out.println(“length of a1 is “ + a1.length);
}
}
This program displays the following output:
length of a1 is 10
length of a1 is 8
length of a1 is 4
INTRODUCING NESTED AND INNER CLASSES
It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if
class B is defined within class A, then B is known to A, but not outside of A. A nested class
has access to the members, including private members, of the class in which it is nested.
However, the enclosing class does not have access to the members of the nested class.
There are two types of nested classes: static and non-static. A static nested class is one
which has the static modifier applied. Because it is static modifier applied. Because it is
static, it must access the members of its enclosing class through an object. That is, it cannot
refer to members of its enclosing class directly. Because of this restriction, static nested
classes are seldom used.
The most important type of nested class is the inner class is the inner class. An inner
class is a non-static nested class. It has access to al of the variables and methods of its outer
class and may refer to them directly in the same way that other non-static members of the
outer class do. Thus, an inner class is fully within the scope of its enclosing class.
The following program illustrates how to define and use an inner class. The class
named Outer has one instance variable named outer_x, one instance method named test(), and
defines one inner class called Inner.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
class Inner {
void display() {
System.out.println(“display : outer_x =” + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output from this application is shown here:
display: outer_x = 100
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. an instance
method named display() is defined inside Inner. This method displays outer_x on the standard
output stream. The main() method of InnerClassDemo creates an instance of class Inner and
the display() method is called.
It is important to realize that class Inner is known only within the scope of class
Outer. The java compiler generates an error message if any code outside of class Outer
attempts to instantiate class Inner. Generalizing, a nested class is no different than any other
program element: it is known only within its enclosing scope.
String x = "airplane";
String x = "book";
String x = "library";
String x = "United";
x += " States"
String x = "Exit";
String x = "01234567";
String x = "oxoxoxox";
public String substring(int begin)/ public String substring(int begin, int end)
The substring() method is used to return a part (or substring) of the String used to invoke the
method. The first argument represents the starting location (zero-based) of the substring. If
the call has only one argument, the substring returned will include the characters to the end of
the original String. If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the second argument.
Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last
character in the returned String will be in the original String's 7 position, which is index 6.
Let's look at some examples:
String x = "0123456789"; // the value of each char is the same as its index!
String s = “Java”;
The following example shows how a user might run Echo. User input is in italics.
java Echo Drink Hot Java
Drink
Hot
Java
Note that the application displays each word — Drink, Hot, and Java — on a line by itself.
This is because the space character separates command-line arguments. To have Drink, Hot,
and Java interpreted as a single argument, the user would join them by enclosing them within
quotation marks.
java Echo "Drink Hot Java"
Drink Hot Java
Parsing Numeric Command-Line Arguments
If an application needs to support a numeric command-line argument, it must convert a String
argument that represents a number, such as "34", to a numeric value. Here is a code snippet
that converts a command-line argument to an int:
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument" + args[0] + " must be an integer.");
System.exit(1);
}
}
parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the
Number classes — Integer, Float, Double, and so on — have parseXXX methods that convert
a String representing a number to an object of their type.