Java Assignment 1
Java Assignment 1
ASSIGNMENT
Submitted By
ARCHANA SURENDRAN
I M.sc Mathematics
Writing in the Java programming language is the primary way to produce code that will
be deployed as byte code in a Java virtual machine (JVM); byte code compilers are also
available for other languages, including Ada, JavaScript, Python, and Ruby. In addition,
several languages have been designed to run natively on the JVM,
including Clojure, Groovy, and Scala. Java syntax borrows heavily from C and C++, but
object-oriented features are modeled after Smalltalk and Objective-C.[12] Java eschews
certain low-level constructs such as pointers and has a very simple memory model
where objects are allocated on the heap (while some implementations e.g. all currently
supported by Oracle, may use escape analysis optimization to allocate on
the stack instead) and all variables of object types are references. Memory
management is handled through integrated automatic garbage collection performed by
the JVM.
UNIT 1
OBJECT –ORIENTED PROGRAMMING CONCEPT
The object-oriented programming concept is based on three basic concepts.They are:
1. Encapsulation
2. Inheritance
3. polymorphism
Encapsulation
Inheritance
The properties of a class prepared for doing task can be inherited into another class and
only the additional capabilities required are to be added in that to perform the new task
is known as the property of inheritance.
Polymorphism
Polymorphism refers to the behavior of the same entity behaving differently at different
situations.
Java does not provide any pointers. Hence the memory location of a system cannot be
accessed through a Java program. Therefore, any program developed in java cannot be
used to hack a system.
Robust
Errors that occur at runtime can be handled easily in java.java provides exception
handling features to overcome many runtime problems , like divide by zero, array index
out of range,file not found etc. Using this feature, a user can properly exit or come out
smoothly without the program hanging. Therefore programs written using java language
are robust
Multithreaded
Java language provides an environment by which several tasks can be initiated and
managed easily. Such a feature is called multithreading.
Internet ready
Java has the capability to handle TCP/IP packets. Hence Java can be used for internet
application.
Simple
Java is not that simple to learn. It s because the capabilities of Java tools are high and
one needs to put an effort to understand the Java programming concepts and use them.
JAVA ARCHITECTURE
JAVA CONSTANTS
Literals, data types and variables are called Java Constants
Literals
Entities that do not change their values in a program are called constants or literals
1)Integer literals
A whole number is called as an integer. Java supports three types of integer literals:
octal, decimal and hexadecimal
Numbers with decimal point and fractional values are called floating point literals.
3) Character literals
Single characters in java are called character literals.. Java character literals are written
within a pair of single quote.
4) String literals
A sequence of characters written within a pair of double quote is called string literal.
5) Boolean Literals
Data types
1. Integers
Float – In float type, the numbers are specified in 32- bit width.
Double- The double type floating point numbers are represented in 64- bit width. It is
declared by the keyword double.
3.Character type
4.Boolean type
The logical values true and false are handled by Boolean type.
Variables
A variable is any combination of letter, number, underscore and $ sign. It takes different
values during the execution of the program.
1. Arithmetic operators
Arithmetic operators operate on numeric type variables and numeric literals. It includes
add, subtract, multiply, divide, modulus
2. Bitwise operators
Bitwise operators are used to manipulate individual bits of a data item. It includes
Bitwise NOT, Bitwise AND, Bitwise OR, Bitwise exclusive OR, Left shift, Right shift,
Right shift zero fill
3.Relational Operators
Relational operators are used to relate a iven value with several possible values of a
variable. Relational operators include Equal to, Not equal to, Greater than, Greater than
or equal to, Less than, Less than or equal to.
4. Boolean Logical Operators
Logical operators operate only on Boolean operand and not on numeric operands. It
includes Logical AND, Logical OR, Logical XOR, Short-circuit OR, short-circuit AND,
Logical unary NOT, Equal to, Not equal to, Ternary if-else.
CONTROL STATEMENTS
THE if…else STATEMENT
This statement helps to select one out of two possibilities based on the given condition.
The general form of statement is
if (conditional expression)
Statement 1;
Else
Statement 2;
The switch statement helps to select one out of many choices.The general form is
switch(expression){
break;
break;
break;
Default: statement;
}
The while STATEMENT
the while statement is used for looping or iterating a block of statements while the given
condition is true. The general form is given by
while(condition)
Statements
The do..while statement is used for looping a block of statements while the given
condition is true. The general form is
do
Statements;
} while(condition);
This statement is a self contained one that is the initial value,termination condition,
iterator are all given in the for structure itself. The general form is given by
for (initialize;condition;iterator)
Statements;
}
THE break STATEMENT
Java allows multiple initialization and iteration in the for statement. With this capability,
more than one variable can be initialized and more than one iteration can be done.
Each of such statements are to be separated by comma.
ARRAYS
An array is a variable representing a collection of like-typed data.
In Java an array is created in two steps. First an array variable is to be declared and
then an array object is to be created using new operator by specifying the number of
memory locations required. Java supports multi dimensional arrays. A conventional
matrix can be represented in a two-dimensional array.
UNIT 2
CLASSES
Classes are the basic building blocks for object –oriented programming in Java. A class
defines the data, how it is accessed and the methods that manipulate the data. The
variables declared in a class are called instance variables.
The dot operator is used to access the instance variables and methods defined in that
object.
CONSTRUCTORS
Constructor is used to assign initial values to an object when it is created. They are
used to initialize the instance variable. One constructor of a class can refer to another
constructor of the same class through the keyword this.
METHOD OVERLOADING
Methods of a class with the same name but with different type signature are called
overloading methods. Overloading methods exhibit the concept of polymorphism.
INHERITANCE
An existing class can be extended by adding additional capabilities. Such a class is
called a subclass. Subclasses inherit all the properties of the parent classes.this
process is known as inheritance.
METHOD OVERRIDDING
A method in a subclass having the same name and type signature of a superclass
method is called overriding method. Overriding method exhibits polymorphism property.
FINAL CLASS
FINAL METHOD
Methods can be declared with the modifier final. Methods declared as final cannot have
overriding methods in subclasses.
FINAL VARIABLES
When object are created, they occupy some memory space of the computer. When an
object is no more in use, Java identifies them automatically and frees the memory. This
is called garbage collection.
There is no separate destructor method in Java. In certain situations, object may use
other than memory, like a file or a system resource. In such cases care must be aken to
free those resources before the object is destroyed. In order to provide such a facility,
Java has finalize method. This method can be put inside the class. Before an object is
destroyed, java runs the finalize method. The user can define whatever action to be
taken inside the finalize method.
RECURSION
When a method calls itself, it is called recursion. There are problems which can be
programmed easily using recursion. Recursive method need stack memory. It is
inefficient in terms of time. Java supports recursive method.
Java provides a mechanism ,in which methods can be called without an instance of a
class. Such methods are called static methods. It is declared by using the modifier
static.
When a variable is declared as static, it becomes a class variable rather than an object
variable. Static variables can be accessed by any part of the program. Even if an
instance is created, the static variables retain the last modified value.
In certain cases, it may be needed to execute a set of statements ina class only once
and independent of the instance. In java such statements can be placed in a block and
declared as static. Such blocks are called static block.
ABSTRACT CLASSES
Java allows defining of methods without body and such methods are called abstract
methods. Abstract methods are defined with a keyword abstract. A class containing an
abstract method is called as an abstract class.
Java has a Gregorian calendar contained in java.util package. This class has several
methods to handle date, year, month, day, hour, minutes, AM , PM etc. one can make
use of this class whenever time and date related information is needed from the system.
Package statement is used to identify the location where a class is stored in the
directory. This is necessary to identify a class when you want to use that class in any
other class in any other directory.. thus packages help to manage large number of
classes.
Interfaces define methods without body. They are similar to abstract class, but differ in
their functionality
WRAPPER CLASS
Number class
The abstract class number contains six concrete subclasses to wrap the simple types
byte, short, int, long, float and double.
Byte- Byte is a wrapper class of byte. The constructors for Byte are Byte(byte number)
and Byte(String str).
Short – short is a wrapper class for short. The constructors for short are short(short n)
and short (String s)
Integer class- The integer class wraps the simple type int. the constructors in int are
Integer(int n) and Integer (String s).
Long class- The long class is used to wrap long type. The constructors of long class
are Long(long n) and Long(String s).
Float class – The float class wraps the float type.the constructors in float are Float
(double x), Float(float x) and Float String s).
Double class – The double class wraps the double type. The constructors in double are
Double (double x) and Double (Strings).
Character class –The character class wraps the char typr. The constructor is Character
(char C).
Boolean class – The Boolean class wraps the Boolean type. The constructors
inBoolean class are Boolean ( Boolean b) and Boolean (String s).
UNIT 3
EXCEPTIONS
The throwable class has two subclasses. Exception and Error. Exception again has two
subclasses, IO Exception and Runtime Exception.
Runtime exception
Exception occurring in the program code at runtime are handled in this class. Divide by
zero error, array index out of bound, wrong cast and null pointer access are of this type.
IOException
Exceptions occurring while accessing I/O devices are handled in this class. File not
found, end of file, encountered are of this type.
Exception
In this class, a user can create ones‘s own exception and use it in java program.
Error
Errors which are beyond the control of the programmes are dealt in this class. Disk full
and memory not enough are of this type. Java does not provide any mechanism to
handle them and should not be caught.
CATCHING EXCEPTION
Java developers have identified commonly occurring exceptions and they are specified
in the Exception. When such exception appear in a program at runtime, they are to be
brought and handled. The exception is caught by try…catch mechanism.
RETHROWING EXCEPTION
Creating an exception
new ThrowableClass();
or
new ThrowableClass(String s)
It is important to bradcast that the method is going to throw an exception, so that the
caller of that method can handle the exception appropriately. Exceptions of type Error
that cannot be handled at all the Runtime exception that could have been avoided by
the programmer should not be bradcast. Only exception other than Error or runtime
exception can be bradcast. The bradcasting is done using the throws keyword. The
broadcasting is made while declaring the method.
Java treats all data as a stream of bytes or characters. A large number of classes, to
deal with disk files, memory and source/ destination independent process are available
in Java.
Data used in Java are handled in two streams, byte stream and character stream.
The file class
The file class is used only to know the details about a file. It cannot be used to read or
write bytes into a file. It helps to study a file before handling it. The file class has the
following constructors:
BYTE STREAM
In this, stream data are accessed as a sequence of bytes. All types other than character
or text are dealt in this stream. It has two abstract classes Inputstream and
OutputStream
The two abstract classes, InputStream and Outputstream have a number of concrete
subclasses which implement the abstract methods. Only objects of these subclasses
can be created for input stream and output stream. FileInputStream and
FileOutputStream are subclasses of Inputstream and OutputStream.
FileInputStream
This class is used to read bytes from a disk file. The FileInputStream class has the
following constructors: FileInputStream(String filename) and FileInputStream(File
fobject)
FileOutputStream
This class is used to write bytes into a disk file. The FileOutputstream class has the
following constructors are FileOutputstream(string filename), FileOutputStream(file
fobject) and FileOutputStream(String filename,Boolean append)
FILTERED BYTE STREAMS
Each stream in java provides methods to access the data in different forms. The basic
byte streams access the data in byte form. The raw byte cannot be used for any useful
purpose. For converting bytes to useful forms such as char,string,int etc Java has
several streams. These streams work on other streams and convert byte to useful form
or viceversa. Such streams that can take other streams as argument are called filtered
streams. The Java has FilterInputStream and FilterOutputstream.
DataOutputstream
It is a subclass of FilterOutputstream. The method in this class help to convert the basic
types to bytes and pass it to an underlying output stream. The write methods in this
class help to create an output stream which can be read by the methods in
dataInputStream.
DataInputstream
String()
String(char charray[])
String(string strObject()
Strings that need modification are handled by StringBuffer class. After creating a
StringBuffer new strings can be inserted or appended to it. The size of StringBuffer can
grow whenever needed. StringBuffer objects can be dynamically altered. When a
StringBuffer is created, space for 16 more characters is always appended with it. This
helps the StringBuffer object to grow by 16 more characters without any other process.
That is, the size of the StringBuffer is the number of characters in that string plus 16.
When the string grows beyond the free 16 character space, the StringBuffer is relocated
to a new memory space with the required size. StringBuffer type objects are safe to use
in multithreaded environment.
There is yet another class StringBuilder to handle mutable or flexible string. It has all the
methods defined in StringBuffer class. StringBuilder type strings are not safe to use in
multiple threads.
THREADS
A single task can be divided into a number of small sub tasks. Each subtask can be
executed as an independent process. Such a process is known as thread.
Multitasking
When more than one task is processed by a computer it is called multitasking.. this is
being done to utilize the idle time of a CPU more effectively. Each task has its own set
of variables and separate memory location for them.
Multithreading
Creating a thread
States of a thread
When athread is created,it goes to different states before it completes its task and is
dead. The different states are new ,runnable ,running ,blocked and dead.
new thread
when a thread is created, it is in a new state. In this state the thread will not be
executed.
runnable thread
when the start() method is called on the thread object, the thread is in runnable state. A
runnable thread need not be executed by the CPU. A runnable thread joins the
collection of threads that are ready for execution.
running threads
blocked threads
A running thread may go to the blocked state due to the following reason
dead thread
A thread becomes dead on two occasions. In the first case, a thread completes it task,
exits the running state and becomed dead. In other case, the run method is aborted,
due to the occurrence of an exception and the thread becomes dead.
THREAD PRIORITIES
Threads can be assigned priorities. The priorities are used by the operating system to
find out which runnable thread is to be given in the CPU time. Priorities are given by the
priority numbers ranging from 1 to 10.. a thread with higher priority number will be given
prefernc over the threads with lower priority numbers.
Applets are programs that can be downloaded from a foreign machine through a
network and executed in a local machine. Applets are not controlled by the local
operating system. Applets cannot access local resources in the computers. Applets are
split in small packets called byte codes and travel across the network. These bytecodes
arereassembledin java virtual machine in the receiving machine and are executed by
the browser.
Applets cannot access the local resources like disk and floppy. Applets cannot be
executed directly. An applet can only be an element of an HTML page. Applets are used
for client side programming.
Applets do not use main() method and System.out.println(0 method. Applets use oly
graphics methods for output. They generate window based output. Therefore, they need
graphics support.
Applets are created, executed, stopped and destroyed by appropriate methods provided
in applet class. All these activities are carried out by the following methods. They are
called life cycle methods. These methods are called by AWT automatically.
paint() - This method is called after the start method. The user screen is drawn
using the paint() method.
stop() - This method is called automatically when a user leaves the page containing
the applet. Hence it can be called repeatedly
Destroy() - This method is called automatically when the browser ends the activity. This
method helps to release the resources used by the applet.
The HTML APPLET TAG
An applet can be an element of an HTML page. The applet statement itself has its own
structure and is called applet tag. The individual components define behaviours and
properties of an applet.
Applet can read data defined in the applet tag using PARAM attribute. Ti is one of the
way to bring data into the applet. The getParameter() returs a String type. Therefore,if
numeric values are defined, they are to be converted from String to numeric types
GRAPHICS
Java provides a variety of tools for designing graphics and graphical user interface. All
such tools are provided in Abstract Window Toolkit (AWT). This package contains a
large number of classes. Graphics tools are available in java.awt.Graphics class. To
draw graphics object,a window is needed. One way to obtain a window is by creating an
applet which automatically creates panel type window. Alternatively a Frame window
can also be used.
CONCLUSION
There are many places where Java is used in the real world, starting from a commercial
e-commerce website to android apps, from scientific application to financial applications
like electronic trading systems, from games like Minecraft to desktop applications like
Eclipse, Netbeans, and IntelliJ, from an open-source library to J2ME apps, etc
Java is very big in Financial Services. Lots of global Investment banks like Goldman
Sachs, Citigroup, Barclays, Standard Charted, and other banks use Java for writing
front and back office electronic trading systems, writing settlement and confirmation
systems, data processing projects, and several others.
Java is also big on E-commerce and web application space. You have a lot of rest full
services being created using Spring MVC, Struts 2.0, and similar frameworks. Even
simple Servlet, JSP, and Struts based web applications are quite popular on various
government projects. Many governments, healthcare, insurance, education, defense,
and several other departments have their web application built in Java.
In 1990s Java was quite big on Internet due to Applet, but over the years, Applet's lost
its popularity, mainly due to various security issues on Applet's sand boxing model.
Today desktop Java and Applets is almost dead. Java is by default Software industries
darling application development language, and given its heavy usage in financial
services industry, Investment banks and E-commerce web application space, any one
learning Java has bright future ahead of him. Java 8 has only reinforced the belief that
Java will continuing dominating software development space for years to come