Chapter 1 1
Chapter 1 1
Chapter 1 1
Core Java
inventors of Java.
Object Oriented
Distributed
High Performance
Java environment include 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 Java Standard Library(JSL),also known as the
The Java Development Kit comes with a collection of tools that are used for developing
javac(Java Compiler)
java(Java Interpreter)
jdb(Java debugger)
The java standard library or API includes hundred of classes and methods grouped into
Utilities package(java.util.*)
Input/Output package(java.io.*)
Networking package(java.net.*)
Databases package(java.sql.*)
1.1.3 Process of Building & running java application program:
Text editor
javac
java jdb
web applets
Stand alone application can be executed by java interpreter and we applets can be
class classname
Java compiler produces an intermediate code known as byte code for a machine that does
not exist. This machine is called the java virtual machine(JVM) and it exists only inside
Process of Compilation:
java source code java compiler byte code
Virtual machine
real machine
Data type specify the size and type of values that can be stored. Every variable in java has
a data type.
non-primitive data
Numeric
Non Numeric
interfaces
arrays
long 8 byte
char 2 byte
boolean 1 bit
1.3 VARIABLE
A variable is an identifier that denotes a storage location used to store a data value. A
variable may take different values at different times during the execution of the program.
Variable names may consist of alphabets, digits, underscore (_) and dollar character,
1.4 OPERATORS
They are used to manipulate primitive data types. Java operators can be classified as
unary, binary, or ternary—meaning taking one, two, or three arguments, respectively.
A unary operator may appear before (prefix) its argument or after (postfix) its argument.
A binary or ternary operator appears between its arguments.
Java operators fall into eight different categories:
Assignment arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type.
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Conditional Operator ?:
1.5 ARRAYS
An array is a group of homogeneous data items share a common name. The java array
enables the user to store the values of the same type in contiguous memory allocations.
Arrays are always a fixed length abstracted data structure which can not be altered when
required.
Declaring an array:
Declaring an array is the same as declaring a normal variable except that you must put a
set of square brackets after the variable type. Here is an example of how to declare an
An array is more complex than a normal variable so we have to assign memory to the
array when we declare it. When you assign memory to an array you also set its size. Here
Instead of assigning memory to the array you can assign values to it instead. This is
called initializing the array because it is giving the array initial values.
Using an array:
You can access the values in an array using the number of the element you want to access
between square brackets after the array's name. There is one important thing you must
remember about arrays which is they always start at 0 and not 1. Here is an example of
a loop to set all the values of an array to 0 which you will see is much easier than setting
Sorting an array
Sometimes you will want to sort the elements of an array so that they go from the lowest
value to the highest value or the other way around. To do this we must use the bubble
sort. A bubble sort uses an outer loop to go from the last element of the array to the first
and an inner loop which goes from the first to the last. Each value is compared inside the
inner loop against the value in front of it in the array and if it is greater than that value
2D arrays:
So far we have been using 1-dimensional or 1D arrays. A 2D array can have values that
go not only down but also across. Here are some pictures that will explain the difference
All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.
Java Control statements control the order of execution in a java program, based on data
values and conditional logic. There are three main categories of control flow statements;
We use control statements when we want to change the default sequential order of
execution
The If Statement
The if statement executes a block of code only if the specified expression is true. If the
value is false, then the if block is skipped and execution continues with the rest of the
program. You can either have a single statement or a block of code within an if statement.
if (<conditional expression>)
<statement action>
statement fails, the statements in the else block are executed. You can either have a single
statement or a block of code within if-else blocks. Note that the conditional expression
if (<conditional expression>)
<statement action>
else
<statement action>
The switch case statement, also called a case statement is a multi-way branch with
several choices. A switch is easier to implement than a series of if/else statements. The
long integral value. Following the controlling expression is a code block that contains
zero or more labeled cases. Each label must equate to an integer constant and each must
be unique. When the switch statement executes, it compares the value of the controlling
expression to the values of each case label. The program will select the value of the case
label that equals the value of the controlling expression and branch down that path to the
end of the code block. If none of the case label values match, then none of the codes
within the switch statement code block will be executed. Java includes a default label to
use in cases where there are no matches. We can have a nested switch within a case block
of an outer switch.
When executing a switch statement, the program falls through to the next case.
Therefore, if you want to exit in the middle of the switch statement code block, you must
insert a break statement, which causes the program to continue executing after the current
code block.
While Statement
The while statement is a looping construct control statement that executes a block of code
while a condition is true. You can either have a single statement or a block of code within
the while loop. The loop will never be executed if the testing expression evaluates to
The do-while loop is similar to the while loop, except that the test is performed at the end
of the loop instead of at the beginning. This ensures that the loop will be executed at least
once. A do-while loop begins with the keyword do, followed by the statements that make
up the body of the loop. Finally, the keyword while and the test expression completes the
do-while loop. When the loop condition becomes false, the loop is terminated and
execution continues with the statement immediately following the loop. You can either
do
<loop body>
while (<loop condition>);
For Loops
The for loop is a looping construct which can execute a set of instructions a specified
number of times. It’s a counter controlled loop.
The first part of a for statement is a starting initialization, which executes once before the
loop begins. The <initialization> section can also be a comma-separated list of expression
statements. The second part of a for statement is a test expression. As long as the
expression is true, the loop will continue. If this expression is evaluated as false the first
time, the loop will never be executed. The third part of the for statement is the body of
the loop. These are the instructions that are repeated each time the program executes the
loop. The final part of the for statement is an increment expression that automatically
executes after each repetition of the loop body. Typically, this statement changes the
value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the
two semicolons are mandatory. In particular, leaving out the <loop condition> signifies
that the loop condition is true. The (;;) form of for loop is commonly used to construct an
infinite loop.
1.7 CLASSES
A class is nothing but a blueprint or a template for creating different objects which
defines its properties and behaviors. Java class objects exhibit the properties and
behaviors defined by its class. A class can contain fields and methods to describe the
behavior of an object.
<constructor declarations>
Below is an example showing the Objects and Classes of the Cube class that defines 3
fields namely length, breadth and height. Also the class contains a member function
getVolume().
int length;
int breadth;
int height;
1.8 METHODS
Methods are nothing but members of a class that provide a service for an object or
perform some business logic. Java fields and member functions names are case sensitive.
Current states of a class's corresponding object are stored in the object's instance
variables. Methods define the operations that can be performed in java programming.
// code statements
1.9 INHERITANCE:
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This
means that an object of a subclass can be used wherever an object of the superclass can
be used. Class Inheritance in java mechanism is used to build new classes from existing
classes. The inheritance relationship is transitive: if class x extends class y, then a class z,
The mechanism of deriving a new class from an old class is called inheritance.
The inheritance allows subclasses to inherit all the variables and methods of their parent
classes.
Defining a Sub-class:
variables declarations;
methods declarations;
The keyword extends signifies that the properties of the super-class-name are extended to
the sub-class-name.
Types of inheritance:
Single inheritance:
It is an inheritance in which there is one super-class and one sub-class.
Example:
class room
int length;
int breadth;
room(int x,int y)
length=x;
breadth=y;
int area( )
int height;
super(x,y);
height=z;
int volume( )
class inhertest
int area1=room1.area( );
int volume1=room1.volume( );
System.out.println(area1);
System.out.println(volume1);
}
Multiple inheritance:
In this type more than one super-class having single sub-class derived.
A B
Hierarchical inheritance:
B C D
Multi-level inheritance:
C
1.10 EXCEPTION HANDLING
The purpose of exception handling mechanism is to provide a means to detect and report
suggests incorporation of a separate error handling code that performs the following
tasks.
try block
Statement that cause an exception
(Exception object creater)
Throws
exception object
Catch block
Statement that handle the exception
(Exception handler)
Fig.1.2
Syntax:
try
catch(Exception-type e)
Example:
class error1
int a = 10 ;
int b = 5 ;
int c =5 ;
int x , y;
try
}
catch( ArithmaticException e )
y = a / (b+c);
System.out.println( “y = “ + y);
}}
try
statement ;
catch ( Exception-Type-1 e)
statement ;
catch ( Exception-Type-2 e)
statement ;
catch ( Exception-Type-N e)
statement;
}
try try
{ {
statement ; statement;
} }
finally catch ( )
{ {
statement; statement
} }
catch( )
statement;
finally
{
statements;
Example :
import java.import.Exception;
MyEcxeption(String message)
super(message) ;
class TestMyException
int x=5,y=1000;
try
catch (MyException e)
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
finally
1.11 MULTITHREADING
concurrently. For example, one subprogram can display an animation on the screen while
another may build the next animation to be displayed. This is something similar to
dividing a task into subtasks and assigning them to different people for execution
Single-Threaded
body of execution
End
}
Once initiated by the main thread, the threads A,B and C run concurrently and share the
resources jointly. It is like people living in joint families and sharing certain resources
concurrency. Since threads in Java are subprograms of a main application program and
share the same memory space, they are known as lightweight threads or lightweight
processes.
Main Thread
Main Method
module
Start Start
Start
● New
● Runnable
● Blocked
● Dead
New Threads
When you create a thread with the new operatorfor example, new THRead(r)the thread is
This means that it is in the new state. When a thread is in the new state, the program has
not started
executing code inside of it. A certain amount of bookkeeping needs to be done before a
thread can run.
Runnable Threads
Once you invoke the start method, the thread is runnable. A runnable thread may or may
not actually be
running. It is up to the operating system to give the thread time to run. (The Java
call this a separate state, though. A running thread is still in the runnable state.)
Blocked Threads
A thread enters the blocked state when one of the following actions occurs:
● The thread goes to sleep by calling the sleep method.
● The thread calls an operation that is blocking on input/output, that is, an operation that
will not
return to its caller until input and output operations are complete.
● The thread tries to acquire a lock that is currently held by another thread.
A thread moves out of the blocked state and back into the runnable state by one of the
following pathways.
Dead Threads
A thread is dead for one of two reasons:
In particular, you can kill a thread by invoking its stop method. That method throws a
ThreadDeath error
object that kills the thread. However, the stop method is deprecated, and you should not
Declaring a thread:
…………..
………….
………….
……………
athread.start( )
Example:
}}
}}
{
public void run( )
}}
class threadtest
new A( ).start( );
new B( ).start( );
new C( ).start( );
}}
1.12 COLLECTIONS:
ArrayList:
An ordered sequence that allows efficient insertions and removal at any position.
HashSet:
TreeSet:
It is a sorted set.
HashMap:
TreeMap:
Import java.util.*;
a1.add(10 );
a1.add( 20);
a1.add( 30);
a1.add( 40);
System.out.println(“Array list %s ; size:%d” a1.tostring( ) , a1.size( ) );
a1.remove(new Integer(30) );
a1.remove(0);
A stream in java is a path along which data flows.It has a source and a destination.
Input Stream reads the data from source and pass the data to program.
Byte stream classes have been designed to provide functional features for creating and
1. InputStream classes
2. OutputStream classes
Different InputStream classes are
FileInputStream
DataInputStream
ObjectInputStream
BufferedInputStream
FileOutputStream
DataOutputStream
ObjectOutputStream
BufferedoutputStream
1. Reader classes
2. Writer classes
Import java.io*;
int i ;
FileInputStream fin;
Try
{
Fin =new FileInputStream(args[ 0] );
Catch( FileNotFoundException e )
Return;
Catch(ArrayIndexOutOfBoundException e)
System.out.println(“java filename”);
Return;
System.out.print( (char)i);
Fin.close( );
Abstract windows toolkit contains all the classes for creating user interfaces and for
component.
Component class is the root of all AWT components.
Button
Label
TextField
Checkbox
Combobox
GridLayout
TextArea
Scrolbar
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.*;
TextField tc,tf;
Button cal;
tf=new TextField(5);
tc.setText(“0”);
tf.setText(“0”);
cal=new Button(“calculate”);
add(lc);
add(tc);
add(lf);
add(tf);
add(cal);
cal.addActionListener(this);
If(ae.getSource( ) = = cal)
Double cel=Double.parseDouble(tc.getText( ) );
Tf.setText( String.valueOf(9.0/5/0*cel+32.0) );
}
1.15 APPLET PROGRAMMING
Applets are small java programs that are primarily used in internet programming. They
can be transported over the internet from one computer to another and run using the
Import java.awt.*;
Import java.applet.*;
………………..
………………..
………………..//Appletsoperations code
…………………
Running state
Idle state
Dead state
Initialization state:
Syntax
…………//Action
……………..
Running State:
Applet enters running state when the system calls the start method.
Syntax
{
…………………….//Action
…………………….
Syntax
……………….//action
……………….
Dead state:
Syntax
………………//Action
……………….
}
1.16.QUESTIONS AND SOLUTIONS FROM PREVIOUS UNIVERSITY EXAMS
SOLUTION:
concurrently. For example, one subprogram can display an animation on the screen while
another may build the next animation to be displayed. This is something similar to
dividing a task into subtasks and assigning them to different people for execution
class ABC
{ Beginning
Single-Threaded
body of execution
End
}
Single-Threaded Program
Once initiated by the main thread, the threads A,B and C run concurrently and share the
resources jointly. It is like people living in joint families and sharing certain resources
concurrency. Since threads in Java are subprograms of a main application program and
share the same memory space, they are known as lightweight threads or lightweight
processes.
Main Thread
Main Method
module
Start Start
Start
Multi-Threaded Program
● New
● Runnable
● Blocked
● Dead
not yet running. This means that it is in the new state. When a thread is in the new state,
the program has not started executing code inside of it. A certain amount of bookkeeping
Once you invoke the start method, the thread is runnable. A runnable thread may or may
not actually be running. It is up to the operating system to give the thread time to run.
A thread enters the blocked state when one of the following actions occurs:
● The thread calls an operation that is blocking on input/output, that is, an operation that
will not return to its caller until input and output operations are complete.
● The thread tries to acquire a lock that is currently held by another thread. We discuss
locks on page.
A thread moves out of the blocked state and back into the runnable state by one of the
following pathways.
In particular, you can kill a thread by invoking its stop method. That method throws a
Q2.Write a program to create a user defined Exception called “No Match xception”
that throws an arbitrary message when a string is not equal to “INDIA”.
SOLUTION:
import java.import.Exception;
NoMatchException(String message)
super(message) ;
class TestNoMatchException
String m;
System.out.println(“enter a string”);
m=s.next( );
try
If(m!=”INDIA”)
{
throw new NoMatchException (“String is not india”);
catch (NoMatchException e)
System.out.println(“Caught NoMatchException”);
System.out.println(e.getMessage());
} } }
Q3.What are applets ? Explain their usage. How are they different from java
programs.
SOLUTION:
Applets are small java programs that are primarily used in internet programming. They
can be transported over the internet from one computer to another and run using the
Applet viewer or any web browser that supports Java. Applet does not contain main()
method.
Usage of Applet:
Applets
---Javacanapplets
be usedare
for small
internetjava
programming.----Java programs are programs
program used in internet used for applications
It can be used to extend the capabilities of html web-pages.
programming by embedding development.
inside html
Difference documents.
between java applet and Java programs:
--Java applets cannot have main() --Java programs must have main
method. () method.
SOLUTION:
Interface is a class which consists of constant variables and undefined methods. Interface
can be treated as templates used by different classes by inherit the interface. Interface
cant create any objects. It is only used by other classes those inherit it. Interface can be
used to implement multiple inheritances.
Syntax of Interface:
Interface interface-name
{
//Final or constant variables;
//Undefined methods;
}
Example of Interface:
Interface product
{
Final int productno;
Public void getdescription( );
}
Using interface for multiple inheritance:
Interface is used to implement multiple inheritances by inheriting a class from multiple
interfaces as below.
Interface A Interface B
Class C
Interface A
{
Final Int a;
Void getdata();
}
Interface B
{
Final int b;
Void putdata();
}
Class C implements A , B
{
Int c;
Void getdata()
{
a=4;
System.out.println(a);
}
Void putdata()
{
b=5;
System.out.println(b);
}}
Class test
{
Public static void main(String args[]) {
test t1;
t1.getdata();
t1.putdata(); } }
Q.5. Why is java more suitable as compared to other language.
SOLUTION:
Java is more suitable as compared to other languages because of the following features
Object Oriented
Distributed
High Performance
Java is platform independent because of byte code which can be interpreted by any
Object Oriented:
Java is purely object oriented programming language.Data hiding,
Java is robust because Java works as usual when any extension is made in java.Java is
Java support multithreading because in java different parts of a program can execute
concurrently.
SOLUTION:
Java bytecode is the form of instructions that the Java virtual machine executes. Each
byte code opcode is one byte in length, although some require parameters, resulting in
some multi-byte instructions.
To understand the details of the bytecode, we need to discuss how a Java Virtual Machine
(JVM) works regarding the execution of the bytecode.
A JVM is a stack-based machine. Each thread has a JVM stack which stores frames. A
frame is created each time a method is invoked, and consists of an operand stack, an array
of local variables, and a reference to the runtime constant pool of the class of the current
method. Conceptually, it might look like this:
Figure . A frame
The array of local variables, also called the local variable table, contains the parameters
of the method and is also used to hold the values of the local variables. The parameters
are stored first, beginning at index 0. If the frame is for a constructor or an instance
method, the reference is stored at location 0. Then location 1 contains the first formal
parameter, location 2 the second, and so on. For a static method, the first formal method
parameter is stored in location 0, the second in location 1, and so on.
Q.7.How is platform independent feature of java implemented. Explain role of main
( ) method in execution of java program.
SOLUTION:
Java is platform independent because of its byte code creation by compiler that is handled
by Java Virtual Machine.
Byte code is of .class extension and that can be executed by any platform by their own
interpreter.
Main () method is the first method executed by CPU after that any methods are executed.
All objects are created inside the main( ) method and methods are called inside main( )
method.
SOLUTION:
Exceptional errors occurs during execution of program because in the time of program
execution some unusual condition occurs and disrupts the normal flow of execution.
such as a number division by zero, file not found , array index out of bound , arithmetic
exception etc.
An exception is an event, which occurs during the execution of a program, that disrupts
The purpose of exception handling mechanism is to provide a means to detect and report
suggests incorporation of a separate error handling code that performs the following
tasks.
try block
Statement that cause an exception
(Exception object creater)
Throws
exception object
Catch block
Statement that handle the exception
(Exception handler)
try try
{ {
statement ; statement;
} }
finally catch ( )
{ {
statement; statement }
Finally {
} Statement