U1 Java
U1 Java
C
Introduction to Java h
Topics
1. **Java Features.
a
2. **How Java is Differ from C and C++. pt
3. Java and Internet.
4. Java and WWW, Web Browsers.
er
5. Hardware and Software Requirements. -
6. Java Environment.
7. **JVM
1
What is Java?
Java is a “general purpose object oriented programming language” and high-level, robust, secure and
developed by “Sun Microsystems” of USA. It is a Platform.
Platform: - any hardware and software environment in which a program runs is known as a platform.
Since java has its own runtime environment i.e. JRE [Java Runtime Environment] and API [Application
program Interface] and it is called “Platform”.
History of Java
Java was designed for the development of software for consumer electronic devices like TVs, VCRs,
and such other electronic machines.
Year Development
1990 Sun Microsystems decided to develop special software that could be used to manipulate
consumer electronic devices.
1991 After exploring the possibilities of using the most popular object- oriented language C++, the
team announced a new language named “Oak” (a tree name)
1992 The team formed to accomplish Oak language called as Green Team, and project is called as
Green Project by Sun Microsystems. And the team consist five members. The team leader is
James Gosling and members are Mike Sheridan, Patric Naughtier, Chrriswarth, and Ed Prank.
1993 The WWW gaining more popularity. The Green Project team came up with the idea of
developing Web applets (Tiny programs) for internet.
1994 The team developed a Web Browser called “Hot Java” to locate and run applet programs on
Internet.
1995 Oak was renamed as “Java”, due to legal snags. Because Oak is a national tree in many country
like USA, France, Germany, etc.. Java is not an acronym. Many popular companies including
Netscape and Microsoft announced their support to Java.
1996 Sun Microsystems releases Java Development Kit 1.1 (JDK 1.1)
Note: Java refers to Coffee Beans produced in the Indonesian Java Island. The symbol of java is tea cup
saucer.
The most striking feature of java is a Platform-Neutral. Java is the first programming language that is
not tied to any particular hardware or operating system. The programs developed in java can be
executed anywhere on any system.
J2SE deals with developing standalone applications and applications for network and also
exploring java library. J2SE is basically used for developing client side applications/programs.
J2EE deals with developing business solutions for a network or internet. J2EE is used for
developing server side applications/programs.
J2ME deals with developing embedded systems and wireless applications. J2ME is used for
developing server side applications/programs.
In the second stage, the Java interpreter generates machine code from byte code that can be
directly executed by the system. Thus Java is both compiled and interpreted language.
2. Platform Independent:
A program (or) technology is said to be platform independent, because java is “Write once run
anywhere” and java can run on all available operating systems. The language JAVA will have a
common data types and the common memory spaces on all operating systems and the JAVA
software contains the special programs which converts the format of one operating system to
another format of other operating system. Hence JAVA language is treated as platform independent
language.
3. Portable:
The most benefit of java over other languages is its “portability”. Java programs can be easily
moved from one computer to another, anywhere and anytime.
A portable language is one which can run on all operating systems and on all processors irrespective
of their architectures and providers. The languages like C, C++ are treated as non-portable languages
whereas the language Java is called Portable language.
4. Object Oriented:
Java is a true object oriented language. Almost everything in Java is an object. Any programming
language that satisfies all the principles of OOP is called as an Object Oriented Programming
Language. The Java language satisfies all the principles of OOP. Hence it is called an Object Oriented
Programming Language. Java is a true object oriented language.
5. Robust:
Java is Roust programming language. It provides many safeguards to ensure reliable code. Robust is
nothing but it doesn’t allow to crash the system.
Note: Compile time errors are occurring when the programmer is not following syntax rules of the
programming language.
6. Secure:
Security becomes an important issue for a language that is used for programming on Internet. Java
is one of the most secured programming languages. Java also ensures that no viruses are
communicated with an applet. (The absence of pointers in Java ensures that programs cannot gain
access to memory locations without proper authorization.)
To provide the security to our java real time applications, we need not write our own security code.
Since java library (API) contains readily available security programs for protecting confidential
information from unauthorized users.
7. Distributed:
Java is designed as a distributed language for creating the applications on networks. It has the
ability to share both data and programs. Java programs can open and access remote objects on
Internet as easily as they can do in a local system.
Java is small and simple language. Many features of C and C++ that are either redundant or
unreliable code are not part of Java. For example, Java does not use pointers, pre-processor header
files, goto statement and many others. It also eliminates operator overloading and multiple
inheritance.
9. Multithreaded:
Java is one of the High Performance programming languages because of the following reasons.
A language (or) technology is said to be architectural neutral which can run on any available
processors in the real world. The languages like C, C++ are treated as architectural dependent.
The language Java can run on any of the processor irrespective of their architecture and vendor.
The following are some of the C features those does not include in the Java
The following are some of the C features those does not include in the Java
Before Java the WWW was limited to display the images and texts. However, the incorporation of
Java into Web pages made it capable of supporting animation, graphics, games, and a wide range of
special effects. Java communicates with a Web page through a special tag called <APPLET>.
The following are the steps that illustrate the communication steps.
The user sends a request for an HTML document to the remote computer`s Web server. The Web
server is a program that accepts a request, processes the request, and sends the requested
document.
The HTML document is returned to the user`s browser. The document contains the APPLET tag,
which identifies the applet.
The corresponding applet byte code is transferred to the user`s computer. This byte code had been
previously created by the Java compiler using the Java source code file for that applet.
The Java enabled browser on the user`s computer interprets the byte codes and provide output.
Web Browsers:
Web browsers are used to navigate through the information found on the net. They allow us to
retrieve the information across the Internet and display it using the Hypertext Markup Language
(HTML). Examples for Web browsers are as follows.
Hot Java
Netscape Navigator
Internet Explorer
These are explained as follows;
Hot Java
Hot Java is the web browser form the Sun Microsystems. Hot java is written entirely in Java. When
the Java language was first developed and ported to the Internet, no browsers were available that
could run Java applets.
Hot Java is currently available Windows 95, Windows NT and Windows XP.
Netscape Navigator
Netscape Navigator, from Netscape Communications Corporation, is a general-purpose browser
that can run Java applets.
Netscape Navigator has many useful features such as visual display about downloading process and
indication of the number of bytes downloaded.
Internet Explorer
Internet Explorer is another popular browser developed by Microsoft for Windows 95, NT and XP
Workstations. Both the Navigator and Explorer use toolbars, icons, menus and dialog boxes for easy
navigation. Explorer uses a Just-In-Time (JIT) compiler which greatly increases the speed of
execution.
Java Environment:
Java Environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development Kit (JDK) and
the classes and methods are part of the Java Standard Library (JSL), also known as the Application
Programming Interface (API).
a) Java Development Kit (JDK)
The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs. They include
appletviewer: Enables us to run Java applets.
javac (Java Compiler): The Java Compiler, which translates Java source code to bytecode files
that the interpreter can understand.
java (Java Interpreter): Java Interpreter, which runs applets and applications by reading and
interpreting byte code files.
javadoc (for creating HTML documents): Creates HTML- format documentation from Java
1) Java Virtual Machine (JVM): It is a program that interprets the intermediate Java byte code and
generates the desired output.
2) Runtime Class Libraries: These are a set of core class libraries that are required for the execution
of java programs.
3) User Interface Tool Kit: AWT and Swing are example of toolkits that support varied input
methods for the users to interact with the application program.
II. Java Web Start: Enables remote-deployment of an application. With Web Start, users
can launch an application directly from the Web browser without going through the
installation procedure.
First of all, the .java program is converted into a .class consisting of byte code instructions by the
java compiler for a machine called Java Virtual Machine as shown in below. The JVM exists only
inside the computer memory.
The byte code is not a machine specific code (machine code). The machine code is generated by the
Java Interpreter by acting as an intermediary between the virtual machine and the real machine as
shown in below.
JVM Architecture:
Now in this JVM lession, let’s understand the Architecture of JVM. JVM architecture in Java contains
classloader, memory area, execution engine etc.
1) Class Loader
The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the
code for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory
is common and shared across multiple threads.
Java language Stacks store local variables, and its partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a
method is invoked, and it is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing.
In Java, each thread has its separate PC register.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test
execution engine never carries any information about the tested product.
The Native Method Interface is a programming framework. It allows Java code which is running
in a JVM to call by libraries and native applications.
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution
Engine.
C
h
2. Naming Conversion and Data_type a
p
Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
t
r
–Page no -10
Names of all public methods and instance variables start with a leading lowercase letter.
Examples: average
total
When more than one words are used in a name, the second and subsequent words are marked
with a leading uppercase letters.
Examples: firstDayOfMonth
totalMarks
All private and local variables use only lowercase letters combined with underscores.
Examples: length
batch_strength
All classes and interfaces start with a leading uppercase letter (and each) subsequent word with
a leading uppercase letter.
Examples: Student
HelloJava
Variables that represent constant values use all uppercase letters and underscores between
words.
Examples: TOTAL
F_MAX
It should be remembered that all these are conventions and not rules. We may follow our own
conventions as long as we do not break the basic rules of naming identifiers.
Java Applications:
1. Stand- Alone applications
Stand-alone applications are programs written in java to carry out certain tasks on local
computer. In fact java can be used to develop programs for all kinds of applications, which earlier
were developed using languages like C and C++. Executing a stand-alone java program involves two
steps:
We can develop applets for doing everything from simple animated graphics to complex games
and utilities.
Since applets are embedded in an HTML documents and run inside a webpage, creating and
running applets are more complex than creating an application. An applet can only run within
a Web Browser.
.
Fig. Structure of Java Program
1. Documentation Section
The documentation section contains a set of comment lines giving the name of the program,
the author and other details. Comments must explain why and what classes and how of
algorithms.
Java provides a special type of comments they are multiline comments “/* ……. */” and single
line comments “//” these are called documentation comments. This form of comment is used
for generating documentation automatically.
2. Package Statement
The first statement allowed in a java file is a package statement. This statement declares a
package name and informs the compiler that the classes defined here belong to this package.
“The package statement is optional”.
Example: package student;
3. Import Statement
The next statement after a package statement may be a number of import statements. This is
similar to the #include statement in C language. Using import statements; we can have access
to classes that are part of other named packages.
Example: import java.lang.System; , import java.io.*;
This statement instructs the ‘interpreter’ to load the ‘System’ class contained in the ‘lang’
Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no -12
The first three lines document section and package section and import section and the program
will starts from the class section these three sections are optional.
1. Class Declaration
The program starting fourth line
class Sample
Declares a class, which is an object oriented construct. Java is a true object-oriented programming
language and therefore, everything must be placed inside a class.
Class: - is a keyword used to declare a new class definition.
Sample: - is a java identifier that specifies the name of the class.
2. Opening Brace
Every class definition in java begins with an opening brace “{“and ends with a matching closing
brace“}”.
public The keyword public is an Access Specifier that declares the main method as
unprotected and therefore making it accessible to all other classes. This is similar
to the C++ public modifier.
static The keyword static declares this method as one that belongs to the entire class
and not a part of any objects of the class. The main must always be declared as
static since the interpreter uses this method before any objects are created.
void This keyword states that the main method does not return any value.
Output:
E:\WINDOWS\system 32\cmd.exe
Java Comments
There are three types of comments in java – single line, multi line, and Java documentation.
These comments are for making a single line as a comment. These comments start with double slash
symbol (//) and after this, whatever is written till the end of the line is taken as a comment.
Example: // This is my comment of one line
2. Multi-line Comment
These comments are used for representing several lines as comments. These comments start with /*
and end with */. In between /* and */ , whatever is written is treated as a comment.
Example:
These comments start with /** and end with */. These comments are used to provide description
for every feature in a java program.
Keywords are an essential part of a language definition and it is a special type of reserved words.
They implement the specific features of the language. The Java language has reserved 50 words
as keywords as shown in the below table.
Since the keywords have specific meaning in java, we cannot use them as names for variables,
classes, methods and so on. All keywords are to be written in lower-case letters.
Java Keywords
2. Identifiers
Identifiers are program designed tokens. They are used for naming the classes, methods,
variables, objects, labels, packages and interfaces in a program.
They can have alphabets, digits and the underscore (_) and dollar ($) sign
characters.
Identifiers must be meaningful, short enough to be quickly typed and easily read. Java developers
have followed some naming conventions.
Names of all instance variables and methods start with a leading lowercase letter. One or
more than one word is used in a name, the second and subsequent words are marked with a
leading uppercase letters.
Example: int average
float sum
float dayTempature shorttotalMarks
char firstDayOfMonth
TOTAL PI
PRINCIPAL_AMOUNT
3. Literals
Literals in java are a sequence of characters that represent constant values to be stored in
variables.
Java language specifies five major types of literals. They are
Integer literals
Floating point literals
Character literals
String literals
Boolean literals
4. Operators
An operator is a symbol that takes one or more arguments and operates on them to
produce a result.
5. Separators
Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code. The following are the list of separators and
their functions.
Name Its function
Parentheses ( () ) Used to enclose the parameters in method definition and invocation, also used
for defining precedence in expressions.
Braces ( { } ) Used to contain the values of automatically initialized arrays and to define a
block of code for classes, methods and local scopes
Brackets ( [ ] ) Used to declare array types and for dereferencing the array values.
Semicolon ( ; ) Used to separate the statements
Comma ( , ) Used to separate the consecutive elements in a variable declaration
Period ( . ) Used to separate package names from sub-packages and classes, also used to
separate a variable method from a reference variable.
Java Statements
The statements in java are like sentences in natural languages. A statement is an executable
combination of tokens ending with a semicolon (;) mark. Statements are usually executed in the
sequence in the order in which they appear.
The following diagram illustrates the types of java statements.
1. Expression Statements
Most statements are expression statements. Java has seven types of Expression statements.
Assignment
Pre-increment
Pre-decrement
Post-increment
Post-decrement
Method call
Allocation expression
2. Labeled Statement
Any statement may begin with a label. Such labels must not be keywords. In java they are used
as the arguments of jump statements.
3. Control Statements
In java, it is possible to control the flow of execution. Java language provides three types of
control structures. Those are discussed below
a. Selection Statement
These select one of several control flows. There are three types of statements in java.
Those are if, if-else and switch
b. Iteration Statement
These specify how and when looping will take place. There are three types of iteration
statements in java. Those are while, do and for.
c. Jump Statement
Jump statements pass the control to the beginning or end of the current block, or to a
labeled statement. The four types of jump statements are break, continue, return and
throw.
4. Synchronization Statement
5. Guarding Statement
Guarding statements are used for safe handling of code that may cause exceptions. These
statements use the keywords try, catch and finally.
I.Create program
II.Compile program
To compile the java program, we must use the java compiler javac along with the source file
name on the command line as shown in below.
C:/> javac Test.java
If everything is OK, then java compiler creates a .class file containing the byte code of the
program (Test.class).
To run a stand-alone application we need to use the java interpreter on the command prompt
as shown in below.
C:/> java Test
Now, the interpreter looks for the main method in the program and begins execution from there.
When the program is executed the above program displays the output…
Hellow !
Welcome to the world of Java…
Spaces, commas, and non-digit characters are not permitted between digits.
Example: 1 5, 20.001, 1$0 are illegal numbers.
2) Octal Integer:- consists of any combination of digits from the set 0 through 7,
with a leading 0.
1) It is possible that the number may not have digits before the decimal point or digits
after the decimal point
Example: 215. .95 -.127
2) The real numbers are formed with two parts known as mantissa and exponent
where mantissa is either decimal (or) integer and exponent is an integer either
positive (or) negative
3) Exponential notation is useful for representing numbers that are either very
large or very small in magnitude.
For example 430000 may be written as 4.3e5 or 43e4. Similarly, -0.00000234 is equivalent
to -.e5234.
3.Character Constants
A Character constant is a single character i.e., enclosed within a pair of single quotes.
Every character is having integer values known as ASCII (American standard code for
information interchange) values.
4. String Constants
A group of characters combined within a pair of double quotes is known as string constants.
Example: “SURYA”, ” INDIA”, “3”, “+..*!”, “3+1”, “U”, “Standard Java”
Variables
“A variable is a named memory location and identifiers that can store the value of the
program”. A Variable is an identifier this takes different values at different times during the
program execution. A variable name can be chosen by the programmer in a meaningful, shorter
form.
average
height
total_height
sum
Variable names may consist of alphabets, digits, the underscore ( _ ) and dollar character ( $ ).
While declaring the variable we should follow some precautions.
Rules for defining variables:
1) They must begin with a character including underscore(_).
2) They should not start with digits(0-9).
3) They can take any of length.
4) Keywords names are shooed not used in the variable names.
5) Upper case and lower case are distinct i.e., sum & SUM are not the same.
Declaration of Variables
In java, the variables are the names of the storage locations. After designing the variable
name, we must declare them to the compiler. It tells three things.
1) It tells the compiler what the variable name is
A variable must be declared before it is used in the program variable can be used to store a
value of any data type. That is, name has nothing to do with the type. Java allows any
properly formed variable to declared as a type.
The declaration statement defines the type of the variable. The general form of the declaration is
Data Types
Data types specify the size and type of values that can be stored. Java language supports
numerous data types. Every variable in java has a data type. Data types are used for
representing the data in main memory of the computer. The variety of data types are available
allow the programmer to select the type appropriate to the program.
Java has eight data types which are grouped in four groups. They are Integer category Data
types, Floating point category data types, Character category data types, Boolean category data
types.
Integer types can hold whole numbers such as 112, -234, and 566. They are used to
represent integer data. Java supports four types of integers. Java values are signed meaning
they can be positive or negative.
The following table shows memory size and range of all integer types.
It should be remembered that data types require more time for manipulation, and therefore
it is advisable to use smaller data types, whenever possible. This process will improve the
speed of execution of the program.
Whatever the data type we should not exceed the predefined value.
We can make integers long by appending the letter L or 1 at the end of the number.
Float category data types are used for representing the data in the form of scale, precision
i.e., these category data types are used for representing numbers with fractional part. There
are two types of floating point storage in java.
We must append f or F to float numbers.
Example: 1.23f (or) 1.23F456.67e3f
The following table shows memory size and range of all float types.
C/CPP JAVA
1 byte 2 bytes
ASCII UNICODE
The following table shows memory size and range of all character type.
UNICODE character set is one which contains all the characters which are available in 18
international languages and it contains 65536 characters.
Boolean category data types is used for representing logical values i.e., TRUE or FALSE values.
To represent logical values we use a keyword called boolean. This data type takes one bit of
memory space.
Scope of Variables
Java variables are actually classified into three kinds.
1) Instance variables
2) Class variables
3) Local variables
1. Instance Variables:
Instance variables are declared and created when the objects are instantiated. They take
different values for each object.
2. Class Variables:
Class variables are those which are present within the class and belongs to entire set of
objects that class creates. Only one memory location created for each class variable.
3. Local Variables:
Local variables are the variables that are present within the method. They are not available
outside of the method. These variables are visible within the method where it is defined.
We cannot declare a variable to have same name again. For example if you declare x variable
in one block is not repeated in another block within the same class (this is perfectly legal in
C and C++).
Symbolic Constants
A Numeric value is not always clear, to the sense that it means different things at different places.
For example 50 may mean number of students at one place, and the pass marks at the other
place.
Assignment of a symbolic name to such constants frees us from these problems. For example
we may use the name strength to denote the number of students. “pass-mark “to denote the
pass marks required in a subject.
Symbolic names take the same form as variable names. But they are generally
written in capitals to distinguish from the normal variable names.
They should not be declared inside a method. They should be used only as class
data members in the beginning of the class.
Operators in Java
Java supports a rich set of operators. An Operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables.
Java Operators are classified into a number of related categories as shown in below.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo Division
Output:
2) Relational Operators
We often compare two quantities, and depending on their relation, take certain decisions.
These comparisons can be done with the help of relational operators. An expression
containing a relational operator is termed as a Relational Expression. The value of relational
expression is either TRUE or FALSE.
The list of operators as shown in below
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Table: Relational Operators
A simple relational expression contains only one relational operator and is of the following
form.
Syntax : exp1 rel_operator exp2
Example: 1 < 2
Here exp1 and exp2 are any two arithmetic expressions, which may be simple constants,
variables or combination of them. When arithmetic expressions are used on either side of a
relational operator, the arithmetic expressions will be evaluated first and then the results
compared. That is, arithmetic operators have a higher priority over relational operators.
Expression Value
3<2.5 FALSE
61< = 51 – 10 FALSE
-3> -22 TRUE
3 + 2 >= 6 FALSE
a + b == c + d TRUE **
4 * 2 != 7 TRUE
** Only if sum of values of a and b is equal to the sum of values of c and d.
The following program illustrates Relational Operators.
// Java program on Relational Operators
import java.lang.*;
class RealOpe
{
public static void main(String args[])
{
Int a=20, b=10;
System.out.println ("a =b " + (a==b));
3) Logical Operators
In addition to relational operators, java has three logical operators listed below in the table.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we want to form compound conditions by
combining two or more relations.
Example: a > b && b < c
An expression of this kind which combines two or more relational expressions is termed as a
Logical Expression or a Compound Relational Expression. Like the simple relational
expressions, a logical expression also yields a value of TRUE or FALSE, according to the truth
table AND and OR. Logical NOT operator is negate the result from true to false and vice
versa.
exp1 exp2 exp1 && exp2 exp1 || exp2
True True True True
True False False True
False True False True
False False False False
The following program illustrates Logical Operators.
// Java program on Logical Operators
import java.lang.*;
class LogicalOpe
{
public static void main(String args[])
{
int a=10, b=5, c=20;
System.out.println ("a<b && a<c is " + (a<b && a<c));
System.out.println ("a<b II a<c is " + (a<b II a<c));
System.out.println ("a<b ! a<c is " + (a<b ! a<c));
}
}
Output:
4) Assignment Operators
Assignment Operators are used to assign the value of an expression to a variable. We have
seen the usual assignment operator, ‘=’. In addition to that java has a set of Shorthand
assignment operators which are used in the form
Var op= exp;
Where var is a variable, exp is an expression and op is a java binary operator. The operator
‘op=’ is known as
shorthand assignment operator. Assignment operators are +=, -=, *=, /=, ^=, %=.
Example - 1: a += 1;
When this statement is executed, 1 is added to a, if old value of a is 10, then new
value of x is 11. This actually means;
a = a + 1;
Example - 2: x += y+4;
This actually means, x = x + (y+4);
Some of the commonly used shorthand assignment operators are listed below.
There are three advantages using the shorthand operators, they are
o What appears on the left hand side need not be repeated and therefore it becomes
easier to write.
o The statement is more concise and easier to read.
o Use of shorthand operator’s result in a more efficient code.
import java.lang.*;
class IncOpe
{
public static void main(String args[])
{
int a=15, x;
// Pre increment
System.out.println ("Pre_Increment");
x = ++a;
System.out.println ("a = " + a);
System.out.println ("x = " + x);
System.out.println ();
// Post increment
System.out.println ("Post_Increment");
x= a++;
System.out.println ("x = " + x);
System.out.println ("a = " + a);
}
}
Output:
6) Conditional Operator
The character pair ?: is a ternary operator available in java. This operator is used to
construct conditional expressions of the form
import java.lang.*;
class CondOpe
{
public static void main(String args[])
{
int a=10, b=20, x;
System.out.println ("a = " + a);
System.out.println ("b = " + b);
System.out.println ();
x = (a>b)? a : b; // logic for biggest of two numbers
System.out.println ("Biggest of two numbers is " + x);
}
}
Output:
7) Bitwise Operators
Java has numerous bitwise operators for manipulation of data at bit levels. These operators
are used to testing the bits, or shifting them to the right or left. Bitwise operators may not be
applied to float or double.
Java supports the following operators:
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
If we execute statement
c = a & b;
c = 0000 0000 0000 1000 --- 8
sides by integer expressions. The result of OR is 1 if at least one of the bit has a value
of 1; otherwise it is 0.
Example: a= 10, b= 8
If we execute statement
c = a | b;
c = 0000 0000 0000 1010 --- 10
Bitwise Exclusive OR ( ^ )
The Bitwise exclusive OR operator is represented by ( ^ ) symbol and is surrounded on
both sides by integer expressions. The result of exclusive OR is 0 if all of the bits has same
value i.e. both bits (0 , 0 or 1 ,1); otherwise it is 1.
Example: a= 10, b= 8
If we execute statement
c = a ^ b;
c = 0000 0000 0000 0010 --- 2
b. Bitwise Compliment Operator( ~ )
The compliment operator ( ~ ) also called the one’s compliment is an unary operator
and inverts all the bits represented by its operand. That is 0s become 1s and 1s
become as 0s.
Example -1: a = 10;
~ a = -11;
8) Special Operators
Java supports some special operators are as follows:
a. instanceof Operator
This operator is used to test if an object belongs to a class or not. The word instance
means an object. This operator can also be used to check if an object belongs to an
interface or not.
Example: Boolean x = emp instanceof Employee;
Here we are testing if emp is object of Employee class or not.
b. new new Operator
operator often used to create objects to classes. Objects are created on heap
memory by JVM, dynamically at runtime.
Syntax: class_name obj = new class_name();
Example: Employee emp = new Employee();
c.Member (Dot) Operator:
member operator is also called as dot operator since its symbol is a . (dot or period).
Arithmetic Expression
1. An Arithmetic expression is a combination of variables and operators arranged as per the
syntax of the language. Java can handle any complex mathematical expression.
2. Expressions are evaluated using an assignment statement of the form
variable=expression;
3. Variable is any valid java variable name. When the statement is encountered, the
expression is evaluated first and the result then replaces the previous value of the
variable on the left hand side.
Example:
x=a*b-c;
The basic evaluation procedure includes two left to right passes through the expression.
During the first pass, the high priority operators are applied and during the second pass, the
low priority operators are applied. Consider the following evaluation statement
x= a – b / 3 + c * 2 -1
when a=9, b=12 and c=3, the statement becomes x= 9 – 12 /3 + 3 *2 -1 and is evaluated as
follows.
First pass
Step1: x=9-4+3*2-1 ………………..(12/3 evaluated)
Step2: x=9-4+6-1 …………………….(3*2 evaluated)
Second pass:
Step3: x=5+6-1 ……………………….(9-4 evaluated)
Step4:x=11-1 ………………………….(5+6 evaluated)
Step5: x=10 …………………………….(11-1 evaluated)
The operators of the same precedence are evaluated either from left to right or from right to
left, depending on the level. This is known as the Associativity property of an operator.
The following table provides complex lists of operators, their precedence levels, and their
rules of association.
! Logical negation
~ Ones complement
(type) Casting
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right shift
>>> Right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Type comparison
== Equality Left to right 7
!= In equality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Operator Right to left 13
= Assignment operator Right to left 14
op= Shorthand assignment
When a program breaks the sequential flow and jumps to another part of the code, it is called
Selection or Branching. When the branching is based on a particular condition, it is known as
conditional branching. If branching takes place without any condition, it is known as
Unconditional Branching.
Java language possesses such decision making capabilities and supports the following
statements known as Control or Decision Making Statements.
1. if statement
2. switch statement
3. Conditional operator statements
The if is a powerful decision making statement and is used to control the flow of execution of
statements. It is two – way decision statement (two – way branching statement). It allows the
computer to evaluate the expression (test condition) first and depending upon the value of
the test condition is ‘true’ or ‘false’, it transfers the control to the particular statement.
1. Simple if statement
2. if-else statement
1. Simple IF Statement
// Java program to check age for vote casting by using simple if statement
Example:
//Java Program to demonstate the use of if statement.
public class IfExample
{
public static void main(String[] args)
{
int age=20; //checking the age
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
Output:
The if…else statement is an extension of simple if statement. The syntax of the if-else
statement is the following:
Syntax:
if(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
}
If the Test condition is true, then the True-block Statement(s) will be executed and then
Statement-x and so on (if any) executed in order. If the Test condition is false, False-block
Statement(s) will be executed and then Statement-x and so on (if any) executed in order. In
either case, only one of the statements True- block Statement(s) or False-block Statement(s)
is executed, but not both.
Flowchart:
Output:
Once if consists another if condition called as Nested If. When a series of decisions are
involved, we may have to use more than one if statements in nested as follows.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Flowchart:
Example:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample
{
public static void main(String[] args)
{
int age=20;
int weight=80; //Creating two variables for age and weight
if(age>=18) //applying condition on age and weight
{
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output:
3. ELSE IF ladder
A common programming construct in the java is the if-else-if ladder, which is often also called
the if- else-if staircase because of its appearance.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
This construct is known as the ELSE IF LADDER. The conditions are evaluated from the top of
the ladder. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default-statement
will be executed.
Flow chart:
Example:
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
Else
{
System.out.println("Invalid!");
}
}
}
Output:
2).SWITCH Statement
Java provides a Multi-Way Branch decision statement known as switch. The switch statement
tests the value of a given variable (or expression) against a list of case values and when a
match is found, the block of statements associated with that case are executed.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
The expression is an integer expression (or) characters. value-1, value-2,…are constants and
are known as case labels. Each of these values should be unique within a switch statement.
block-1, block-2,.. are statement lists and may contain zero or more statements. There is no
need to put braces around these blocks but it is important to note that case labels end with a
colon (:).
When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2,… if match is found, then the block of statements that follows the case
are executed.
The break statement at the end of each block signals the end of a particular case and causes
an exit from the switch statement, transferring the control to the statement-x following the
switch.
Flow chart:
Example:
//Example Program to print days of the week using Switch statements?
class WeekDays
{
public static void main(String s[])
{
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Noweekday");
break;
}
}
}
Output:
First the compiler evaluates the expression1 if it is true expression 2 will be executed by ignoring
the expression 3 i.e, expression 2 will become the resultant value for the entire expression. If the
expression 1 is false expression 3 will be executed by ignoring expression 2 i.e, expression 3 will
become the resultant value of the entire expression.
Example:
A Program loop consists of two segments, one known as control statement and other known as
body of the loop. The control statement tests certain condition and then directs the repeated
execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure may be
classified either as the Entry-Controlled Loop (or) Exit Controlled Loop.
In Exit Controlled Loop, the test condition is performed at the end of the body of the loop and
therefore the body is executed unconditionally for the first time. The body of the loop is
executed till the test condition is true.
1. while construct
2. do construct
3. for construct
Now we are discussing features and applications of these looping statements.
1. WHILE Statement
The while is an Entry Controlled Loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true, the body is executed once again. This process
is repeated until the test condition returns a false value and the control are transferred out of
the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements. It is good practice to use braces even if the body has only one
statement.
The basic format of the while statement is as follows;
Syntax:
while(condition){
//code to be executed
}
Flow chart:
Output:
2. DO..WHILE Statement
On reaching the do statement, the program proceeds to execute the body of the loop first. At
the end of the loop, the test condition in the while statement is evaluated. If the condition is
true, the program continues to evaluate the body of the loop once again. This process
continues as long as the condition is true. When the condition is false, the loop will be
terminated.
Since the test condition is evaluated at the bottom of the loop, the do…while constructs
provides an Exit- Controlled Loop and therefore the body of the loop is always executed at
least once.
The following is the syntax for the do statement;
do{
//code to be executed
}while(condition);
Flow Chart:
The body of the loop executed first time and display “i” value and “welcome to while loop”
then “i”
value incremented inside the loop and checks while loop. do block executed 5 number of
times from i = 1…5.
While Do…while
It is a looping construct that will It is a looping construct that will
execute execute at least once
only if the test condition is true. even if the test condition is false.
It is entry controlled loop. It is an exit controlled loop.
It is generally used for It is typically used for implementing
menu based
implementing common looping
programs where the menu is
situations.
required to be printed at least
once.
3. FOR Statement(LOOP)
The for loop is another entry controlled loop that provides a more concise loop control
structure. The general form of the loop is as follows.
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
1. Initialization:
It is the initial condition which is executed once when the loop starts. Here, we can initialize
the variable, or we can use an already initialized variable. It is an optional condition.
2. Condition:
It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false.
3. Statement:
The statement of the loop is executed each time until the second condition is false.
4. Increment/Decrement:
Syntax:
Initialization of the variable is done first, using assignment statements such as i=1 and
count=0. The variables i and count are known as loop-control variables.
The value of the control variable is tested using the test condition. If the test condition is true,
the body of the loop is executed; otherwise the loop is terminated.
When the body of the loop is executed, the control is transfer back to the for statement after
evaluating the last statement in the loop. Now, the control variable is incremented (or)
decrement.
Consider the following segment of a program
……………
……………
int x;
for(x=0; x<=9; x++)
{
System.out.println(x + “: Welcome to For loop”);
}
……………………..
This for loop is executed 10 times and prints the digits 0 to 9 and Welcome to For loop 10 times.
The for loop has several capabilities that are not found in other loop constructs. They are
1. More than one variable can be initialized at a time in the for statement. The statements
Sp=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)
Note that the initialization section has two parts p=1 and n=0 are separated by comma.
2. Like the initialization section, the increment section may also have more than one part. For
example
for(n=1,m=50 ; n<=m ; n++,m--)
3. The test condition may have any compound relation and the testing need not be limited only
to the control variable. Consider the following
sum=0;
for(i=1; i<20 && sum<100; i++)
{
………………
……………..
}
4. Another unique aspect of for loop is that one or more sections can be omitted, if necessary.
However the semicolons separating the sections must remain. Consider the following example
…………..
………….
m=5;
for( ; m!=100 ; )
{
System.out.println(m);
m=m+5;
}
………….
………….
5. We can also set up time delay loops using the null statement as follows;
for(j=10;j<=100;j++);
This loop is executed 90 times without producing any output; it simply causes a time delay.
Notice that the body of the loop contains only a semicolon, known as empty statement.
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if
we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
Jumps in Loops
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out
of a loop.
When the break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it. The break will exit only a single
loop.
The format of break statement is simply:
break;
This statement can also be used within while, do or for loops as illustrated below.
The continue statement tells the compiler “SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITH THE NEXT ITERATION”.
The format of continue statement is simply:
continue;
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}
All streams are represented by classes in java.io (input and output) package. This package
contains a lot of classes, all of which can be classified into two basic categories: input streams
and output streams.
Keyboard is represented by a field, called in System class. When we write System.in, we are
representing a standard input device, i.e., keyboard, by default. System class is found in
java.lang (language) package and has three fields as shown below. All these fields represent
some type of stream:
1. System.in:
This represents Input Stream object, which by default represents standard input device,
i.e., keyboard.
2. System.out:
This represents PrintStream object, which by default represents standard output device,
i.e., monitor.
3. System.err:
This field also represents PrintStream object, which by default represents monitor.
But System.out is used to display normal messages and results whereas System.err is used to
display error messages.
1. Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.
In this statement, we are creating InputStreamReader object and connecting the Keyboard
(System. in) to it.
Here, we are creating BufferedReader object (br) and connecting the InputStreamReader
object (obj) to it.
In the above two steps, can be combined and rewritten in a single statement as:
3. Now, we can read the data coming from the keyboard using read() and readLine() methods
Here, the read() method reads a single character from the keyboard but it returns its ASCII
number, which is an integer. Since, this integer number cannot be stored into character type
variable ch, we should convert it into char type by writing (char) before the method as:
import java.io.*;
class Accept
{
public static void main(String args[]) throws IO Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter a character:”);
char ch= (char)br.read():
System.out.println(“You entered:” +ch);
}
}
Output:
Enter a character: A
You entered: A.
Here, readLine() method accepts a string from the keyboard and returns the string into str. In
this case, casting is not needed since readLine() is taking a string and returning the same data
type. But this method can give rise to the runtime error: IOException, which can be thrown out
without handling by using the statement:
throws IOException.
import java.io.*;
class Accept
{
public static void main(String[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a name:");
String.name br.readLine();
System.out.println("You entered: "+name);
}
}
Output:
Enter a name: Rohith
You entered: Rohith
1. First, we should accept the integer number from the keyboard as a string, using readLine() as :
2. Now, the number is in str, i.e., in form of a string. This should be converted into an int by
using parseInt() method of Integer class as :
int n = Integer.parseInt(str);
If needed, the above two statements can be combined and written as:
int n = Integer.parseInt(br.readLine());
Here, parseInt() is a static method in Integer class, so it can be called using class name as
Integer.parseInt()
import java.io.*;
class Accept
{
public static void main(String arg[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an int value:");
int num= Integer.parseInt(br.readLine());
System.out.println("You entered: "+num);
}
}
Output:
Enter an int value: 457890 You entered: 457890
float n Float.parseFloat(br.readLine());
In this statement, we are accepting a float in the form of a string using br.readLine() and then
passing the string to Float parseFloat() to convert it into float.parseFloat is a static method in
Float class.
Output:
Accepting other types of values: Similarly, we can write different statements to accept many
other data types from the keyboard as follows:
byte n = Byte.parseByte(br.readLine());
short n=Short.parseShort(br.readLine());
long n=Long.parseLong(br.readLine())
boolean n=boolean.parseBoolean(br.readLine())
1. First receive a string str from the keyboard, which contains different types of inputs.
Assume that the inputs are separated by commas.
2. Pass this string str to StringTokenizer object, so that it will be broken into pieces wherever a
comma is found. These tokens will be stored in StringTokenizer object st.
In the above statement, str is the string which is split into tokens and which represents the
character from where to split the string. This comma is also called delimiter. Suppose we want
to split the string where a space is found, we can use a space as delimeter as:
3. Collect the individual tokens from st using nextToken() method of StringTokenizer class.
These individual tokens represent the different types of inputs given. These tokens can be
converted into corresponding data types and can be used in the program.
import java.io.*;
import java.util.*;
class Different
{
public static void main(String args[])
{
String str= br.readLine();
StringTokenizer st = new StringTokenizer(str, ",");
String s1= st.nextToken();
String s2= st.nextToken();
s1=s1trim();
$2-$2.trim():
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(s2);
System.out.println("Result of additon:" + (n1+n2));
System.out.println("Result of subtraction: "+ (n1-n2));
System.out.println("Result of multiplication:" + (n1*n2));
Output:
Method Use
next() To read a string
nextByte() To read byte value
nextInt() To read integer balue
nextFloat() To read floating value
nextLong() To read long value
nextDouble() To read double value
Program: To read different types of data separated by space, from the keyboard using the Scanner
class.
import java.util.Scanner;
class Examplel
{
public static void main(String arg[])
{
System.out.print("Enter id name sal: ");
Scanner s=new Scanner(System.in);
int id=s.nextInt());
String name=s.next();
float sal= s.nextFloat();
System.out.println("Id="+ id);
System.out.println("Name="+ name);
System.out.println("Sal" + sal);
}
}
Output:
This method returns a string that contains the formatted output which can be processed and
used as the programmer wants it.
Output:
class Example2
{
public static void main(String arg[])
{
int i=65;
String s ="Hai";
char ch = 'A':
String str=String.format("i-%d %ns=%s%nch=%c", i, s, ch);
System.out.println(str);
}
}
Output:
I=65
Hai
ch-A
We know that System.out returns PrintStream class object, so to call the printf() method, we can
use: System.out.printf().
Character Meaning
%s String
%c Char
%d Decimal integer
%f Float number
%o Octal number
%b, %B Boolean value
%x, %X Hexadecimal number
%e, %E Number is scientific notation
%n New line character
class Example3
{
public static void main(String arg[])
{
String s1="Hello";
int n=65;
float f=15.1234f;
System.out.printf("String=%s%n num=%d%n hexa decimal =%x%n float=%f", s1, n, n, f);
}
}
Output:
String=Hello
Num=65
hexa decimal=41
float=15.123400.
Arrays
1. Arrays
2. Strings
3. Vectors
4. Wrapper Classes
Arrays Definition
“An array is a collection of contiguous (or) similar data items with same name and same data
type”.
For example we can define an array name regno to represent a set of register numbers of a
class. A particular value is indicated by writing a number called index number or subscript in
brackets after the array name.
All the elements in the array are of the same data type. Array elements are accessed
individually using the index. The index value starts with 0 (zero). An array can have one (or)
more dimensions. Arrays can be any variable type.
Note that an array always starts from its index values “0” to “n-1”. Suppose we want to
access fifth element from the above elements, then we have to use 4th index because 5th
element stored in 4th index. The no. of elements and types are identified by its subscripts.
Array Types:
An array can be classified in two types in java.
Creating an array
Arrays must be declared and created in the computer memory before they are used.
Creation of an array involves three steps:
1) Declaring of an array.
2) Initialization of an array.
3) Accessing of an array.
1)Declaration of array
An array must be declared before they are used, so the computer can allocate space for
them in memory. The general syntax of one-dimensional array is.
Here, type is data type of the array and array-name is any valid identifier.
Examples:
int marks[];
float []average;
After declaring an array, we need to create it in memory. Java allows us to create arrays using
new operator only.
Here, new – keyword used to allocate memory for the array, and size – number of elements
that the array would hold.
Examples:
marks = new int[5];
Now the variable marks refers to 5 integers values. We can combine both the steps
declaration and creation into a single one as shown below:
type <array-name> [ ] = new type [size];
Example:
int number [ ] = new int [5];
2)Initialization of an Arrays
Assigning the values to an array is known as Initialization. This is done using array subscript
because; every array element is accessed using its index number.
Example:
int marks[ ] = {10, 20, 30, 40};
marks [0]= 10;
marks [1]= 20;
marks [2} = 30;
Note that array starts the subscript with 0 and ends with a value one less than the size
specified. i.e. 0 to ( n- 1)
Example:
Example:
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}}
Output:
Array Length
In java, all arrays store the allocated size in a variable named length. We can obtain the
length of the array using the length. This information will be useful in the manipulation of
arrays when their size is required.
Example:
int number[] = {10, 20, 30, 40, 50};
int n = number.length; //Here n value is 5
Two-Dimensional Array
An array use two subscripts of two index are called two dimensional array. A two dimensional
array represents several rows and columns of data. For example, the marks obtained by a group
of students in different subjects can be represented by a 2D array.
1)Declaration of 2D array
A two dimensional array is declared as shown below:
‘a’ is a two dimensional array which can hold 12 elements in 3 rows and 4 columns.
2)Initialization of an 2D Array
Initialization of two dimensional array elements is done using the index values:
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
The following diagram is a representation of a two-dimensional array in memory.
We can directly initialize the elements of a two dimensional array as shown below:
3)Accessing of an 2D Array
Example:
//Java Program to demonstrate the addition of two matrices in Java
class Testarray5{
public static void main(String args[])
{ //creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3]; //adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
}
}
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
System.out.print(c[i][j]+" ");
}
System.out.println(); //new line
}
}}
Output:
Three dimensional array are also called space array. In this space rows and columns are
taken. Three dimensional array will required subscript i.e., three pairs of square brackets.
1. Declare 3D
2. Initialization of 3D
You can initialize a three dimensional array in similar way like a two dimensional array.
Example:
int ar[2][3][4]={{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{13,14,15,16},{17,18,19,20},{21,22,23,24}};
3D contains array contains 3 subscripts, we will use three for loops to access the elements.
Example:
Class ThreeD
{
Public static void main(String args[])
{
int a[][][]= new int [2][2][2],I,j,k,m=1;
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
for (k=0;k<2;k++0
{
a[i][j][k]=m;
m++;
}
}
System.out.println(“3D is”);
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
for (k=0;k<2;k++0
{
System.out.println(a[i][j][k]+“ ”);
}
System.out.println();
}
System.out.println();
}
}
}
Output:
We can write Java programs that can received and use the arguments provided in the
command line. The signature of the main() method.
Here, args is declared as an array of strings (known as string objects). Any arguments provided
in the command line (at the time of execution) are passed to the array args as its elements. We
can simply access the array element and use them in the program as we wish.
This command line contains Two arguments. These are assigned to the array args as follows:
FORTRAN→ args[1]
C++ →args[2]
Java → args[3]
class Sample
{
public static void main(String args[])
{
int i;
System.out.println ("command line arguments are ...");
for (i=0; i< args.length; i++)
{
System.out.println (args[i]);
}
}
}
Compile and Run the program with command line as follows: javac Sample .java
cpp
java
UNIT-II, STRINGS
Q). What is a String? How to creating strings in java?
1. We can create a string just by assigning a group of characters to a string type variable:
String s="Hello";
2. We can create an object to String class by allocating memory using new operator. This is just
like creating an object to any class, like given here:
String s= new String("Hello");
Here, we are doing two things. First, we are creating object using new operator.
3. The third way of creating the strings is by converting the character arrays into strings. Let us
take a character type array: arr[] with some characters, as :
Now the String object 's' contains the string: "chairs". This means all the characters of the array
are copied into the string. If we do not want all the characters of the array into the string, then we
can also mention which characters we need, as:
Here, starting from 2nd character a total of 3 characters are copied into the strings.
Immutability of strings:
Mutable:- Mutable objects are those objects whose contents can be modified.
Immutable:- Immutable objects are those objects, once created cannot be modified.
And String class objects are immutable. Let us take a program to understand whether the String
objects are immutable or not.
class Test
{
public static void main(String arg[])
{
string s1="data";
string s2=new string("base");
s1=s1 + s2
System.out.println(s1);
}
}
Output:
C:> javac Test.java
C:\>java Test
Database
In java Strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class. A java string is not a
character array and not a NULL terminated. String may be declared and created as follows
Syntax:
String Methods:
The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks. Some most commonly used string methods.
Method Call Task Performed
s2 = s1.toLowerCase(); Converts the String s1 to all lowercase
s2 = s1.toUpperCase(); Converts the String s1 to all Uppercase
s2 = s1.replace(‘x’, ‘y’); Replace all appearances of x with y
s2 = s1.trim(); Remove white spaces at the beginning and
end of String s1
s1.equals(s2) Returns ‘true‘ if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns ‘true‘ if s1=s2, ignoring the case of
characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2
s1.compareToIgnoreCase(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2, ignoring the case of
characters
s1.concat(s2) Concatenates s1 and s2
s1.subString(n) Gives the substring starting from nth character
s1.subString(n, m) Gives the substring starting from n th character
up to m
(excluding m)
s1.startsWith(‘x’) Returns true if s1 starts with ‘x’
s1.endsWith(‘x’) Returns true if s1 ends with ‘x’
System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.replace('I', 'i'));
System.out.println(s1.trim());
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.length());
System.out.println(s1.charAt(3));
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s1.concat(s2));
System.out.println(s2.substring(4));
System.out.println(s2.substring(0,6));
System.out.println(s2.startsWith(" "));
System.out.println(s2.endsWith(" "));
}
Output:
StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Method Task
s1.setCharAt(n, ‘x‘) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n, s2) Inserts the string s2 at the position n of the string s1
In java we can’t use (>,<,>=,<=) symbols for string comparison, We can compare String in Java on
the basis of content and reference. It is used in authentication.
1. equals() Method
2. Using == Operator
3. compareTo() Method
1) equals() Method
The String class equals() method compares the original content of the string. It compares values of
string for equality. String class provides the following two methods:
Teststringcomparison1.java
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3=new String("Virat");
String s4="Kohli";
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true
System.out.println(s1.equals(s4)); //false
}
}
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
2) == operator
eststringcomparison3.java
class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3=new String("Virat");
System.out.println(s1==s2); //true (because both refer to same instance)
System.out.println(s1==s3); //false(because s3 refers to instance )
}
}
3) compareTo() method
The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.
Teststringcomparison4.java
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Virat";
String s2="Virat";
String s3="Kohli";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}
Introduction to OOPs
Object-Oriented Programming
Definition:
Object-Oriented Programming is an approach that provides a way of modularizing programs
by creating partitioned memory area for both data and methods that can be used as
templates for creating copies of such modules on demand.
Object-Oriented Paradigm
The major objective of Object-Oriented approach is to eliminate some of the Drawbacks
encountered in the Procedural approach. OOP treats data as critical element in the program
development and does not allow the data to flow freely around the system. “It ties data more
closely to the methods that operate on it and protects it from accidental modification from
outside functions”.
The data of an object can be accessed only by the methods associated with the object. However
methods of one object can access the methods of other objects.
OOP allows us to decompose a problem into a number of entities called Objects. The
combination of data and methods make up an object.
1. Object
2. Class
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing
1. Object
Objects are the real word entity (or) runtime entities in an object-oriented system. Objects are
closely matched with real world objects. Object may represent a person (or) a place, (or) table
of data (or) any item that can be handled by program. In order to store the data for the data
members of the class, we must create an object.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Definitions of an Object
Instance of a class is known as an object.
Class variable is known as an object.
Real world entities are called as Objects.
The following figure is the representation of an object
Object: student
Data:
name;
regdno;
Methods:
marks();
total();
avg();
result();
2. Class
“Collection of objects is called class”. It is a logical entity. A class is model for an object, and it is
a blue print of an object.
Once class has been defined, we can create any number of objects belongs to that class. Each
class is associated with data and methods.
For example mango, apple and banana are objects of fruit class. The syntax used to create
object is no different than the syntax used to create an integer object in C.
If fruit has been defined as a class, then the statement
fruit mango; // will create an object mango belonging to the class fruit.
Note: Any JAVA program can be developed with respect to Class only i.e., without Class there
is no JAVA program.
(Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes)
Ex:- While driving a car, you don’t have to concern with its internal working details, here we
need to concern about the parts like Steering, wheels, accelerators, Breaks, etc.
Data Encapsulation
The wrapping up (Combining) of data and methods into a single unit is known as
Encapsulation. Encapsulation is the most important feature of a class.
The data is not accessible to the outside world, but this Encapsulation provides direct access to
data. By this direct access the program is called data hiding or information hiding.
AKNU
COURSES
COLLEGE-2 COLLEGE-3
COLLEGE-1
COURSES COURSES
COURSES
Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no- 77
UG PG UG PG UG PG
COURSES COURSES COURSES COURSE COURSE COURSES
S S
Fig. Inheritance
5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, it means the
ability to take more than one form is called Polymorphism.
The word Polymorphism means combining the two words i.e Poly & Morphism, poly means
many, morphism means availability.
For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation. It supports two concepts.
a. Operator Overloading:
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading i.e. a single operator can perform different operations.
Ex. If the operands are two numbers then the operator is sum i.e., 2 + 3= 5.
If the operands are strings then the operator is concatenation.
b. Function Overloading:
A single function name is used to perform different types of tasks is known as function
overloading. The following is an example for polymorphism concept.
Fig. Polymorphism
6. Dynamic Binding
Binding refers if the code is associated with class function, we can’t identify that until the code
has been executed in run time, it is also called Dynamic binding. It is associated with the
polymorphism and inheritance.
7. Message Passing
The OOP’s consists of a set of objects that communicate with each other. Objects
communicate with one to another by sending and receiving information.
Exchanging the data between multiple objects is known as Message Passing. Objects
communicate with one another by sending and receiving information much the same way as
people pass message to one another.
Applications of OOP
OOPS applications are very important because of it is used in many areas like windows has
a more popular application in the OOPS. It is designed by interface with oops. The number of
windows systems developed by oops technique, like business system and commercial systems, etc
The following are some of areas of Object Oriented Programming
Real-Time systems
Simulation and modeling
Object oriented databases
Hypertext, hypermedia and expert text.
Parallel programming.
AI and expert systems.
Designing supports
Cam//Cad
Neural networks and parallel programming.
Decision support and office automation systems.
1. Procedural programming mainly focuses on procedures (or) functions. Less attention is given
to the data.
2. The data and functions are separate from each other.
3. Global data is freely moving and is shared among various functions. Thus, it becomes difficult
for programmers to identify and fix issues in a program that originate due to incorrect data
handling.
4. Changes in data types need to be carried out manually all over the program and in the
functions using the same data type.
5. Limited and difficult code reusability.
6. It does not model real-world entities (e.g., car, table, bank account, loan) very well where we
as a human being, perceive everything as an object.
7. The procedural programming approach does not work well for large and complex systems.
Classes, Objects
1. Defining a Class
“The process of binding the ‘data members’ and ‘member functions’ into a single unit is
called as a class”. In other words a class is a user defined data type. Once the class type has
been defined, we can create “variables” of that type. In java these variables are termed as
instances of class, which are the actual objects.
The basic form of a class definition is as follows;
[fields declaration;]
[methods declaration]
}
Here, sub_classname and super_clsname are any valid java identifiers. The keyword extends
indicates that the properties of the super_classname class are extended to the sub_classname
class. This concept is called as Inheritance.
Everything inside the square brackets is optional. This means that the following would be a
valid class definition.
class <class-name>
{
Here, the body of the class is empty; this does not contain any properties and therefore cannot
do anything.
We can declare the instance variables exactly the same way as we declare the local variables.
Syntax:
type < variable1,…… >
Example:
class Rectangle
{
int length; // Instance variable declaration
int width; // Instance variable declaration
}
The class Rectangle contains two integer type instance variables (length, width). Here, these
variables are only declared and therefore no storage space has been created in the memory.
Instance variables are also known as Member Variables.
length=x;
width=y;
}
(Note: In class we will have many numbers of variables and methods. Instance variables and methods in classes are accessible
by all the methods in the class but a method cannot access the variables declared in other methods.
Example:
class Check
{
int x;
void method1()
{
int y;
x=10; //legal
y=x; //legal
}
void method2()
{
int z;
x=20; //legal
z=10; //legal
y=5; //illegal
method1(); //legal
}
} )
OBJECT
1. Creating of an Object:
Object is a real word entity. “An instance of a class is called as an Object”. An object in java
is a block of memory that contains space to store all the member variables. Crating an
object is also referred to as Instantiating an object.
Objects in java are created using the new operator. The new operator creates an object for
the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.
The first statement declares a variable to hold the object reference(R1) and the second
one actually creates an object and assigns the object reference to the variable R1. The
variable R1 is now an object of the Rectangle class. Both statements can be combined
into one as shown below.
The method Rectangle( ) is the Default Constructor of the class. We can create any
number of objects of Rectangle.
Example:
Each object has its own copy of the instance variable of its class. This means if any changes in
variables of one object that cannot effect on the other variables.
It is also possible to create two or more references to the same object as shown in below.
1. Here, object_name is the name of the object and variable_name is the name of the
instance variable inside the object.
3. parameter-list is separated by comma, and that must match in type and number with
the parameter list of the method name declared in the class.
The instance variables of the Rectangle class may be accessed and assigned values as
follows:
R1.length = 10;
R1.width = 20;
R2.length = 30;
R2.width = 40;
Note that the two objects R1 and R2 store different values as shown below:
In our case getData() method can be used to do this. We can call this getData() method by
using objects R1/R2 as follows:
R1.getData(1,2); // calls getData method and pass values 1, 2 to parameters x, y of the method getData
R2.getData(10,20);//calls getData method and pass values 10, 20 to parameters x, y of the method getData
The following is the program that illustrates the concepts discussed so far.
import java.lang.*;
class Rectangle // Declaration of class
{
int len, wid; // Declaration of instance variables
Output:
Constructors in Java
A constructor in Java is similar to a method, which is invoked when an object of the class is
created. Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type.
For example,
Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return
type.
It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
class Main
{
private String name;
Main() // constructor
{
System.out.println("Constructor Called:");
name = "Programiz";
}
Output:
Constructor Called:
The name is Programiz
<class_name>
()
{
}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
//Java Program to create and call a default constructor
class Bike
{
Bike() //creating a default constructor
{
System.out.println("Bike is created");
}
public static void main(String args[]) //main method
{
Bike1 b=new Bike1(); //calling a default constructor
}
}
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Main
{
String lang;
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
3) They are arranged in a way that each constructor performs a different task.
4) They are differentiated by the compiler by the number of parameters in the list and
their types.
name = s;
}
Student(int i, String s, int a) //creating three arg constructor
{
id = i;
name = s;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Examplel: A program to initialize the Person class instance variables in Demo class.
//Initializing the instance variables
class Person
{
public String name; //public Instance variable
void disp()
{
System.out.println("Hello lam " + name);
System.out.println("My age is " + age);
}
Output:
Hello lam Raju
My age is 5
The access modifiers in Java specify the accessibility (or) scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1.Private:
The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2.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.
3.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.
4.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.
There are many differences between constructors and methods. They are given below.
Methods in JAVA
Methods must be declared inside the body of the class but immediately after the declaration of
instance variables.
Declaration:
Here, method name represents the name given to the method. After the method name, we
write some variables in the simple braces. These variables are called parameters. Method
parameters are useful to receive data from outside into the method.
Example
int sqrt (int num)
Here, sqrt is the method name, num is method parameter that represents that this method
accepts a int type value.
2. Method Body:
Below the method header, we should write the method body Method body consists of a group
of statements which contains logic to perform the task. Method body can be written in the
following format:
int method_name(parameter_list)
{
//statements;
}
For example, we want to write a method that calculates sum of two numbers. It may contain
the body, as shown here:
Program: Write a program for a method with two parameters and return type.
class Sample
{
int sum(int num1, int num2)
{
int res=num1 + num2;
return res; //return result
}
}
class Methods
{
public static void main(String args[])
{
Sample s = new Sample();
int x=s.sum (10, 22);
System.out.println("Sum="+x);
}
}
Output:
C:\>javac Methods.java
C:\> java Methods
Static Members
The variables and methods in the class are called as instance variables and instance methods.
This is because every time the class is instantiated, a new copy of each of them is created.
They are accessed using the objects (with dot operator).
Let us assume that we want to define a member that is common to all the objects and
accessed without using particular object.
i.e. the member belongs to the class as a whole rather than the objects created from the class.
Such members can be defined as follows:
The members that are declared with the keyword static are called as static members. Since
these members are associated with the class itself rather than individual objects, the static
variables and static methods are often referred to a class variables and class methods.
Static variable:
static method:
Syntax :
<class-name>.<variable-name>;
<class-name>.<method-name>;.
Note: main () method is static, since it must be accessible for an application to run, before any
instantiation takes place.
The keyword 'this': 'this' is a keyword that refers to the object of the class where it is used. In
other words, 'this' refers to the object of the present class. Generally, we write instance
variables, constructors and methods in a class.
All these members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object, as shown in the Figure. This default reference
is nothing but 'this'. So 'this' can refer to all the things of the present object.
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
Instance methods: Instance methods are the methods which act upon the instance variables. To call
the instance methods, object is needed, since the instance variables are contained in the object. We
call the instance methods by using objectname.methodname(). The specialty of instance methods is
that they can access not only instance variables but also static variables directly.
Accessor methods are the methods that simply access or read the instance variabiles. They do not
modify the instance variables.
Mutator methods not only access the instance variables but also modify them.
class Person
{
private String name;
private int age;
public void setName(String name) //mutator methods to store data
{
this.name =name;
}
public void setAge(int age)
{
this.age= age;
}
public void setAge(int age)
{
this.age=age;
}
public String getName() // Accessor metods to read data
{
return name;
}
public int getAge()
{
return age();
}
}
class Methhods
{
public static void main(String args[])
{
Person p1=new Person();
p1.setName(“Raju”);
p1.setAge(20);
System.out.prinntln(“Name=”+p1.getName());
System.out.prinntln(“Age=”+p1.getAge());
}
}
Output:
Primitive data types (or) fundamental data types represent single entities (or) single values. For
example, char, byte, short, int, long, float, double and boolean are called primitive data types,
because they store single values. They are passed to methods by value.
This means when we pass primitive data types to methods, a copy of those will be passed to
methods. Therefore, any changes made to them inside the method will not affect them outside the
method. In the following program, we pass two integer numbers 10 and 20 to the swap method. Let
us display the output to know whether they are interchanged or not.
Program:
class check
{
vold swap (int n1, int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
}
class PassPrimitive
{
public static void main(String args[])
{
int n1= 10, n2=20;
check ck= new check ();
System.out.println(n1+ " " +n2);
ck.swap(n1, n2);
System.out.println(n1+" " +n2);
}
}
Output:
C> javac PassPrimitive.java
C:>java PassPrimitive
10 20
10 20
Here, myMethod() is a method that accepts Employee class object. So reference of Employee
class is declared as parameter in myMethod()). After doing some processing on the object, if it
returns the same object, we can write a statement like:
return obj;
Program : Write a program to interchange the values inside an object, since the same object data is
modified, we can see the data has been interchanged. Interchanging the values should be done in a
single object
class Employee
{
int id1, id2;
Employee (int id1, int id2)
{
this.id1 = id1;
this.id2=id2;
}
}
class Check
{
value swap(Employee obj)
{
int temp;
temp=obj.id1;
obj.id1 = obj.id2;
obj.id2=temp;
}
}
class PassObjects
{
public static void main(String args[])
{
Employee obj1 = new Employee(10, 20);
Check obj = new check();
System.out.println(obj1.id1+""+obj1.id2);
obj.swap(obj1);
System.out.println(obj1.id 1+"\t"+obj1.id2);
}
}
Output:
C: javac Pass Objects.java
Objects Pass Objects
10 20
2019
Just like the objects are passed to methods, it is also Possible to pass arrays to methods and return
arrays from methods. In this case, an array name should be understood as an object reference. For
example,
int [] myMethod(int arr[])
This is the way, we can pass a one dimensional array 'arr' to 'myMethod()'. We can also return a one
dimensional array of int type as shown in the preceeding statement.
int[] [] myMethod(int arr[][])
Here, we are passing and returning a two dimensional array of int type.
Example:
class Array
{
public int[] sortArr (int a [], int len)
{
for(i=0; i<len; i++)
for (j=i+1; j<len;j++)
{
if (a[i]>a[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public static void main(String args[])
{
int a[]={10, 40, 30, 20, 50);
int b[]=obj.sortln(a,a.lengt);
System.out.println("sorted array elements are");
for(int i=0;i<b.length;i++)
System.out.println(b[i] +’’);
}
}
Output:
sorted array elements are
10 20 30 40 50
A static block is a block of statement declared as “static”, some thing like tis:
static
{
Statement;
}
JVM execute a static block on a highest priority basis. This means JVM first goes to static block even
before it looks for the main() method in the program.
Example:
Class Test
{
Static
{
System.out.println(“Static block”);
}
public static void main(String args[])
{
System.out.println(“Static method”);
}
}
Output:
class Recursion
{
static long factorial(int num)
{
long result;
if (num==1)
return 1;
result =factorial (num-1)*num;
return result;
}
public static void main(String args[])
{
System.out.println("Factorial of 5:");
System.out.println(Recursion.factorial(5));
}
}
Output:
C:\>javac Recursion.java
C:\>java Recursion
Factorial of 5;
120
A factory method is a method that creates and returns an object to the class to which it belongs.
A single factory method replaces several constructors in the class by accepting different options
from the user, while creating the object.
To understand how to use a factory method, let us take an example program to calculate the
area of a circle.
class Circle
{
public static void main(String arg[])
{
final double PI = (double)22/7;
double r= 15.5; //radius
double area = Pl*r*r;
System.out.println("Area = " + area);
}
}
Output:
C:>javac Circle.java
C:\> java Circle
Area-755.0714285714286
Inheritance in Java
Inheritance in Java
It is a mechanism in which one object acquires all the properties and behaviors of a parent object. It
is an important part of OOPs (Object Oriented programming system).
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 the parent class.
Moreover, you can add new methods and fields in your current class also.
Parent (Properties)
Fig: Inheritance
The class which is giving members (variables and methods) to some other class is known as
base class / super class / parent class.
The class which is retrieving or obtaining members (variables and methods) is known as
derived class / sub class / child class.
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes. A Derived class contains its own properties (members) plus base class properties
(members).
Advantages of Inheritance
Syntax for INHERITING the features from base class to derived class:
The keyword extends signifies that the properties of the super_classname are extended to
the sub_classname.
The subclass will now contain its own variables and methods as well those of the super
class.
This kind of situation occurs when we want to add some more properties to an existing
class without actually modifying it and also improves functionality of derived class.
1. Single Inheritance
In Single Inheritance single base class is derived to a single derived class. If one child class is
inheriting the properties of the parent class without any intermediate class, then it is called as
“Single Inheritance”.
A subclass acquires the properties from the super class is also called as “Single inheritance”. For
example C2 class is derived from C1 class; Now C2 access all the properties of C1 and itself. It is
shown in below.
Fig: Single Inheritance
Example:
class c1
{
---------
}
class c2 extends c1
{
---------
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
2. Multilevel Inheritance
Multilevel Inheritance contains one base class and one derived class, and multiple
intermediate base classes.
A Child class(Derived class) acquire the properties of Parent class(intermediate class), and
Parent class(intermediate class) acquire the properties of grandparent class(Base class). It is
also called multilevel inheritance.
For example C2 class is derived from C1, C3 class is derived C2, and C4 class is derived C3; Now
C2 access C1 class members and itself only, C3 access C2 and C1 class members and itself only,
and C4 can access C3,C2,C1class members and itself only. It is shown in below.
Example:
class c1
class Animal {
---------
{
---------
void eat() }
{ class c2 extends c1
System.out.println("eating..."); {
} ---------
---------
} }
class c3 extends c2
class Dog extends Animal{ {
void bark() ---------
{ ---------
}
System.out.println("barking..."); class c4 extends c3
} {
} ---------
---------
class BabyDog extends Dog }
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
3. Hierarchical Inheritance
Hierarchical Inheritance contains a single base class and multiple derived classes. In hierarchical
inheritance multiple subclasses acquire the properties of only single super class, it is also called
as hierarchical inheritance.
For example C2, C3, C4, classes are derived from C1 class; Now C2, C3, C4 classes can access C1
class members and itself only. It is shown in below.
Syntax:
class c1
{
---------
---------
}
class c2 extends c1
{
---------
---------
}
class c3 extends c1
{
---------
---------
}
class c4 extends c1
{
---------
---------
}
Example:
class Animal
{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{System.out.println("meowing...");}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
4. Multiple Inheritance
Multiple Inheritance contains multiple base classes and a single derived class. For example C4
class is derived from C1, C2, and C3 Base classes; Now C4 can access C1, C2, C3 members and
itself. It is shown in below.
Super keyword
Subclass Constructor (‘super’ keyword)
A Subclass constructor is used to construct the instance variables of both the subclass and the
super class. The subclass constructor uses the keyword super to invoke the constructor method
of the super class. The super keyword is used subject to the following conditions.
The call to super class constructor must appear as the first statement within the
subclass constructor.
The parameters in the super call must match the order and type of the instance
variables declared in the super class.
The Protected Specifier: The private members of the super class are not available to sub classes
directly. But sometimes, there may be a need to access the data of super class in the sub class.
For this purpose, protected specifier is used. Protected is commonly used in super class to make the
members of the super class available directly in its sub classes.
Example: Program to understand private members are not accessible in subclass, but protected
members are available in sub class.
class Access
{
private int a;
protected int b;
}
class Test
{
public static void main(String args[])
{
Subs= new Sub ();
s.get();
}
}
Output:
Q). Polymorphism
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can perform a
single action in different ways.
System.out.println (a+b) ;
Java compiler decides the data type of the result of the expression a+b depending on the data
types of a and b. If a and b are int type, then a + b will also be taken as int type. If a and b are float
type variables, then a+b will be taken as float type. If a is int and b is float, then the compiler
converts a also into float and then sum is found. Thus, the result a + b is exhibiting polymorphic
nature. It may exist as an int or as a float or as some other data type depending on the context.
This is also called 'Coercion'.
Types of Polymorphism
There are two types of polymorphism in Java:
1. Static Polymorphism (Compile Time Polymorphism)
2. Dynamic Polymorphism (Run Time Polymorphism)
1. Static Polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism. Polymorphism that
is resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.
1. Method overloading :
The process of defining methods with same name but with different functionalities is termed
method overloading.
To create an overloaded method, several different method definitions are created in the class with
the same name but with different parameter lists. Java differentiates overloaded methods based
on the number and type of parameters and not on the return type of the method.
A compiler error would occur when two methods with the same name and same parameter list
but different return types are created.
class MethodOverload
{
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 108
Output
2. Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a
method is called, the method call is bound to the method body at the time of running the
program, dynamically. In this case, Java compiler does not know which method is called at the
time of compilation. Only JVM knows at runtime which method is to be executed. Hence, this is
also called 'runtime polymorphism' or 'dynamic binding'.
1. Method Overriding:
Method overriding means both the super class method and sub class methods having the same
name, same signature. i.e., number of parameters and types of parameters should be same.
Method overriding is allowed only in inheritance. Method overriding is an example of
polymorphism.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
void run() //defining a method
{System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle
{
void run() //defining the same method as in the parent class
{System.out.println("Bike is running safely");}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
Output:
Bike is running safely
Bike is running safely
A static method is a method, one single copy in memory is shared by all the objects of the class. Static
methods belong to the class rather than to the objects. So they are also called class methods. When
static methods are overloaded or overridden, since they do not depend on the objects, the Java
compiler need not wait till the objects are created to understand which method is called.
Program: Write a program to use super class reference to call the calculate () method.
//static polymorphism
class One
{
static void calculate (double x)
{
system.out.println("square value="+(x*x));
}
}
class Two extends One
{
static void calculate (double x)
{
System.out.println("square root="+ Math.sqrt(x));
}
}
class Poly
{
public static void main(String args[])
{
one o= new Two ();
o.calculate (25);
}
}
Output:
Private methods are the methods which are declared by using the access specifier 'private. This
method is not to be available outside the class. So other programmers cannot access the private
methods.
Even private methods are not available in the sub_classes. This means there is no possibility to
override the private methods of the super_class in its sub_classes. So only method overloading is
possible in case of private methods.
Example:
class Hello
{
private void call ()
{
system.out.println (“Hello world!”);
}
public static void main (String args [])
{
Hello h1=new Hello();
h1.call ();
}
}
Here in this code we have a private method -call() and we try to access this method under the main
method which lies in the same class Hello. Hence we get the desired output.
But if you try to call this private method - call() in some other class then you won't get the desired
output. Because when you write a method as private then it's accessibility is limited to that
particular class only.
The Specifier final is used to finalize classes, methods and variables. Finalizing a thing effectively
'freezes the implementation or value of that thing. More specifically, here is how final works with
classes, variables and methods, respectively:
1. When the Specifier final is applied to a class, it means that the class cannot be inherited.
2. When final is applied to a variable, it means that the variable is constant.
3. When final is applied to a method in a class, it means that the method cannot be overridden in
the sub-classes. .
1. Finalizing classes:
In order to finalize a class, the Specifier final is added to the class definition. Typically, it is added
after protection Specifiers such as private (or) public. This is done as shown below:
For better efficiency. Final classes allow programmers to rely on instances of only that class
and optimize those instances
2. Finalizing variables:
The value of a finalized variable cannot be changed. It is then, effectively, a constant. To declare
constants in Java, final variables with initial values are used. This declaration can be done in a
program as follows:
3. Finalizing methods:
Methods that cannot be overridden are known as finalized methods. The implementations of
final methods cannot be redefined in sub-classes. The syntax for declaring a method final is the
following.
It is possible to convert one primitive data type into another primitive data type. This is done in
two ways, widening and narrowing. The primitive data types are classified into two types, lower
types and higher types naturally, the lower types are the types which use less memory and which
can represent lesser number of digits in the value. The higher types use more memory and can
represent more number of digits. To recognize the lower and higher types, the following diagram
is useful:
Lower ------------------------------higher
Thus, char is a lower type than int. float is a higher type than long, boolean is not included earlier,
because it cannot be converted into any other type.
Converting a lower data type into a higher data type is called wide examples:
char ch = 'A' ;
Here, we are converting char type variable 'ch' into used the cast operator by writing 'int' in the
simple. Now that ch is converted into int type, it can be is an example for widening.
int x=9500;
Here, we are converting int type variable 'x' into float. So, we wrote (float) before the variable x.
Widening is safe because there will not be any loss of data or precision or accuracy.
Converting a higher data type into a lower data type is called 'narrowing'. Take the examples:
int n=66;
Here, we are converting int type n value into char type. The value of n is 66 which is when
converted into char type represents the character 'B', since 66 is the ASCII value of 'B'. This
character is stored into ch.
The type_cast can be to its own class type or to one of its subclass or super_class types or
interfaces. There are compile-time rules and runtime rules for casting in java. There are two types
of Reference Type Casting in Java, they are:
1. Up Type_casting
2. Down Type_casting
1. Up Type_casting:
A subtype object into a supertype and this is called up Type_cast. In Java, we need not add an
explicit cast and you can assign the object directly. Compiler will understand and cast the value to
supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an
explicit cast and no issues.
2. Down Type_casting:
A supertype to a subtype is called down Type_cast. This is the mostly done cast. By doing this we
are telling the compiler that the value stored in the base object is of a super type. Then we are
asking the runtime to assign the value. Because of down Type_cast, we get access to methods of
the subtype on that object. When performing down Type_casting, that you’re well aware of the
type of object you’ll be casting.
Let's take an example, there is getObject () method that returns an object but it can be of any type
like Employee, Student etc, we can use Object class reference to refer that object. For example:
The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.
Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this
class.
public int hashCode() returns the hashcode number for this object.
public boolean equals() compares the given object to this object.
protected Object clone() creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long timeout) causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
protected void finalize() is invoked by the garbage collector before object is being
garbage collected.
An abstract method does not contain any body. It contains only the method header, So we can say it
is an incomplete method. An abstract class is a class that generally contains some abstract methods.
Both the abstract class and the abstract methods should be declared by using the key word 'abstract'.
Points to Remember
abstract class A
{
}
Abstract Methods:
A method which is declared as abstract and does not have implementation is known as an abstract
method.
abstract void printStatus(); //no method body and abstract
You have to place the abstract keyword before the method name in the method declaration.
An abstract method contains a method signature, but no method body. Instead of curly braces
an abstract method will have a semoi colon(;) at the end.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Interface in java
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 116
Interface in java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Defining Interface
An interface is like a fully abstract class, except that it cannot have any concrete method (or)
instance variables. It is a collection of abstract method declarations and constants that is static
final variables.
This means that interfaces do not specify any code to implement these methods.
Any class that implements an interface must implement all of the methods specified in that
interface.
A class can implement many interfaces but can extend only one class.
interface InterfaceName
{
variable declaration;
method declaration;
}
Here interface is a keyword and interfaceName is any valid Java variable.
Example:
interface Item
{
static final int code = 1001;
static final String name = "fan";
void display();
}
Extending Interfaces
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 117
Interfaces can also be extended as a classes. The new sub_interface will inherit all the members of
the super_interface in the manner similar to subclasses.
interface ItemConstants
{
int code = 1000;
String name = "Fan";
}
interface Item extends ItemConstants
{
void display();
}
Output:
While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the
method declared in the super interface. Instead, it is the responsibility of any class that
implements the derived interface to define all the methods.
Interfaces can have access Specifiers of public or blank, just like classes.
An interface can be defined as extending another interface, similar to class hierarchy, but there is
no base interface analogous to the Object class.
import java.io.*;
interface inter1
{
int a = 100;
final static int b = 200;
}
interface inter2 extends inter1
{
void show();
}
class interclass implements inter2
{
public void show()
{
int c = a + b;
System.out.println("Sum="+c);
}
}
class ExtendingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output :
Implementing Interfaces
Interfaces are used as "superclasses" whose properties are inherited by classes. It is, therefore,
necessary to create that inherits the given interface.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
Implementing Interface:
import java.io.*;
interface inter //interface define
{
void show();
}
class interclass implements inter // implement the interface
{
public void show()
{
System.out.println("Hello Java - Interface");
}
}
class ImplementingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output:
Java does not support multiple inheritances. This means that a class cannot extend more than one
class. Therefore, following is illegal
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A4 implements Printable, Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
PACKAGES
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 121
If we need to use classes from other programs without physically copying them into the program
under development, this can be accomplished in java by using packages a concept similar to “class
libraries” in another languages.
1. Advantages of packages:
The classes contained in the packages of other programs can be easily reused.
Two classes in two different packages can have the same name. They can be uniquely
identified by packagename.classname.
Thus a Package is a collection of classes, interfaces and sub-packages. A Sub package in turns
divides into classes, interfaces and sub-sub-packages, etc.
Types of Packages:
In java the packages are classified into two categories. They are
User-defined packages are those packages that are designed (or) created by the developer
(user) to categorize classes and packages. They are much similar to the built-in that java
offers. It can be imported into other classes and used the same as we use built-in packages
Creating our own packages (or) user defined packages involves the following steps:
Step1:
1. To create a package, simply include a package command as the first statement in a Java
source file. First declare the name of the package using package keyword followed by a
package name.
2. This must be first statement in java source file (except any comment or white spaces).
3. Any class you declare within that file will belong to the specified package.
Step 2:
1. Next define the class that is to be put in the package and declare it as public.
package mypack; // package declaration
public class FirstClass // class definition
{
…………
………… // Body of class
…………
}
Step 3:
1. Now store the classname.java file as same as normal java programs save.
Step 4:
1. File is to be compiled as fallows.
Which creates FirstClass.class file and stores it in the mypack directory created under current
directory by -d. Java also supports the package hierarchy, which allows grouping related
classes into a package and then grouping related packages into a larger package. We can
achieve this by specifying multiple names in a package statement, separated by dot.
A java system package can be accessed either by using a fully qualified class name or by using
import statement. We generally use import statement.
Syntax:
Here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on.
In this way we can have several packages in a package hierarchy. We should specify explicit
class name finally. Multiple import statements are valid. * indicates that the compiler should
search this entire package hierarchy when it encounters a class name.
It is also possible to write interfaces in a package. But whenever, we create an interface the
implementation classes are also should be created. We cannot create object to the interface
but we can create objects for implementation classes and use them. We write an interface to
display system date and time in the package mypack as shown in the following program.
package mypack;
public interface MyDate
{
void showDate();
}
Output:
C:\> javac -d. MyDate.java
C:\>
Compile the preceding code and observe that the Java compiler creates a sub directory with the
name mypack and stores MyDate.class file there. This MyDate.class file denotes the byte code of
the interface.
Program: Write a program to create an implementation class for the MyDate interface with the
name DateImpl and storing it in the same package mypack.
When the preceding code in completed, Datelmpl.class file is created in the same package mypack.
Datelmpl class contained showDate () method which can be called and used in any other program.
Program: Write a program which shows how to use the Datelmpl which is an implementation class
of MyDate interface.
import mypack.Datelmpl;
class DateDisplay
{
public static void main(String args[])
{
Datelmpl obj= new Datelmpl();
obj.showDate();
}
}
Output:
Here, we are creating pack2 which is created inside pack1. To use the classes and interfaces of pack2,
we can write import statement as:
This concept can be extended to create several sub packages. In the following program we are
creating tech package inside dream package by writing the statement
package dream.tech;
Program: Let us make a program to learn how to create a sub package in a package.
package dream.tech;
public class Sample
{
public void show ()
{
System.out.println ("welcome to Dream tech");
}
}
Output:
C:\>java -d. Sample.
C:\>
When the proceeding program is compiled, the Java compiler creates a sub directory with the name
dream. Inside this, there would be another sub directory with the name tech is created. In this tech
directory, Sample class is stored. Suppose the user wants to use the Sample class of dream.tech
package, he can write a statement as:
import dream.tech.Sample;
Output:
The access specifiers in Java specify the accessibility (or) scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access Specifier on it.
1. Private:
The access level of a private specifier is only within the class. It cannot be accessed from
outside the class.
2. Default:
The access level of a default Specifier 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.
3. Protected:
The access level of a protected Specifier 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.
4. Public:
The access level of a public Specifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
There are many non-access Specifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access Specifiers only.
Application Programming Interface (API) document is a Hyper Text Markup language (html) file that
contains description of all the features of software, a product or a technology.
API document is like a reference manual that is useful to all the users of the product to understand all
the features and how to use them. For example, JavaSoft people have created API document
separately for the three parts, Java SE, Java EE and Java ME after they created Java language.
Every feature of Java language is described in API document. We can select any package, any class in
that package and the description of the class along with the fields, constructors, methods will appear.
When we click on any of these features, a detailed description of the feature is displayed. We can also
click on Index of the first row to see the index of all items in alphabetical order. Let us know how to
create an API document for any software:
1. First of all, we should copy all the source code files (.java) into a directory. For example, copy
APIDocEx .java of the package pack into a directory
e:\temp.
2. We should open each of the source code files and provide Java documentation comments by
using /** and */. When documentation comments are written, the APIDocEx .java files look like
shown here:
javadoc M.java
After generating the documented API. We will now see many HTML(browser) files created. Now we
need to open the index.html file to get the information about the classes. The figure below shows the
following.
JAR (Java Archive) file is a file that contains compressed version of class files, audio files, image files
or directories. We can imagine a jar file as a zipped file (.zip) that is created by using WinZip software.
Even, WinZip software can be used to extract the contents of a jar file. The difference is that a jar file
can be used as it but whereas the .zip file cannot be used directly. The files should be extracted first
from a .zip file, and then used...
Exceptions Handling
Error
It is common to make mistakes while developing as well as typing a program. A mistake leads to an
error. Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output (or) may terminate the execution of the program
abruptly (o)r even may cause the system to crash. It is therefore important to detect and manage
properly all the possible error condition in the program so that the program will not terminate or
crash during execution.
Types of Errors
Errors may broadly classified into two categories.
1. Compile-time errors
2. Run-time errors.
1. Compile-Time Errors
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler displays an error, it will not create the
.class file.
Most of the compile time errors are due to typing mistakes. The most common problems:
Missing semicolons
Missing brackets in the classes and methods
Misspelling of identifiers and keywords
Missing of double quotes in strings
Use of undeclared variables
Incompatible types in assignment / initialization And so on
2. Runtime Errors
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic (or) may terminate due to errors
such as stack overflow. Most common Run-time errors are:
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Trying to store a value into an array of an incompatible class or type
Passing a parameter that is not in a valid range or value for a method
Attempting to use a negative size of an array.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
When such errors encountered, java typically generates an error message an aborts the program.
The following program is the illustration of Run-time errors.
Exception
An exception is a condition that is caused by a Run-Time Error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an Exception Object
and throws it (i.e. informs us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.
If we want the program to continue with exception of the remaining code, then we should
try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as Exception Handling.
The purpose of exception handling mechanism is to provide a means to detect and report an
“Exceptional Circumstance” so that appropriate action can be taken.
Exception handling mechanism performs the following tasks:
Find the problem ( Hit the exception)
Inform that an error has occurred (throw the exception)
Receive the error information (catch the exception)
Take corrective actions (Handle exception)
The error handling mechanism code basically consists of two segments, one detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.
Java exception handling is managed via 5 keywords, try, catch, throw, throws and finally. The
general form of exception handling block is
1. Try:
The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch (or) finally. It means, we can't use try block alone.
2. Catch:
The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
3. Finally:
The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
4. Throw:
5. Throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.
Java uses the keywords try and catch to handles the exceptions in the java programs.
The following table shows the some common errors that are occurred in the java programs.
These exceptions are not essentially handled in the program code, instead the JVM handles
such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.
Syntax:
try
{
//Statements that causes Exception
}
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
}
Example:
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}
catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
Example:
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)
Finally Statement
finally creates a block of code that will be executed after a try/catch block has completed. The finally
block will execute whether or not an exception is thrown. If an exception is thrown, the finally block
will execute even if no catch statement matches the exception. It may be added immediately after the
try block or after the last catch block.
Syntax 1:
try
{
// statements
}
finally
{
// statements
}
Syntax 2:
try
{
// statements
}
catch (…………)
{
// statements
}
catch (…………)
{
// statements
}
finally
{
// statements
}
In case the programmer does not want to handle the checked exceptions, he should throw them out
using throws clause. Otherwise, there will be an error flagged by Java complier.
package demo;
import java.io.*;
public class Demo
{
void checkout() throws IOException
{
System.out.println("checking machine");
}
public static void main(String[] args) throws IOException
{
Demo d = new Demo();
d.checkout();
System.out.println("successfully checked");
}
}
In the above statement, Null Pointer Exception class object is created and 'Exception data' is stored
into its object. Then it is thrown using throw statement. Now, we can catch it using catch block as:
//using throw
class Sample
{
static void demo()
{
try
{
System.out.println(“inseid demo()”);
throw new NullPointerException(“Excception data”);
}
catch(NullPointerException)
{
System.out.println()ne;
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}
class B
{
public static void main (String args[])
{
A a= new A();
try {
a.methodl ()
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println ("I caught rethrown exception");
}
}
}
Output:
UNIT-4, THREADS
What is a Thread
“A thread is a lightweight sub process, and the smallest unit of processing”. It is a separate path of
execution. A thread is similar to a program that has a single flow of control. It has a beginning, a
body, and an end, and executes commands sequentially. In fact main program in our programs
can be called as Thread.
Threads in java are subprograms of a main application program, they can share the same
memory space, and saves the CPU time, they are known as Lightweight Processes or Lightweight
Threads.
All the threads are running on a single processor, the flow of execution is shared between the
threads.
Benefits of threads:
It enables the programmers to do multiple things at one time.
Main method
module
switchin switchin
g g
A thread can be employed to execute one task at a time. Suppose there are 3 taks to be executed.
We can create a thread and pass the 3 tasks one by one to the thread.
For this purpose, we can write all these tasks separately in separate methods: task1(), task2(),
task3(). Then these methods should be called from run() method, one by one.
Remember, a thread executes only the code inside the run() method. It can never execute other
methods unless they are called i run ().
void task1()
{
System.out.println ("This is taks 1");
}
void task2()
{
System.out.println ("This is task 2");
}
void taxk3()
{
System.out.println("This is task 3");
}
class Single
{
public static void main(String args[])
{
MyThread obj= new MyThread();
Thread t1=new Thread(obj);
}
}
}
Output:
This is taks1
This is taks2
This is taks3
In multi tasking, several tasks are executed at a time. For this purpose, we need more than one
thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks.
Then those tasks are simultaneously executed by the two threads. Using more than one thread is
called 'multi threading’.
When we go to a movie theatre, generally a person is there at the door-checking and cutting the
tickets. When we enter the hall, there is another person who shows the seats to us. Suppose there
is only one person (1 thread) doing these two tasks. He has to first cut the ticket and then come
along with us to show the seat. Then he goes back to the door to cut the second ticket and then
again enter the hall to show the seat for the second ticket. Like this, if he is does the things one by
one, it takes a lot of time, and even though the show is over, there will be still a few people left
outside the door waiting to enter the hall! This is pretty well known to the theatre management. So
what they do? They employ two persons (2 threads) for this purpose
The first person will cut the ticket, and the second one will show the seat. When the second person
is showing the seat, the first person cuts the second ticket. Like this, both the persons can act
simultaneously and hence there will be no wastage of time.
Program: Create a program showing two threads working simultaneously upon two objects.
//Two threads performing two tasks at a time-Theatre example
class MyThread implements Runnable
{
String str;
MyThreads(String str)
{
this.str=str;
}
The first method of creating a thread is simply by extending the thread class. The Thread class is
defined in the package java.lang.Thread. This gives access to all the thread methods directly. It
includes the following steps:
The run() method has been inherited by the class MyThread. This method order to
implement the code to be executed by our thread. The basic implementation of run() will look
like this:
{
………..
……….. // Thread code here
………..
}
When we start the new thread, Java calls the thread's run() method, so it is the run() method,
where all the action takes place.
3. Starting New Thread:
To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
aThread. start(); // invokes run() method
The first line instantiates a new object of class MyThread. This statement just creates the
object. The thread is in a newborn state.
The second line calls the start() method causing the thread to move into the runnable state.
Example program:
import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5; i++)
{
System.out.println("\tFrom ThreadA: i=” +i);
}
System.out.println("Exit form A);
}
}
class ThreadTest
{
The Runnable interface declares the run() method that is required for implementing threads in
our programs. To do this, we must perform the steps listed below.
Example:
class XYZ implements Runnable
{
public void run()
{
for(int i=1;i<10; i++)
{
System.out.println("Thread XYZ:” +i);
}
System.out.println("End of ThreadXYZ");
}
}
class RunnableTest
{
public static void main(String args[])
{
XYZ runnable= new XYZ();
Thread tx=new Thread(runnable);
tx.start();
System.out.println(“End of main Thread”);
}
}
boolean stop=false;
2. Let us assume that we want to terminate the thread when the user presses <Enter> key. So,
when the user presses that button, make the boolean type variable as true
stop = true;
3. Check this variable in run() method and when it is true, make the thread return from the run()
method.
class Demo1
{
public static void main(String args[]) throws IOException
{
MyThread obj = new MyThread();
Thread t = new Thread (obj);
t.start();
System.in.read();
obj.stop()=true;
}
}
Output:
Take the case of railway reservation. Every day several people want reservation of a berth for
them. The procedure to reserve the berth is same for all the people. So we need same object
with same run() method to be executed repeatedly for all the people (threads).
Let us think that only one berth is available in a train, and two passengers (threads) are asking for
that berth. In reservation counter no.1, the clerk has sent a request to the server to allot that
berth to his passenger. In counter no.2, the second clerk has also sent a request to the server to
allot that berth to his passenger. Let us see now see to whom that berth is allotted.
Program: Create a program showing two threads acting upon a single object.
class Unsafe
{
Reserve obj = new Reserve (1);
Thread t1= new Thread (obj);
Thread t2= new Thread(obj);
t1.setName ("First person");
t2.setName ("Second person");
t1.start();
t2.start();
}
Output:
Available Berths = 1
1 Berths reserved for First Person
Available Berths = 1
1 Berths reserved for Second Person
Deadlock Example
First, let's take a look into a simple Java example to understand deadlock. In this example, we'll
create two threads, T1 and T2. Thread T1 calls operation1, and thread T2 calls operations.
1. public class TestDeadlockExample1 {
2. public static void main(String[] args) {
3. final String resource1 = "ratan tata";
4. final String resource2 = "vimal tata";
5.
6. Thread t1 = new Thread() { // t1 tries to lock resource1 then resource2
7. public void run() {
8. synchronized (resource1) {
9. System.out.println("Thread 1: locked resource 1");
10.
11. try { Thread.sleep(100);}
12. catch (Exception e) {}
13. synchronized (resource2) {
14. System.out.println("Thread 1: locked resource 2");
15. } } } };
16.
17. Thread t2 = new Thread() { // t2 tries to lock resource2 then resource1
18. public void run() {
19. synchronized (resource2) {
20. System.out.println("Thread 2: locked resource 2");
21.
22. try { Thread.sleep(100);}
23. catch (Exception e) {}
24. synchronized (resource1) {
25. System.out.println("Thread 2: locked resource 1");
26. } } } };
27. t1.start();
28. t2.start();
29. } }
Once we run the program, we can see that the program results in a deadlock and never exits. The log
shows that thread T1 is waiting for lock2, which is held by thread T2. Similarly, thread T2 is waiting
for lock1, which is held by thread T1.
Avoiding Deadlock
Deadlock is a common concurrency problem in Java. Therefore, we should design a Java application
to avoid any potential deadlock conditions.
We improve the efficiency of communication between threads. Java.lang. Object class provides
3 methods for this purpose.
1. notify():
This method releases an object (obj) and sends a notification to a waiting thread that the
object is available.
Ex: public final void notify()
2. notifyAll():
This method is useful to send notification to all waiting threads at once that the object (obj) is
available.
Ex: public final void notifyAll()
3. wait():
This method makes a thread wait for the object (obj) till it receives a notification from a
notify() or notify All() methods. It is recommended to use the above methods inside a
synchronized block.
Method Description
public final void wait() throws InterruptedException It waits until object is notified.
public final void wait(long timeout) throws It waits for the specified amount of time.
InterruptedException
Java permits us to set the priority of a thread using the setPriority() method as follows.
ThreadName.setPriority(Number);
The Number is an integer value to which the threads priority is set. The Thread class defines several
priority constants of 3 types that is.
The Number may assume one of these constants or any value between 1 and 10. The default setting
is NORM _ PRIORITY.
Whenever multiple Threads are ready for execution, the Java system chooses the highest priority
thread and executes it. For a thread of lower priority to gain control, one of the following things
should happen.
class as:
Here we are creating and adding the thread group tg1 to the thread group tg. The name of the
added thread group is represented by groupname.
4. To know the parent of a thread or a thread group, we can use getParent().
tg.getParent ();
This method returns ThreadGroup object which is the parent of tg.
5. To know the parent thread group of a thread, we can use:
t.getThreadGroup();
This return a ThreadGroup object to which the thread t belongs.
6. To know the number of threads actively running in a thread group :
tg.setMaxPriority ();
Normally, the maximum priority of a thread group will be 10. But this method can set it as any other
number between 1 and 10.
Example: To demonstrate the creation of thread groups and some methods which act on thread
groups.
class TGroups
{
public static void main(String[] args) throws Exception
{
Reservation res = new Reservation ();
Cancellation can = new Cancellation ();
A daemon thread is a thread that executes continuously. Daemon threads are service providers for
other threads (or) objects. It generally provides a background processing
A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in below figure.
1. NewBorn State
When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
Schedule it for running using start() method
2. Runnable State
The Runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. If all the threads have equal priority, then they are given time
slots for execution in first-come, first-serve manner. If we want a thread to relinquish (hand
over) control to another thread to equal priority before its turn comes, we can do so by using
the yield().
3. Running State
Running means that the processor has given its time to the thread for its execution. The
thread runs until it loses control on its own or it is preempted by a higher priority thread. A
Thread may be control its control in one of the following situations.
A thread is said to be Blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleping, or
waiting in order to satisfy certain requirements. A blocked thread is considered “not
runnable” but not dead and therefore fully qualified to run again.
5. Dead State
Every thread has a lifecycle. A running thread ends its life when it has completed executing
its run() method. It is natural death. However, we can kill it by sending the stop message to it
at any state thus causing a premature death to it. It is done by stop() method.
Thread class also defines many methods for managing threads. Some of them are,
Method Description
1)setName() to give thread a name
2)getName() return thread's name
3)getPriority() return thread's priority
4)isAlive() checks if thread is still running or not
5)join() Wait for a thread to end
6)run() Entry point for a thread
7)sleep() suspend thread for a specified time
8)start() start a thread by calling run() method
Returns an estimate of the number of active threads in
9)activeCount()
the current thread's thread group and its subgroups.
Determines if the currently running thread has
10) checkAccess()
permission to modify this thread.
Returns a reference to the currently executing thread
11) currentThread()
object.
Prints a stack trace of the current thread to the
12) dumpStack()
standard error stream.
13) getId() Returns the identifier of this Thread.
14) getState() Returns the state of this thread.
15) getThreadGroup() Returns the thread group to which this thread belongs.
Method Description
16) interrupt() Interrupts this thread.
17) interrupted() Tests whether the current thread has been interrupted.
18) isAlive() Tests if this thread is alive.
19) isDaemon() Tests if this thread is a daemon thread.
20) isInterrupted() Tests whether this thread has been interrupted.
21) setDaemon(boolean Marks this thread as either a daemon thread or a user
on) thread.
22) setPriority(int
Changes the priority of this thread.
newPriority)
A hint to the scheduler that the current thread is willing
23) yield()
to yield its current use of a processor.
UNIT-4 STREAMS
Q). What is a Stream?. Concept of stream.
Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices. A stream presents a uniform, easy-to-use,
object-oriented interface between the program and the input/ output devices.
A stream in Java is path along which data flows (like a river or a pipe along which water flows). It
has a source (of data) and a destination (for the data). Both the source and the destination may
be physical devices or programs or other streams in the same program.
Java streams are classified into two basic types, namely, input stream and output stream. An
input stream extracts (i.e., reads) data from the source (file) and sends it to the program.
Similarly, an output stream takes data from the program and sends (i.e. writes) it to the
destination (file). The program connects and opens an input stream on the data source and then
reads the data serially. Similarly, the program connects and opens an output stream to the
destination place of data and writes data out serially.
The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions
It was designed to provide functional features for creating and manipulating streams and files
for reading and writing bytes. Byte stream are defined by using two classes, InputStream and
OutputStream.
InputStream classes that are used to read 8-bit bytes, include a super class known as
InputStream and a number of sub classes for supporting various input related functions.
b. OutputStream classes:
OutputStream classes that are used to write 8-bit bytes, include a super class known as
OutputStream and a number of sub classes for supporting various output related functions.
16-bit unicode character. There are two kinds of character stream classes namely
Character streams can be used to read and write reader stream classes and writer stream
classes.
Reader stream classes are designed to read character from the files. Reader class is the base
class for all other classes in this group.
Writer stream classes are designed to write all output operation on files. Writer class is the
base class for all other classes in this group. We can also cross-group the streams based on
the type of source or destination they read from or write to. The source(or destination) may
be memory, a file or a pipe.
FileOutputStream class belongs to byte stream and stores the data in the form of individual
bytes. It can be used to create text files. We know that a file represents storage of data on a
second storage media like a hard disk or CD. The following steps are to be followed to create a
text file that stores some characters (or text)
i) First of all, we should read data from the keyboard. For this purpose, we should attach the
keyboard to some input stream class. The code for using DatalnputStream class for reading
data from the keyboard is as:
Here, System.in represents the keyboard which is linked with DataInputStreamm object, that is, dis.
ii) Now, attach a file where the data is to be stored to some output stream. Here, we take the
help of FileOutputStream which can send data to the file. Attaching the file myfile.txt to
FileOutputStream can be done as
iii) The next step is to read data from DataInputStream and write it into FileOutputStream. It
means read data from dis object and write it into fout object, as shown here:
Finally, any file should be closed after performing input or output operations on it, else the
data of the file may be corrupted. Closing the file is done by closing the associated streams.
For example, fout.close(); will close the FileOutputStream, hence there is no way to write
data into the file. These steps are shown in Figure and implemented in Program
import java.io.*;
class CreateFile
{
public static void main (String args[]) throws IOException
{
DataInputStream dis = new DataInputStream (System.in);
FileOutputStream fout = new FileOutputStream ("myfile.txt");
System.out.println("Enter text (@at the end);");
char ch;
while ((ch=(char)dis.read()) != '@')
fout.write(ch);
fout.close();
}
}
Output:
CA> javac createfile java
C:\> java createfile
enter text (@ at the end);
This is my life line one
This is my life line two
@
C: type myfile.txt
This is my file line one
This is my file line two.
Q). Explain about Reading data from a file using FileInputStream with example?
FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible
to read data from a text file using FileInputStream. Let us see how it is done:
This will enable us to read data from the file. Then, to read data from the file, we should read
data from the FileInputStream as :
When the read() method reads all the characters from the file, it reaches the end of the file.
When there is no more data available to read further, the read() method returns -1.
2. For displaying the data, we can use System.out which is nothing but PrintStream object.
System.out.print(ch);
3. Finally, we read data from the FileInputStream and write it to System.out. This will display all
the file data on the screen.
Output:
Q). Explain about writing character to a file and Reading character from a file with
examples.
(or)
Explain about File writer and FileReader classes with example?
Java provides two special types of stream called the FileReader and FileWriter to read
characters from file and write characters in to a file.
The FileWriter class can use to write characters to a file. FileWriter will create the file before
opening it for output when we create the object.
Method Description
1) public void write(String text) :writes the string into FileWriter.
2) public void write(char c) :writes the char into FileWriter.
3) public void write(char[] c) : writes char array into FileWriter.
4) public void close() : closes File Writer.
import java.io.*;
class Simple {
public static void main(String args[])
{
try{
FileWriter fw= new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}
catch(Exception e)
{System.out.println(e);}
System.out.println("success");
}
Output: success...
The FileReader class that we can use to read characters from a file. A FileReader object can be
created as follows
1) public int read() : returns a character in ASCII form. It returns-1 at the end of file.
2) public void close() : closes FileReader.
import java.io.*;
class Simple {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader ("abc.txt");
int i;
While(i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}
Output:
my name is sachin
Let us now learn how to compress data in a file, say 'file' by following these steps:
ii) Take the output file 'file2' and attach it to FileOutputStream. This will help to write data
into 'file2'.
iv) Now, read data from FileInputStream and write it into DeflaterOutputStream. It will
compress the data and send it to FileOutputStream which stores the compressed data
into the output file. These steps are shown in Figure and implemented in Program
import java.io.*;
import java.util.zip.*;
class Zip
{
public static void main (String args[]) throws Exception{
// FileInputStream for reading data
FileInputStream fis = new FileOutputStream("files1")
FileOutputStream fos=nes FileOutputStream ("file2")
DeflaterOutputStream dos = new DeflaterOutputStream(fos);
fis.close();
int data;
while ((data = fis.read()) != -1)
dos.write (data);
fis.close();
dos.close();
}
Output:
C:\> javac Zip.java
C:\> java Zip
The file with the name 'file2' contains compressed data and suppose we want to obtain original
uncompressed data from this file. Let us follow these steps to data from this file.
i) Attach the compressed file 'file2' to FileInputStream. This helps to read data from 'file2'
ii) Attach the output file file3' to FileOutputStream. This will help to write uncompressed
data into 'file3".
iii) Attach FileInputStream to InflaterInputStream so that the data read from FileInputStream
goes into InflaterInputStream. Now InflaterInputStrea uncompresses the data.
iv) Now, read uncompressed data from InflaterInputStream and write it into
FileOutputStream. This will write the uncompressed data to 'file3'. These steps are shown
in Figure below and are implemented in Program.
import java.io.*;
import java.util.zip.*;
class unzip
{
public static void main (String args[]) throws Exception
{
FileInputStream fis= new FileInputStream ("file2");
FileOutputStream fos= new FileOutputStream ("file3");
InflaterInputStream iis = new InflaterInputStream(fis);
int data;
while ((data = iis.read()) != -1)
fos.write(data);
fos.close();
}
}
So far, we wrote some programs where we stored only text into the files and retrieved same
text from the files. These text files are useful when we do not want to perform any calculations
on the data.
For example, we want to store some employee details like employee identification number (int
type), name (String type), salary (float type) and date of joining the job (Date type) in a file. This
data is well structured and got different types. To store such data, we need to create a class
Employee with the instance variables id, name, sal, doj as shown here:
Then create an object to this class and store actual data into that object. Later, this object
should be stored into a file using objectOutputStream. Observe that the Serializable interface
should be implemented by the class whose objects are to be stored into the file. This is the
reason why Employee class implements Serializable interface.
To store the Employee class objects into a file, follow these steps:
i) First, attach objfile to FileOutputStream. This helps to write data into objfile.
iii) Now, ObjectOutputSteam can write objects using writeObject() method to FileOutputStream,
which stores them into the objfile.
Storing objects into a file like this is called 'serialization'. The reverse process where objects can be
retrieved back from a file is called 'de-serialization'.
Program: Write a program to create Employee class whose objects are to be stored into a file.
//Employee class
import java.io.*;
import java.util.Date;
class Employee implements Serializable
{
private int id;
private Straing name;
private float sal;
private Date doj;
Employee (int i, String n, float s, Date d)
{
Id=i;
Name=n:
Sal=s;
Doj=d;
}
System.out.println(id+"\t"+name+"\t"+doj);
static Employee getData() throws IOExecption
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in);
System.out.print("Enter emp id: ") ;
int id= Integer.parseInt(br.readLine());
System.out.print ("Enter name: ");
String name = br.readLine();
Date d= new Date();
Output:
C>javac Employee.java
Output:
C: javac Storeobj.java
C>java Storeobj
Write a program which accepts a filename from command line argument and displays the
number of charaters, words, and lines in the file.
{
int ch;
boolean prev= true;
int char_count=0; int line_count=0;
int word_count=0;
FileInputStream fin= new FileInputStream (args [0]);
while ((ch=fin.read()) != -1)
{
if (ch !=’ ‘) ++char_count ;
if (!prev && ch==' ')++word_count;
if (ch==' ') prev=true; else prev= false;
if (ch=='\n')++line_count;
}
char_count=line_count*2;
word count+=line_count;
System.out.println ("No. of chars="+char_count);
System.out.println("No. of words="+word_count);
System.out.println("No. of lines="+ line_count);
fin.close();
}
}
Output:
C:\> javac Count.java
C:\> java Count myfile No. of chars = 44
No. of words=12
No. of lines=6
Sometimes we need to copy the entire data of a text file into another text file. Streams are useful
in this case. To understand how to use streams for copying a file content to another file, we can
use the following logic:
ii) For writing data into the output file, which is to be created, attach it to
FileOutputStream.
Example: Write a program to read the contents of the input file and write them into an output
file..
import java.io.*;
class CopyFile
{
public static void main (String args[]) throws loXeception
{
int ch;
FileInputStream fin = new FileInputStream(args[0]);
Q). Briefly explain about File class and Methods with example?
1. File Class
File class of java.io package provides some methods to know the properties of a file or a
directory. First of all, we should create the File calss object by passing the filename or directory
name to it.
1. boolean is File (): This method returns true if the File object contains a filename, otherwise
false.
2. boolean isDirectory(): This method returns true if the File objects contains a directory name.
3. boolean canRed (): This method returns true if the File object contains a file which is
rendable.
4. boolean can Write (): This method returns true if the file is writable.
5. boolean canExecute (): This method returns true if the file is executable.
6. boolean exists(): This method returns true when the File object contains a file or directory
which physically exists in the computer
7. String getParent (): This method gives the name of directrory path of a file or directory.
8. String getPath(): This method gives the name of directory path of a file or directory.
9. Stirng getAbsolutePath(): This method gives the absolute directory path of a file or directory
location. Absolute paaath is mentioned staarting from the root directory.
10. long length(): This method returns a number that represents the size of the file in bytes.
11. boolean delete (): This method deletes the file or directory whose name is in File object.
12. boolean createNewFile(): This method automatically creates a new, empty file indicated by
File object, if and only if a file with this name does not yet exist.
13. boolean mkdir (): This method creates the directory whose name is given in File object.
14. boolean rename To (File newname): This method charges the name of the file as new name.
15. String[] list (): This method returns an array of strings naming the files and directories in the
directory.
Applet
Applets are the small java programs that are primarily used for Internet computing. They can be
transported over the internet from one computer to another. They can be run using the applet
viewer (or) any web browser that supports java. An applet like any application program, can
perform arithmetic operations, display graphics, play sounds, accept user input, create
animation, and play interactive games.
“A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet”. If our system is connected to the internet, we can download the
remote applet on to our system via internet and run it.
G. ANKAMMA RAO
How Applets differ from Applications
Applets are designed for the use on the internet. They impose certain Limitations and restrictions
in their design.
1. Applets do not use the main( ) method for initiating the execution of the code. Applets are
loaded automatically to call certain methods of applet class to start( ) and execute( ) the
applet code.
3. Applets cannot read from or write to the files in the local computer.
Applet enters the running state when the system calls the start( ) method of Applet class. This
occurs automatically after the applet is initialized. Starting can also occur if the applet is
already in “stopped” (idle) state. The start( ) method may be called more than once.
public void start()
{
-----------------
-----------------
}
----------------
----------------
}
4) Dead State:
An applet is said to be dead when it is removed from the memory. This occurs automatically
by invoking the destroy ( ) method destroying occurs only once in the life cycle.
If the applet has created any resources, like threads. We may override the destroy( ) method
to clean
up these resources.
public void destroy( )
{
----------------
----------------
}
Display State:
Applet moves to the display state whenever it has to perform some output operations on the
screen. paint( ) method is used to accomplish the task. The default version of paint( ) method
does absolutely nothing we must override this method .
public void paint(Graphics g)
{
----------------
----------------
}
It is to be noted that the display state is not considered as a part of applet’s life cycle. This
method is inherited from the Component class a super class of the applet class.
The Applet class which is contained in the java.applet package provides life and behavior to
the applet through its methods such as init ( ), start( ) and paint( ).
Unlike the applications which calls the main( ) method directly to initiate the execution of a
program, when applet is loaded, java automatically calls a series of Applet class methods for
starting, running, and stopping the applet code. the applet code is executed when an applet is
loaded.
The paint( ) method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics, or sound. The paint( ) method
requires the Graphics class object as an argument.
This requires that the applet code imports the java.awt package that contains the Graphics
class. All the output operations of a class are performed using the methods defined in the
Graphics class.
Applet will have a general format as shown below.
import java.awt.*;
import java.applet.*;
---------------
----------------
public class <applet class name> extends Applet
{
public void paint(Graphics g)
{
------------------- // Applet operation code
-------------------
}
}
The <applet class name> is the main class for the Applet. When the applet is loaded, Java
creates an instance of this class and a series of applet class methods are called on that
instance to execute the code.
Example:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to Java World”,10,100);
}
}
This should be saved with the filename HelloJava .java. The main Applet class must be
declared public. When drawstring is executed, draws the string Welcome Java at the position
10, 100 (pixels) of applet reserved space.
Example:
The compiled output file called HelloJava.class is placed in the same directory as the source.
<HTML
>
<!
…………………………
………………………… Comment Section
>
<HEAD>
<TITLE >.............
</TITLE> Head Section
</HEAD>
<BODY>
<APPLET............. > Body Section
</APPLET>
<BODY>
</
HTML>
a) Comment section:
This section contains comments about the web page. It is useful to prepare notes. A comment
line begins with a <! and ends with a >. Web browsers ignore the text enclosed between
them.
b) Head section:
The head section is defined with a starting <HEAD> tag and a closing </HEAD> tag. This
section contains a title for the web page as shown below.
<HEAD>
<TITTLE>
welcome to java applets
</TITTLE>
</HEAD>
The text enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the web
browser when it displays the page. A slash ( / ) in a tag signifies the end of that tag section.
c)Body Section:
After the head section body section appears. This section contains the entire information
about the web page and its behaviour. We can set up many options to indicate how our page
must appear on the screen like color, location, sound etc.
<BODY>
<CENTER>
<H1>
Welcome to the world of applets
</H1>
</CENTER>
<APPLET>
</APPLET……>
</BODY>
The HTML code tells the browser to load the compiled hellojava.class, which is in the same
directory as the HTML file. This also specifies the display area for the applet output as 400
pixels width, 200 pixels height.
The Applet tag specifies three things.
Name of the Applet
Width of the Applet
Height of the Applet.
<APPLET>
CODE=”HelloJava.class”
WIDTH=400 HEIGHT=200>
</APPLET>
</BODY>
</HTML>
And finally save HTML file with the name HelloJava.html.
If we use a java-enabled web browser, we will be able to see the entire web page containing
the applet. We can use it to run applet; just double click on the HelloJava.html file or open
with a web browser (ex: Internet Explorer, google chrome etc.)
If we use the appletviewer tool, we will only see the applet output. Applet viewer is available
as a part of Java Development Kit (JDK). We can use it to run applet as follows:
Appletviewer HelloJava.html
<HTML>
<HEAD>
<TITLE>
Here is an Applet
</TITLE>
</HEAD>
</BODY>
<APPLET CODE= HelloJava.class WIDTH=400 HEIGHT=200 ALIGN=RIGHT>
</APPLET>
</BODY>
</HTML>
HTML Tags
1. <HTML> …. </HTML> : Specifies the beginning and end of the file.
2. <HEAD> …. </HEAD> : This tag includes the details about the web page.
3. <TITLE> …. </TITLE> : displays title.
4. <BODY> ….. </BODY> : This contains the main text of the web page. This is the
place where the applet tag is declared.
5. <H1> ….. </H1> : Header tags: These are used to display the headings.
6. <H6> ….. </H6> : Creates the smallest tag.
7. <CENTER> …… </CENTER> : places the text contained at the centre of the page.
8. <PARAM> : supplies user-defined parameter using <PARAM> tags. The PARAM tag is
allowed only in the <Applet> tag.
9. <B> …. </B> : Text between these tags will be displayed in bold type.
10. <BR> : Line break.
a) MyAppAll.java
import java.awt.*;
import java.applet.*;
public class MyAppAll extends Applet
{
String msg = " ";
public void init()
{
setForeground(Color.yellow);
setBackground(Color.red);
Font f = new Font("Arial", Font.BOLD, 30);
setFont(f);
msg += " init";
}
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet
{
Image picture;
public void init()
{
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g)
{
for(int i=0;i<500;i++)
{
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}
catch(Exception e){}
}
}
}
In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.
myapplet.html
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag
Param Tag
The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value of
the parameter respectively. For example, the param tags for passing name and age parameters
looks as shown below:
Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.
getParameter() Method
Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Output of the above program is as follows:
Databases like Oracle, Sybase, MySQL and SqlServer are in use now a day. Data is stored generally in the
form of tables in these databases. To retrieve data from the tables we need some program. This program
is called 'database client' program. To understand the database client, let us take an example. If oracle
10g is installed in your computer, go to 'Start' menu and click.
Start-> Programs -> Oracle Database 10g Express Edition-> Run SQL command
It opens a window at DOS prompt where SQL> prompt appears. Types connect and, it asks to enter user-
name and password. Type 'scott' and 'tiger' as default values. Then you would be connected to the oracle
database. This application is called SQL*Plus which is a client program to connect to the oracle server at
any moment.
Database clients:
Using SQL Plus application, it is possible to store data into oracle database. Also retrieving the data as
well as updating it is also possible. Since, SQL*Plus is retrieving data from the oracle server in your
system, SQL*Plus is called database client and oracle database is called database server. Now type a
query as:
It displays all the tables available in oracle database. Press Control+Alt+Del to see Task Manager Dialog
box, where you can spot out Oracle.exe file running in your system. This is nothing but the oracle
database.
It is possible to load SQL*Plus client software in a system and the oracle database server program in
another system connected on a network. The client will be able to connect to the database server and
retrieve the data on the network.
go to Start -> MySQL >> MySQL Server 5.0> MySQL Command line client. It asks for password, where you
type: 'root' at DOS prompt. Now you can see the screen shown in the figure.
To see the names of databases in MySQL, give the following command: mysql show databases;
To come out of MySQL, we can type quit at mysql>prompt.
SQL*Plus or MySQL client programs connect to database servers and retrieve the data from them. The
same thing can be done through a Java program which connects to a database and retrieves data from it.
JDBC (Java Database Connectivity): JDBC is an API (Application Programming Interface) that helps a
programmer to write Java programs to connect to a database, retrieve the data from the database and
perform various operations on the data in the Java program.
Every database vendor will provide a document representing all the commands to connect and utilize the
database features. This document is called 'API (Application Programming Interface) document'. API
document is a file that contains description of all the features of a software, a product or a technology.
For example, the vendor of oracle database has given the following information for the programmers
who use his product, in his API document:
If the same programmer wants to work with MySQL database, he should learn the syntax and usage of
functions provided by MySQL vendor in his API document.
For example,
By using these functions of this common API document, programmers can communicate with any
database in the world. Such a document is called ODBC (Open Database Connectivity) API.
“ODBC is a document that contains common functions to communicate with any database”. It is created
by Microsoft Corporation. If any organization creates a software depending on this ODBC document, it is
called ODBC driver.
In the same way, Sun Microsystems Inc. has also created an API document named JDBC (Java Database
Connectivity) API and the actual software which is created according to JDBC API, is called JDBC driver,
JDBC API is defined in java.sql package. This package contains interfaces like Connection, Statement,
ResultSet, ResultSetMetaData, PreparedStatement, Driver, CallableStatement and classes like Date,
Time, DriverManager etc. Several companies have started developing software containing these
interfaces and classes. These software are called JDBC drivers.
TNAME TABTYPECLUSTERID
ACCOUNT TABLE
DEPT TABLR
EMP TABLE
SALGRADE TABLE
4 rows selected.
1) Suppose, we want to create a table with the name 'emptab' with 3 columns: eno (int type), ename
(String type) and sal(float type), we can type SQL command as:
SQL> create table emptab (eno int, ename varchar2(20), sal float);
Table created..
2) To see the information about the table created by us, we can use description command, as:
3) To store data into the table 'emptab'. For this purpose, we should use 'insert' command as:
In this way, we can store rows into empty table. To save all entered rows into the table, we can use
'commit' command, as:
SQL> commit;
4) To see all the rows of our emptab, we should use 'select' command in the following way:
5) Now update the salary of an employee in emptab. Let us increase the salary by Rs.1000 to the
employee whose eno is 11.
SQL> update emptab set sal = sal + 1000 where eno 11;
1 row updated.
7) To save all the changes into the database, we can use to 'commit' command. Similarly, to un-save the
changes, 'rollback' can be used.
SQL> rollback;
Rollback completed.
1) To see what databases are existing in MySQL, give the following command:
mysql> show databases;
Database
Mysql
test
The above output means that there are 2 databases currently available in MySQL and they are: mysql
and test.
2) Let us see which tables are available in the database 'test'. We should first enter test database, as:
mysql> use test;
Database changed
3) To create a table with the name 'emptab' in test database. eno, ename and sal are the columns in
emptab.
mysql> create table emptab (eno int, ename char(20), sal float);
Query OK, 0 rows affected
3 rows in set
6) To see all the rows of the table, we can use select query as:
mysql> select from emptab;
eno ename sal
10 Nagesh 7800
11 Ganesh 10000
12 Vinaya 5000.55
13 Rahul 7800
4 rows in set
7) Suppose we want to retrieve employees names whose salary is Rs.7800.
mysql> select ename from emptab where sal = 7800;
ename
Nagesh
Rahul
2 rows in set
8) Suppose we want to delete the row of an employee whose employee number is 10.
mysql> delete from emptab where eno = 1001;
Query OK, 1 row affected
10) Finally, to close MySQL, we can give 'quit' command to see the system prompt, as:
mysql> quit;
Q). Write the database programming using JDBC? or write various stages in a
database program?
Database programming using JDBC: JDBC APIs are used by a Java application to communicate with a
database. In other words, we use JDBC connectivity code in Java application to communicate with a
database.
There are 6 steps to connect any Java application with the database in Java using JDBC. They are as
follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries (or)Retrieving the result.
5. Close connection
1. By creating an object to driver class of the driver software, we can register the driver. For example, to
register JdbcOdbcDriver of the Sun Microsystems, we can create an object to the driver class:
JdbcOdbeDriver, as shown below:
2. The second way to register a driver is by sending the driver class object to registerDriver() method of
DriverManager class.
DriverManager.registerDrive (new sun.jdbc.odbc.JdbcOdbcDriver());
3. The third way to register the driver is to send the driver class name directly to forNasme() method,
as:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
4. In case, the user should specify the driver name at the time of running the program, we can use
getProperty() method of System class to receive the driver name, as:
String dname= System.getProperty("driver");
Class.forName(dname);
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws SQLException
Example:
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
public Statement createStatement()throws SQLException
Statement stmt=con.createStatement();
public ResultSet executeQuery(String sql)throws SQLException
Program: This is a program to retrieve all the rows from emptab of oracle database. //To retrieve data
from Oracle database import java.sql.*;
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
o permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to
Output:
C:\> set classpath=C:\jars/ojdbe 14.jar;.;
C:\> javac OracleData.java
C:\> java Oracle Data
1001
Nageswara Rao
7800.55
1002
Vijay kumar
6000.0
Step 1: First of all, we should create a DSN (Data Source Name) that represents the name for the
database, by clicking on the Start button and following the
path: Start > Settings> Control Panel -> Administrative tools Data Sources (ODBC).
We can find ODBC Data Source Administrator dialog box as shown in Figure.
Step 2: In this dialog box, select User DSN tab and click the Add button at right side. Now the list of
drivers available will be displayed in a separate dialog box. Select Microsoft ODBC for Oracle driver in the
list and click the Finish button.
Step 3: Now, you can see Microsoft ODBC for Oracle Setup dialog box appears. Type the DSN name and
user name and then click the OK button, as shown in Figure.
Now, we can verify that a new DSN with the name 'nitin' has been created in UserDSN tab. Click the OK
button to close the ODBC Data Source Administrator.
After creating the DSN name as shown above, the next thing we should do is to register the driver. To
register Sun's jdbc-odbc bridge driver, we can use the following statement in our program:
Here, nitin is the DSN name that we have just created, scott is the username and tiger is the password.
Program: Let us see how to use Sun's jdbc-odbe to oracle database and retrieve all the rows from
emptab.
//To retrieve data from oracle database using jdbc-odbe bridge driver
import java.sql.*;
class OracleData
{
public static void main (Strig args[]) throws Exception
{
//Register the driver
DriverManager.registerDriver (new sun.jdbc.odbc.JdbcOdbc Driver());
//Establish connection with the database
Connection con = DriverManager.getConnection("jdoc:odbc:nitin", "scott", "tiger");
//Create a SQL statement
Statement stmt = con.CreateStatement();
//Execute the stmt
ResultSet rs = stmt.executeQuery("Select from emptab");
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getFloat(3));
System.out.println(".......");
//close the connection
con.close();
}
}
Output:
C:> javac OracleData.java
C: java OracleData
10
Nageswara Rao 7800.55
1002
Vijay Kumar
6000.0
Start > Programs -> Microsoft office -> Microsoft Access -> Create a new file - Blank database
File New Database dialog box will be displayed as shown in Figure. Type the database name as 'Mydb' in a
When we enter the MS Access, a dialog box is displayed where double click 'Create table by entering
data' option. This is shown in Figure.
Then, we will see a spread sheet with several rows and columns where we can enter column names in
the table and column data as shown in Figure. Rename Field 1 as eno, Field 2 as ename and Field 3 as sal.
Then enter data.
Then select File -> Save option and Enter Filename as 'emptab' and then click OK button.
MS Access prompts us to enter a primary key. Click on 'NO' button. And close the table. Come out of MS
Access now.
To connect to MS Access, we can use Sun Microsystems 'jdbc-odbe bridge driver. To use this driver, it is
necessary to create a DSN (Data Source Name) by going to Start
Settings-> Control Panel -> Administrative Tools> Data Sources (ODBC).
We can find ODBC Data Source Administrator dialog box where select User DSN tab and click the Add
button at right side. Now the list of drivers available will be displayed in a separate dialog box. Select
Microsoft Access (*.mdb) driver in the list and click Finish button. It displays ODBC Microsoft Access Setup
dialog box as shown in Figure. In this box, enter:
Now DSN is created, we can mention it while connecting it to MS Access database, as:
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getFloat(3));
System.out.println("-------------“);
}
}
}
Output:
C:\> javac AccessData.java
C:\> java AccessData
1001
8900.0
1002
Nageswara Rao
Vijaya 9000.9