S5 Java Programming Using Linux Full Note
S5 Java Programming Using Linux Full Note
# Features of java: - The reason behind of creating Java is to bring portability and
security feature into a computer language. Beside these two major features, there were
many other features that played an important role in java. They are :
1. Simple: - Java is very easy to learn, and its syntax is simple, clean and easy to
understand. Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features,
Eg; explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented: - “mukaliundee”
3.portable:- Java is portable because it can carry the Java byte code to any platform. It
doesn't require any implementation
# java tokens:- In Java, the program contains classes and methods. Further, the
methods contain the expressions and statements required to perform a specific
operation. These statements and expressions are made up of tokens.
-The tokens are the small building blocks of a Java program that are meaningful to
the Java compiler
-The Java compiler breaks the line of code into text (words) is called Java tokens. These
are the smallest element of the Java program.
*Types of Tokens;
1. Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the following
keywords: int, float, if, for, do, char etc
2. Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user.
-It uses letters, underscores, or a dollar sign as the first character.
-The label is also known as a special kind of identifier that is used in the goto statement.
-Remember that the identifier name must be different from the reserved keywords. There
are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
3.Literals: In programming literal is a notation that represents a fixed value (constant) in
the source code.
-It can be categorized as an integer literal, string literal, Boolean literal, etc.
-It is defined by the programmer. Once it has been defined cannot be changed. Java
provides five types of literals are as follows:
Integer, Floating Point , Character , String , Boolean
4. Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators. There are eight
types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Operator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Bitwise &,|,^,~
Integer Constants:- refers to a Sequence of digits which Includes only negative or positive
Values and many other things those are as follows
Eg;
-Decimal Integer Constants :- consists of a set of digits 0 through 9, preceded by an
optional –or + sign.
-Ocatal Integer Constants:- consists of any combimation of digits from the set 0
through 7, with an leading 0. Eg: 038, 320, 0456, 0552, 0432
-Hexadecimal Integer Constants :- consists of any combimation of digits from the
set 0 through F, with an leading 0x or 0X eg; 0x4, 0X456, 0x552, 0x32, 0x43
An Integer Constant must have at Least one Digit
it could be either positive or Negative
if no sign is Specified then it should be treated as Positive
No Spaces and Commas are allowed in Name
Real Constants :- Integer numbers are unable to represent distance, height, temperature,
price, and so on. These informations are contaning fractional parts or real parts like
56.890. Such numbers are called Real or Floating Point Contants .
Single Character Constants :-A Character is Single Alphabet a single digit or a Single
Symbol that is enclosed within Single inverted commas.
1. Character Constant Can hold Single character at a time.
2. Contains Single Character Closed within a pair of Single Quote Marks
3. Single Character is smallest Character Data Type in C.
4. Integer Representation: Character Constant reprent by Unicode
5. It is Possible to Perform Arithmetic Operations on Character Constants
*variables:- is an identifier that denotes a storage location used to store a data value.
-unlike constants the remain unchanged during the execution of a program , a variable
may take diff values at diff times during the execution of the prg.
-variable names may consist of alphabets, digits, underscore(_), and dollar.
-it has some conditions they are;
Must not begin with a digit.
Uppercase and lowercase are distinct that means TOTAL and total are diff
It should not be a keyword
White space is not allowed
Variable names can be of any length.
#data types:- every variable in java has a data type. Data types specify the different sizes
and values that can be stored in the variable. There are two types of data types in Java
> Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
.
>>Integer type :- can hold whole numbers such as 123, -96 and 5639. The size of values that can be
stored depend on the integer data type we choose.java supports 4 types of integers they are byte
,short, int,long
>>Floating point type :- integer type can hold only whole numbers and therefore we use another
type known as floating point type to hold numbers containing fractional parts
-There are two kinds of floating point storage in java they are
1) float:- float type values are single- precision numbers
2) double:- double type represent double- precision numbers.
>> Character type/char:-in order to store character constants in memory, java provide a charater
data type called char.The char type assumes a size of 2 bytes but, basically ,it can hold only a single
character.
>>Boolean type:- Is used when we want to test a particular condition during the execution of the
program.
-there are only two value that a Boolean type can take: true or false.
-it is denoted by keyword Boolean and uses only one bit of storage.
>Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
#operators:- java supports a rich set of operators. Operators is a symbol that tells the
computer to perform certain mathematical or logical manipulations.
1.arithmetic
2.Relational operators
3.logical
4.Assignment Operators:
$ = Assign 10+10 = 20
$ += Add and assign
var a=10; a+=20; Now a = 30
$ -= Subtract and assign
var a=20; a-=10; Now a = 10
$ *= Multiply and assign
var a=10; a*=20; Now a = 200
$ /= Divide and assign
var a=10; a/=2; Now a = 5
$ %= Modulus and assign
var a=10; a%=2; Now a = 0
5.increment and decrement
6.conditional
7.Bitwise
*Arithmetic expression
#Control Statements/ decision making
*if statement
1. if Statement: if we want to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
N.B. that if is written in lowercase letters. Using uppercase letters (IF) will generate a JS
error!
2. if…else Statement
If we want to execute some code if a condition is true and another code if the condition is
not true, use the if….else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
3. if…else nesting
We should use the if….else nesting if we want to select one of many sets of lines to execute.
Syntax
if (condition1) {
code to be executed if condition1 is true
}
else if (condition2) {
code to be executed if condition2 is true
}
else {
code to be executed if condition1 and condition2 are not true
}
* switch Statement
We should use the switch statement if we want to select one of many blocks of code to be
executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case
in
the structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
”fig varakkan padikkanam”
* Branching statements:- are the statements used to jump the flow of execution from
one part of a program to another.
-The branching statements are mostly used inside the control statements.
-Java has mainly three branching statements, i.e., continue, break, and return.
-The branching statements allow us to exit from a control statement when a certain
condition meet.
# looping statements:- : if you want to run the same code over and over again, each
time with a different value.
-There are four types of loops in Java;
1)For loop: iterates the elements for the fixed number of times. It should be used if
number of iteration is known. The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
2)while loop: iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.
while (condition)
{
code to be executed
}
3)do while loop: iterates the elements for the infinite number of times like while loop.
But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
Do
{
code to be executed
}
while (condition);
4) for in loop: is used to iterate the properties of an object.
# jump statements:( break, cont, return)
* continue statement:- is used in loop control structure when you need to jump to th
next iteration of the loop immediately. It can be used with for loop or while loop.
- in Java continue statement is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition
- Java continue statement in all types of loops such as for loop, while loop and do-while
loop.
Syn;-
jump-statement;
continue;
* return statement:- is used for returning a value when the execution of the block is
completed. The return statement inside a loop will cause the loop to break and further
statements will be ignored by the compiler.
- This are the important points must remember while returning a value:
o The return type of the method and type of data returned at the end of the method
should be of the same type. For example, if a method is declared with the float
return type, the value returned should be of float type only.
o The variable that stores the returned value after the method is called should be a
similar data type otherwise, the data might get lost.
o If a method is declared with parameters, the sequence of the parameter must be the
same while declaration and method call.
Syn;- return returnvalue; “return value inta edakku space illa”
# labeled loops: in java ,we can give a label to block of statements .
- A label is any valid java variable name.
-To give a label to a loop , place it before the loop with a colon ath the end. eg;
Module -2
#Defining a Class:- A class is a user defined blueprint or prototype from which objects
are created.
-once class type has been defined, we can create “variables” of that type using declarations
that are similar to the basic type declaration.
-in java ,these variables are termed as instances of classes ,which are the actual object.
#Fields declaration:- Data is encapsulated in a class by placing data fields inside the
body of the class definition.
-These variables are called instance variables because they are created whenever an object
of the class is instantiated.
-Instance variables are declared in the same way as local variables are declared.
Syntax: type variable_name;
Example : int num;
String fname;
#Method declaration:- the method in Java is a collection of instructions that
performs a specific task.
- It provides the reusability of code. We can also easily modify code using methods.
-method declaration have four basic parts
1.the name of the method (method name).
2.the type of the value the method returns (type).
3.A list of parameters (parameter list)
4.the body of the method .
#Creating object:-An object in java is a block of memory that contains space to store
all the instance variables.
-Creating an object is referred to as instantiating an object
-object in java are created using the new operator.
-There are three steps when creating an object from a class. They are;
Declaration - A variable declaration with a valid name and an object type.
Instantiation − The new keyword is used to create the object.
Initialization − The new keyword is followed by a call to a constructor. This call
initializes the new object.
Syntax :
Declaration : classname objectname;
Initialization : objectname=new classname();
Both these statements can be combined as follows:
classname objectname=new classname();
Eg; Rectangle rect=new Rectangle();
# Accessing class members:- Objects of a class are created for accessing class
members from outside the class.
-To do this dot operator is used along with objects.
Syn;
objectname.variablename=value;
objectname.methodname(parameter_list);
#method overloading:-in java ,it is possible to create methods that have the same name
,but different parameter lists and different definitions this is called method overloading.
-it is used when object are required to perform similar tasks but different input parameters.
-when we call a method in an object, java matches up the method name first and then the
number and type of parameters to decide which one of the definitions to executed this
process is called polymorphism.
-There are three ways to overload a method, the argument lists of the methods must differ
in either of these.
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters
-if two methods have same name, same parameters and have different return type, then
this is not a valid method overloading.
# overriding methods:- If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding.
-In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
->Usage
-Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
-Method overriding is used for runtime polymorphism.
->Rules for Method Overriding
-The method must have the same name as in the parent class
-The method must have the same parameter as in the parent class.
-There must be an IS-A relationship (inheritance).
*Difference between Overloading and Overriding
#dynamic method dispatch/Runtime Polymorphism:-is the mechanism in which a
call to an overridden method is resolved at run time instead of compile time.
-When an overridden method is called through a superclass reference, Java determines
which version (superclass/subclasses) of that method is to be executed based upon the type
of the object being referred to at the time the call occurs. Thus, this determination is made
at run time.
-bakki unde”.
#Abstract methods and classes:- A class which is declared using abstract keyword is
known as an abstract class.
- An abstract class may or may not have abstract methods
-An abstract class can have concrete methods (normal methods).
-An abstract class you are not allowed to create an object of it. OR It cannot be instantiated.
-It is used for abstraction.
Syntax : abstract class class_name { }
-Method that are declared without any body within an abstract class are called abstract
method.
-The method body will be defined by its subclass.
-Abstract method can never be final and static.
-Any class that extends an abstract class must implement all the abstract methods.
Syntax: abstract return_type function_name (); //No definition.
#Visibility control:- It is possible to inherit all the members of a class by a subclass using
the keyword extends
-The variables and methods of a class are visible everywhere in the program. However, it
may be necessary in some situations we may want them to be not visible outside.
- We can achieve this in Java by applying visibility.
- The visibility modifiers are also known as access modifiers.
- Java provides three types of visibility modifiers: public, private and protected
-> Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
-> Friendly Access (Default): The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
-> Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
-> Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Module – 3
#Arrays:- A group of related data items that share a common name.
-An array is a collection of similar data types.
-Array is a container object that holds values of homogeneous type. It is also known as
static data structure because size of an array must be specified at the time of its
declaration.
-Array starts from zero index and goes to n-1 where n is length of the array.
-Array can be single dimensional or multidimensional
->Features of Array
It is always indexed. Index begins from 0.
It is a collection of similar data types.
It occupies a contiguous memory location.
It allows to access elements randomly.
all arrays are dynamically allocated.
-Initialization of arrays
Eg; int number[] ={35,23,67,45,32}
->Types of Array in java they are;
1)Single Dimensional Array:- Single dimensional array use single index to store
elements.
⫸ Array Declaration
Syntax : datatype[] arrayName;
or datatype arrayName[];
-Java allows declaring array by using both declaration syntax, both are valid.
-The arrayName can be any valid array name and datatype can be any like: int, float,
byte etc. Example : int[ ] arr; char[ ] arr; short[ ] arr; long[ ] arr;
⫸Initialization of Array
Syntax : arrayName = new datatype[size]
-Initialization is a process of allocating memory to an array.
-At the time of initialization, the size of array to reserve memory area is specified.
-new operator is used to initialize an array.
-The arrayName is the name of array, new is a keyword used to allocate memory and
size is length of array.
- Both declaration and initialization can be combined into a single statement
Datatype[] arrayName = new datatype[size]
2)Multidimensional Array:- A multi-dimensional array is very much similar to a single
dimensional array.
-It can have multiple rows and multiple columns unlike single dimensional array, which
can have only one row index.
-It represents data into tabular form in which data is stored into row and columns.
⫸ Array Declaration
Syntax : datatype[ ][ ] arrayName;
⫸Initialization of Array
Syntax : datatype[ ][ ] arrayName = new int[no_of_rows][no_of_columns];
exceptions etc.
✦ java.applet – classes for creating and implementing applets.
✦ java.io – provide the facilities for input and output.
✦ java.net – include classes for communication with local computers as well as with
internet servers.
2. User defined packages:- User defined packages are Java packages created by user to
categorize their project's classes and interface are known as user-defined packages.
-> Creating packages
-Creating a package in java is quite easy, simply include a package command.
-> Packages – Access Protection
• Anything declared public can be accessed from anywhere.
• Anything declared private cannot be seen outside a class.
• No modifier is the default.
-> Using packages
- Use import to access built-in and user-defined packages.
- import keyword is used
- It is used to access package and its classes into the java program.
* Life Cycle of a Thread:-Durind the life of thread ,there are many state of thread they
are;
4. Blocked State:- When a thread is temporarily inactive, then it’s in one of the following
states: Blocked or Waiting.
-this is tha state when the tread is still alive, but is currently not eligible to run.
5. Dead State/terminated:- Kill the thread using the stop() method.
* Creating Threads:- Threads are implemented in the form of objects and contain a
method called run().
-The heart of the thread is the run() method.
-Threads can be implemented in 2 ways.
1. By extending the Thread class
2. By implementing Runnable interface
Module – 4
*Event Listeners:- A listener is an object that is notified when an event occurs. It has 2
requirements.
1. It must have been registered with one or more sources to receive notifications about
specific type of events.
2. It must implement methods to receive and process these notifications.
-Methods that receive and process events are defined in a set of interfaces in
java.awt.event.
*Event Class
1. ActionEvent - Generated when a button is pressed, a list item is double-clicked or a
menu item is selected.
2. AdjustmentEvent – Generated when a scroll bar is manipulated.
3. ComponentEvent – Generated when a component is hidden, moved, resized or
becomes visible.
4. ContainerEvent – Generated when a component is added or removed.
5. FocusEvent – Generated when a component gains or loses keyboard focus.
6. InputEvent – Abstract super class for all component input event classes.
7. ItemEvent - Generated when a checkbox or list item is clicked. Also occurs when a
choice selection is made or a checkable menu item is selected or deselected.
8. KeyEvent – Generated when input is received from the keyboard.
9. MouseEvent – Generated when the mouse is dragged, moved, clicked, pressed or
released. Also generated when the mouse enters or exits a component.
10.TextEvent – Generated when the value of a text area or text field is changed.
11.WindowEvent – Generated when a window is activated, closed, deactivated,
deiconified, iconified, opened or quit.
#SWINGS:- Swing is a set of classes that provides more powerful and flexible components
such as buttons, checkboxes, labels etc.
Eg; a button may have both an image and a text string associated with it.
-Swing Features
Light Weight − Swing components are independent of native Operating System's API
as Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls.
Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
Highly Customizable − Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Pluggable look-and-feel − SWING based GUI Application look and feel can be changed
at run-time, based on available values.
->Swing architecture “imp annu”
->Swing components
-component is an independent visual control and Java Swing Framework contains a large set
of these components.
-J Component class components are lightweight components.
-container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types
1. Top level Containers
It inherits Component and Container of AWT.
It cannot be contained within other containers.
Heavyweight.
2. Lightweight Containers
It inherits JComponent class.
It is a general purpose container.
It can be used to organize related components together
->JFrame
• JFrame is a java class that is extended by Frame class of Java.
• JFrame is treated as the main window
• Swing version of Frame.
•Top-level window with a title and a border.
->JButton
•JButton class provides functionality of a button.
• Swing version of Button. More powerful than buttons in AWT.
• JButton class has three constructors.
->JLabel
-Swing version of List.
- Displays a list of objects and allows the user to select one or more items.
-It is used to display a single line of read only text.
-The text can be changed by an application but a user cannot edit it directly.
->JCheckBox
-The JCheckBox class is used to create a checkbox.
-It is used to turn an option on (true) or off (false).
-Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
->JRadioButton
-The JRadioButton class is used to create a radio button.
-It is used to choose one option from multiple options.
-It is widely used in exam systems or quiz.
-It should be added in ButtonGroup to select one radio button only.
->JTextField
-Swing version of TextField.
-JTextField is a subclass of JTextComponent.
-A JTextField object is a visual component that can display one line of editable text of one
font and color at a time.
-The text is placed inside a box.
->JPasswordField
- The JPasswordField creates a display for text field similar to JTextField.
-The only difference is that when text is displayed, the actual characters are replaced by *
character.
-This password field is useful where the text typed by a user is not to be seen by other
people.
->JTextArea
-is a subclass of JTextComponent.
-A JTextArea component displays multiple lines of text in one color and with one font.
-Text area text is displayed as such in the defined window.
-There is no scroll bar to view the text.
->JList JList
-is part of Java Swing package .
- JList is a component that displays a set of Objects and allows the user to select one or
more items .
-JList inherits JComponent class.
->JComboBox
-JComboBox is a part of Java Swing package.
- JComboBox inherits JComponent class.
-JComboBox shows a popup menu that shows a list and the user can select an option from
that specified list.
->JPanel
-The JPanel is a simplest container class.
- It provides space in which an application can attach any other component.
-It inherits the JComponents class.
-Java coordinate system has the origin (0,0) in the upper left corner.
Positive x values are to the right, and positive y values are to the bottom.
The values of coordinates x and y are in pixels.
->The Graphics Class:-Java’s Graphics class includes methods for drawing many
different shapes, from simple lines to polygons to text in a variety of font
1. drawArc() – draws an arc.
2. drawLine() – draws a straight line.
3. drawOval() – draws an oval.
4. drawPolygon() – draws a polygon.
5. drawString() – displays a string.
6. fillArc() – draws a filled arc.
7. fillOval() – draws a filled oval.
8. fillPolygon() – draws a filled polygon.
9. fillRect() – draws a filled rectangle.
10. getColor() – retrieves the current drawing color.
11.setColor() – sets the drawing color.
*JDBC Architecture:- The JDBC API supports both two-tier and three-tier
processing models for database access, but in general JDBC Architecture
consists of two layers:
1. The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
-The JDBC driver manager ensures that the correct driver is used to
access each data source.
-The driver manager is capable of supporting multiple drivers
connected to multiple heterogeneous databases
3) card layout:-
4)Border Layout:- is used to arrange the components in five regions: north,
south, east, west, and center.
-Each region (area) may contain one component only.
-The BorderLayout provides five constants for each region:
*public static final int NORTH
*public static final int SOUTH
*public static final int EAST
*public static final int WEST
*public static final int CENTER
-Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.