Chapter-1 Core Java Lecture-1: INTRODUCTION TO JAVA Java is a general-purpose Object Oriented programming language developed by Sun Microsystems of USA in 1991.Originally called Oak by James Gosling, one of the inventors of Java. Java features: Compiled and Interpreted Platform independent and portable Object Oriented
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Chapter-1
Core Java
Lecture-1:
INTRODUCTION TO JAVA
Java is a general-purpose Object Oriented programming language
developed by Sun Microsystems of USA in 1991.Originally called
Oak by James Gosling, one of the inventors of Java.
Java features:
Compiled and Interpreted
Platform independent and portable
Object Oriented
Robust and Secure
Distributed
Familiar, Simple and small
Multithreaded and Interactive
High Performance
Dynamic and Extensible
Java Environment:
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
application Programming Interface(API).
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 (for viewing Java applet)
javac(Java Compiler)
java(Java Interpreter)
jdb(Java debugger)
javadoc(for creating HTML documents)
javah(for C header file)
Application Programming Interface(API):
The java standard library or API includes hundred of classes and
methods grouped into several functional packages, most common
packages are
Language support package(java.lang.*)
Utilities package(java.util.*)
Input/Output package(java.io.*)
Networking package(java.net.*)
Databases package(java.sql.*)
Process of Building & running java application program:
Fig.1.1:Program development process
Types of java program:
Java program can be developed in two ways as follows
stand alone application
web applets
Text editor
java source code
javac
java class file
java
java program output
javadoc
header file
HTML file
javah
jdb
Stand alone application can be executed by java interpreter and we
applets can be executed by java enabled web browser for example
internet explorer.
Format of Java program:
class classname
{
public static void main(String args[ ])
{
System.out.println (“java is better than C++”);
}
}
Java Virtual Machine (JVM):
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 the computer
memory.
It is a simulated computer and does all major functions of a real
computer.
Process of Compilation:
Process of converting byte code into machine code:
The virtual machine code is not machine specific.
DATA TYPES IN JAVA
Data type specify the size and type of values that can be stored. Every variable in java has
a data type.
Data type can be divided into two types as follows
primitive data type
non-primitive data
Primitive data type can be divided into two types as follows
Numeric
java source code java compiler byte code
Virtual machine
byte code java interpreter machine code
real machine
Non Numeric
Numeric is divided into integer and floating point.
Integer is divided into byte, short, int, long
Floating point is divided into float and double.
Non-numeric can be divided into char(character) and Boolean.
Non-primitive data type can be divided into 3 types as follows
classes
interfaces
arrays
Different types can be described in table as follows:
Table 1.1.Data Type
Data Type Size Minimum value
Maximum value
byte 1 byte -128 127
short 2 byte -32,768 32,767
int 4 byte -2,147,483,648 2,147,483,647
long 8 byte
float 4 byte 3.4e-038 3.4e+038
double 8 byte 1.7e-308 1.7e+308
char 2 byte
boolean 1 bit
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,
Subject to the following conditions:
They must not begin with a digit.
Upper case and lower case are distinct.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
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:
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.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.
Advantages of Java Array:
1. An array can hold primitive types data. 2. An array has its size that is known as array length. 3. An array knows only its type that it contains. Array type is
checked at the compile-time.
Disadvantages of Java Array:
1. An array has fixed size. 2. An array holds only one type of data (including primitive
types).
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 array of integers
called a.
public class Array{ public static void main(String[] args) { int[] a; }}
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 is an example of
how to create an array that has 5 elements.
public class Array{ public static void main(String[] args) {
int[] a = new int[5]; }}
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.
public class Array{ public static void main(String[] args) { int[] a = {12, 23, 34, 45, 56}; }}
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 how to set the values for an array of 5 elements.
public class Array{ public static void main(String[] args) { int[] a = new int[5]; a[0] = 12; a[1] = 23;
a[2] = 34; a[3] = 45; a[4] = 56; }}
A much more useful way of using an array is in a loop. Here is an
example of how to use a loop to set all the values of an array to 0
which you will see is much easier than setting all the values to 0
seperately.
public class Array{ public static void main(String[] args) { int[] a = new int[5]; for (int i = 0; i < 5; i++) a[i] = 0; }}
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 then it is swapped. Here
is an example.
public class Array{ public static void main(String[] args) { int[] a = {3, 5, 1, 2, 4}; int i, j, temp; for (i = 4; i >= 0; i--) for (j = 0; j < i; j++) if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } }}
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 between the 2 in a
better way.
All that you need to do to create and use a 2D array is use 2 square brackets instead of 1.
public class Array{ public static void main(String[] args) { int[][] a = new int[3][3]; a[0][0] = 1; }}
CONTROL STATEMENTS
Java Control statements control the order of execution in a java
program, based on data values and conditional logic. There are
three main categories of control flow statements;
Selection statements: if, if-else and switch.
Loop statements: while, do-while and for.
Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution
Selection Statements
The If Statement
The if statement executes a block of code only if the specified
expression is true. If the value is false, then the if block is skipped
and execution continues with the rest of the program. You can
either have a single statement or a block of code within an if
statement. Note that the conditional expression must be a Boolean
expression.
The simple if statement has the following syntax:
if (<conditional expression>) <statement action>
The If-else Statement
The if/else statement is an extension of the if statement. If the
statements in the if 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
must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>) <statement action> else
<statement action>
Switch Case Statement
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 switch statement
begins with a keyword, followed by an expression that equates to a
no 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.
Its general form is as follows:
switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> ... case labeln: <statementn> default: <statement>} // end 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.
Iteration Statements
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 false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)<statements>
Do-while Loop Statement
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 have a single statement or a block of code within the do-
while loop.
The syntax of the do-while loop is
do<loop body>while (<loop condition>);
Below is an example that creates A Fibonacci sequence controlled by a do-while loop
public class Fibonacci {
public static void main(String args[]) {System.out.println("Printing Limited set of
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.
Format of Applet program:
Import java.awt.*;
Import java.applet.*;
Public class appletclassname extends Applet
{
………………..
………………..
Public void paint(Graphics g)
{
………………..//Appletsoperations code
…………………
}
}
Applet Life cycle:
The different states of applet life cycles are
Born state or initialization state
Running state
Idle state
Dead state
Initialization state:
Applet enters initialization state when it is first loaded
Init( ) function is used.
Syntax
Public void init( )
{
…………//Action
……………..
}
Running State:
Applet enters running state when the system calls the start method.
Syntax
Public void start( )
{
…………………….//Action
…………………….
}
Idle or stopped state:
An applet becomes idle when it is stopped from running.
Syntax
Public void stop( )
{
……………….//action
……………….
}
Dead state:
An applet is said to be dead when it is removed from memory.
Syntax
Public void destroy( )
{
………………//Action
……………….
}
1.16.QUESTIONS AND SOLUTIONS FROM PREVIOUS UNIVERSITY EXAMS
Q1.What is multithreading? Explain the life cycle of a thread.
SOLUTION:
Multithreading is a conceptual programming paradigm where a
program (process) is divided into two or more subprograms
( processes ), which can be implemented 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 independently and
simultaneously.
class ABC{
}
Beginning
End
Single-Threaded body of execution
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 among all of them.
The ability of a language to support multithreads is referred to as
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.
Multi-Threaded Program
StartStart
Start
Thread A Thread B Thread C
Main Thread
Main Method module
Life cycle of a Thread:
Life cycle of a Thread can have four states:
● New
● Runnable
● Blocked
● Dead
Diagram for Life cycle of a thread:
New state of Thread:
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
started executing code inside of it. A certain amount of
bookkeeping needs to be done before a thread can run.
Runnable state of a Thread:
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.
Blocked state of a Thread
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. 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.
Dead state of a Thread:
A thread is dead for one of two reasons:
● It dies a natural death because the run method exits normally.
● It dies abruptly because an uncaught exception terminates the
run method.
In particular, you can kill a thread by invoking its stop method.
That method throws a ThreadDeath error object that kills the
thread.
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;
class NoMatchException extends Exception
{
NoMatchException(String message)
{
super(message) ;
}
}
class TestNoMatchException
{
public static void main(String args[])
{
String m;
Scanner s=new Scanner(System.in);
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 can be used for internet programming.
It can be used to extend the capabilities of html web-pages.
Difference between java applet and Java programs:
Q.4. What is an interface ? Explain with a suitable example. How multiple
Inheritance is implemented in java.
SOLUTION:
---Java applets are small java program used in internet programming by embedding inside html documents.
---Java applets are embedded inside html document and enhance capabilities of html webpages
--Java applets cannot have main() method.
--Java applets can only be executed in web browser or appletviewer.
----Java programs are programs used for applications development.
--Java programs cannot embedded inside html document.
--Java programs must have main () method.
---Java programs can be executed by java interpreter.
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
Example of interface to implement multiple inheritance:
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);
Class C
}
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
Platform independent and portable
Object Oriented
Robust and Secure
Distributed
Familiar, Simple and small
Multithreaded and Interactive
High Performance
Dynamic and Extensible
Compiled and Interpreted
Platform independent and Portable
Java is platform independent because of byte code which can be
interpreted by any system. Because of platform independent java is
portable.
Object Oriented:
Java is purely object oriented programming language.Data hiding,
encapsulation,polymorphism,inheritance properties are present.
Robust and Secure:
Java is robust because Java works as usual when any extension is
made in java.Java is secure because of its byte code and case
sensitiveness.
Familiar, Simple and small
Java is easy to understandable ,small and familier.
Multithreaded and Interactive:
Java support multithreading because in java different parts of a
program can execute concurrently.
Dynamic and Extensible
Java works dynamically and can be easily extensible.
Q.6. What do you mean by byte code .Explain its working..
SOLUTION:
Byte code is a code formed by compiler in java having .class
extension
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.
Diagram for platform independence:
Java Source file(.java file)
Byte code (.class file)
Windows system(having JVM)
Unix system(having JVM)
Solaris system(having JVM)
Role of main() method:
Main( ) method is a static method that can automatically called without use of any objects creation.
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.
Without main ( ) method no program is created in java application.
Q.7.Why exceptional errors occurs during execution of program. Discuss usage of finally block.
SOLUTION:
Unix interpreter Solaris interpreterWindows interpreter
Exe fileExe fileExe file
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 normal flow of the program's
instructions.
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. The mechanism suggests
incorporation of a separate error handling code that 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 the exception)
Diagram and Syntax of exception handling code:
Usage of finally block.
try blockStatement that cause an exception (Exception object creater)
Catch blockStatement that handle the exception (Exception handler)
Throws exception object
Finally is a keyword used in exception handling mechanism?
Finally is
Written after try and catch statement .The statements written inside
finally is must execute whether there is exception found or not.