Chapter-1 Core Java
Chapter-1 Core Java
Core Java
Lecture-1:
INTRODUCTION TO JAVA
Java features:
Object Oriented
Distributed
Java Environment:
The Java Development Kit comes with a collection of tools that are
javac(Java Compiler)
java(Java Interpreter)
jdb(Java debugger)
packages are
Utilities package(java.util.*)
Input/Output package(java.io.*)
Networking package(java.net.*)
Databases package(java.sql.*)
javac
java jdb
web applets
internet explorer.
class classname
}
}
for a machine that does not exist. This machine is called the java
memory.
computer.
Process of Compilation:
Virtual machine
real machine
a data type.
non-primitive data
Numeric
Non Numeric
classes
interfaces
arrays
Different types can be described in table as follows:
long 8 byte
char 2 byte
boolean 1 bit
VARIABLE
A variable is an identifier that denotes a storage location used to
store a data value. A
OPERATORS
Conditional Operator ?:
Lecture-2:
ARRAYS
name. The java array enables the user to store the values of the
when required.
Declaring an array:
except that you must put a set of square brackets after the variable
called a.
assign memory to the array when we declare it. When you assign
Using an array:
You can access the values in an array using the number of the
which you will see is much easier than setting all the values to 0
seperately.
Sorting an array
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
the array and if it is greater than that value then it is swapped. Here
is an example.
2D arrays:
can have values that go not only down but also across. Here are
better way.
All that you need to do to create and use a 2D array is use 2 square
brackets instead of 1.
CONTROL STATEMENTS
Java Control statements control the order of execution in a java
Selection Statements
The If Statement
and execution continues with the rest of the program. You can
expression.
if (<conditional expression>)
<statement action>
else
<statement action>
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 an outer switch.
the next case. Therefore, if you want to exit in the middle of the
code block.
Iteration Statements
While Statement
loop begins with the keyword do, followed by the statements that
make up the body of the loop. Finally, the keyword while and the
can either have a single statement or a block of code within the do-
while loop.
do
<loop body>
while (<loop condition>);
For Loops
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
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
particular, leaving out the <loop condition> signifies that the loop
CLASSES
A class is nothing but a blueprint or a template for creating
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
int length;
int breadth;
int height;
METHODS
java programming.
// code statements }
Lecture-3:
INHERITANCE:
Defining a Sub-class:
variables declarations;
methods declarations;
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 volume1=room1.volume( );
System.out.println(area1);
System.out.println(volume1);
Multiple inheritance:
A B
Hierarchical inheritance:
B C D
Multi-level inheritance:
Lecture-4:
C
EXCEPTION HANDLING
program's instructions.
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
{
float z =(float) x / (float) y;
if(z<0.01)
catch (MyException e)
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
finally
}
Lecture-5
MULTITHREADING
Single-Threaded
body of execution
End
}
Single-Threaded Program
Main Thread
Main Method
module
Once initiated by the main thread, the threads A,B and C run
concurrently Start
and share the resources Start
Start jointly. It is like people living
application program and share the same memory space, they are
Multi-Threaded Program
Thread States
Threads can be in one of four states:
● New
● Runnable
● Blocked
● Dead
New Threads
When you create a thread with the new operatorfor example, new
This means that it is in the new state. When a thread is in the new
Runnable Threads
runnable state.)
Blocked Threads
A thread enters the blocked state when one of the following actions
occurs:
return to its caller until input and output operations are complete.
another thread.
Fig 1.5.Life cycle of Thread
A thread moves out of the blocked state and back into the runnable
state by one of the
following pathways.
Dead Threads
run method.
Declaring a thread:
…………..
………….
………….
……………
}
athread.start( )
Example:
}}
}}
}}
class threadtest
{
new A( ).start( );
new B( ).start( );
new C( ).start( );
}}
Lecture-6
COLLECTIONS:
package.
ArrayList:
LinkedList:
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);
a1.size( ) );
a1.remove(new Integer(30) );
a1.remove(0);
System.out.println(“Array list %s ; size:%d” a1.tostring( ) ,
a1.size( ) );
Lecture-7
I/O STREAMS
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.
features for creating and manipulating streams and files for reading
1. InputStream classes
2. OutputStream classes
FileInputStream
DataInputStream
ObjectInputStream
BufferedInputStream
FileOutputStream
DataOutputStream
ObjectOutputStream
BufferedoutputStream
1. Reader classes
2. Writer classes
Import java.io*;
int i ;
FileInputStream fin;
Try
Catch( FileNotFoundException e )
Return;
Catch(ArrayIndexOutOfBoundException e)
System.out.println(“java filename”);
Return;
System.out.print( (char)i);
Fin.close( );
}}
Lecture-8
Abstract windows toolkit contains all the classes for creating user
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( ) );
Lecture-9
APPLET PROGRAMMING
Applets are small java programs that are primarily used in internet
computer to another and run using the Applet viewer or any web
Import java.awt.*;
Import java.applet.*;
………………..
………………..
Public void paint(Graphics g)
………………..//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:
simultaneously.
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
application program and share the same memory space, they are
Main Thread
Main Method
module
Start Start
Start
Multi-Threaded Program
Life cycle of a Thread:
● New
● Runnable
● Blocked
● Dead
When you create a thread with the new operator for example, new
Thread( ) the thread is not yet running. This means that it is in the
new state. When a thread is in the new state, the program has not
A thread enters the blocked state when one of the following actions
occurs:
that is, an operation that will not return to its caller until input and
A thread moves out of the blocked state and back into the runnable
state by one of the following pathways.
run method.
thread.
SOLUTION:
import java.import.Exception;
class NoMatchException extends Exception
NoMatchException(String message)
super(message) ;
class TestNoMatchException
String m;
System.out.println(“enter a string”);
m=s.next( );
try
{
If(m!=”INDIA”)
catch (NoMatchException e)
System.out.println(“Caught NoMatchException”);
System.out.println(e.getMessage());
} } }
SOLUTION:
Applets are small java programs that are primarily used in internet
computer to another and run using the Applet viewer or any web
method.
Usage of Applet:
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:
Object Oriented
Distributed
Familiar, Simple and small
High Performance
portable.
Object Oriented:
sensitiveness.
SOLUTION:
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.
SOLUTION:
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:
such as a number division by zero, file not found , array index out
of bound , arithmetic exception etc.
instructions.
following tasks.
try block
Statement that cause an exception
(Exception object creater)
Throws
exception object
Catch block
Statement that handle the exception
(Exception handler)
Usage of finally block.
try try
{ {
statement ; statement;
} }
finally catch ( )
{ {
statement; statement }
Finally {
} Statement