Core Java

Post on 25-Nov-2014

152 views 3 download

Tags:

Transcript of Core Java

Java TechnologyJava is a high level programming language as well as a

powerful software platform. Programming LanguageDifferent editions of javaJava Standard EditionJava Enterprise EditionJava Micro Edition

Software Platform JVM

Java API

Overview• Methods.• Inheritance.• Access Specifiers• Interfaces and Packages• Exception Handling• Threading• File Handling

• Object Oriented Concepts.• History & Evolution.• Features. • Data type, variables and array.• Operators.• Control Statements.• Classes.

Object Oriented Programming

• Abstraction (essential characteristics of an object)• Encapsulation (wrapping up of data)• Polymorphism (processing of data in more than one

form)• Inheritance (capability of one class to inherit from the

other)

OOP is an approach for developing software in which data and behaviour are packaged together or encapsulated together as classes whose instances are objects.

OOP is based on certain principles

History & Evolution.

Java is a high level object-oriented programming language developed by James Gosling for Sun Microsystems. New language was first called Oak later renamed as Java. Java is developed including all the advantages of C++.

Features.

Java offers• Platform independence• Security• Multi threading • Automatic garbage collection.

Java is a high level programming language. It is a pure object oriented language.

Java Virtual Machine (JVM).

Java technology is based on the concept of a single Java virtual machine (JVM) -- a translator between the language and the underlying software and hardware.

We can develop and run Java on any device equipped with Java Virtual Machine (JVM).

Simple Java Programpublic class Example { public static void main (String args[])

{ System.out.println ("This is a simple Java program");

} }

Variable

Variable serves as place holders in memory for data. Different type of variables are used to store data in different format.

e.g.: int type can store integer values.

Data types

Data types are of two type. 1. Primitive data types2. Derived data types.

Primitive Data types

• float• double• Boolean• char

• byte• short• int• long

Derived Data types

• class• array

ArraysAn array is a container object that holds a fixed number of values of a single type.

The length of an array is established when the array is created.

Each item in an array is called an element, and each element is accessed by its

numerical index.

ArraysDeclarationSyntax

<data_type> []<array_name>

<data_type> <array_name>[]

Initializing at the time of declaration

Eg:int marks[]={40,45,34};

Eg:int []marks;int marks[];

Arrays

Operators• Unary Operators• Assignment Operators• Arithmetic Operators• Equality and Relational Operators• Conditional Operators• Type Comparison Operator

Operators

• Unary Operators + Unary Plus

Operator(indicates +ve)- Unary Minus++ Increment Operator-- Decrement Operator! Logical Complement

Operator

Operators• Assignment Operators = Simple Assignment Operator• Arithmetic Operators

+ Additive Operator (used for String Concatenation)

- Substraction Operator* Multiplication Operator/ Division Operator% Modulus Operator

Operators

• Equality and Relational Operators == Equal to

!= Not Equal to> Greater than>= Greater than or equal to< Less than<= Less than or equal to

Operators• Conditional Operators && Conditional AND

|| Conditional OR?: Ternary Operator

Control Statements

Statements that control the flow of a program .• if-else• switch• break• continue

Loops

Loops are programming constructs which enablesrepeated execution of a specific code.• while• do-while• for

Classes and Objects

In java class is defined as collection of variables and methods.Instance of a class is what we call an object.

Access specifierAccess specifiers are used to specify the visibility and accessibility of a class, member variables and methods. Java provides access specifiers such as:-

• public: can be accessed from anywhere . • private: can be accessed only within the same class.• protected: This modifier makes a member of the class available to all classes in the same package and all the sub classes of the class.

MethodsMethods are the functions built into a class. Method

declaration includes1)Modifiers such as public, private etc.2)Return types the data type of the value returned by the

method or void if the method does not return a value

3)Method name4)Parameter list comma delimited list of input parameters,

preceded by their data types enclosed by parenthesis

5)An exception list6)The method body enclosed btw braces

MethodsMethod declarationeg

public double calculateAmount(int x, int y){}

Method Signaturecomprises method’s name and parameter type

EgcalculateAmount(int, int)

Interfaces

In Java interface is nothing but the collection of methods with empty implementations and constant variables ( variables with static and final declarations ). All the methods in an interface are "public and abstract" by default. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

Interfaces

In Java interface is nothing but the collection of methods with empty implementations and constant variables ( variables with static and final declarations ). All the methods in an interface are "public and abstract" by default. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

PackagesIn java we use packages to organize related classes. A package

contains only classes and interfaces. A package have a hierarchical

structure similar to a directory structure.

Creating a package

To create a package put a package statement with a name at the top of source file .

Eg package myPackage;

Packages

Using a package

We can use an already created package by importing it. It is possible to import the whole package or a specific member.

Syntaximport package_name.*; orimport package_name.class_name;

Exception Handling

• The Java programming language uses exceptions to handle errors and other exceptional events. • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.• Java uses five keywords for exception handling.

Try, catch, throw, throws and finally.

Exception Handlingtry Program statements that we want to monitor for exceptions are contained within try block.throw to manually throw an exceptionthrows any exception that is thrown out of a method must be Specified by a throws clausefinally Any code that absolutely must be executed before a method returns is put in a finally block.

Try blocktry {// code

} catch and finally blocks . . .

•The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.

Catch blocktry

{ } catch (ExceptionType name)

{ } catch (ExceptionType name)

{ }

• Each catch block is an exception handler and handles the type of exception indicated by its argument.

Finally blockfinally

{//code

}

•The finally block always executes when the try block exits. •It allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.

Throw statement

throw someThrowableObject; • All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. •Throwable objects are instances of any subclass of the Throwable class.

Throwable Class and Its Subclasses

Error class:- When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.

Exception Class:-An Exception indicates that a problem occurred, but it is not a serious system problem. The Java platform defines the many descendants of the Exception class. These descendants indicate various types of exceptions that can occur.

Throws statement

modifiers> <return type> <method name>(<parameter list>) throws <list of Throwables> {

/* Java statements */ }

To specify what exceptions a method throws. Every method that throws exceptions should declare what exceptions it throws in the method declaration. <list of Throwables> is a space-separated list of the class Throwable and its subclasses.

Threading

•A thread can be defined as a single sequential flow of control within a program.• Threads are sometimes called lightweight processes. • Threads share the process's resources, including memory and open files. • Each thread is associated with an instance of the class Thread.

Defining and Starting a Thread

Thread can be implemented through any one of two ways1.extending the java.lang.Thread class2.implementing the java.lang.RunnableInterface

extends

Implements

extending Thread classpublic class HelloThread extends Thread {

public void run() {

System.out.println("Hello from a thread!"); } public static void main(String args[]) {

(new HelloThread()).start(); }

}

implementing Runnable interface

public class HelloRunnable implements Runnable {

public void run() {

System.out.println("Hello from a thread!"); } public static void main(String args[]) {

(new Thread(new HelloRunnable())).start(); }

}

Synchronization of Threads Every object in Java code has one lock, which is useful for ensuring that only one thread accesses critical code in the object at a time. This synchronization helps prevent the object's state from getting

corrupted. If a thread has obtained the lock, no other thread can enter the

synchronized code until the lock is released. When the thread holding the lock exits the synchronized code, the lock is

released. Now another thread can get the object's lock and execute the synchronized

code.

File handling in Java

•Introduction to Streams1.Node Streams2.Filter Streams3.Byte Streams4.Character Streams

Introduction to Streams•A Stream is a sequence of bytes travelling from a source to a destination over a communication path.•When a stream of data is being sent, it is said to be written and when a stream of data is being received it is said to be read.•Data in a stream can flow in one direction only. So we use separate streams for reading and writing data.•Java offers 1.java.io.InputStream class to read bytes of data from a source(keyboard). 2.java.io.OutputStream class to write bytes of data to a destination.

Node StreamsInput and Output streams that read from or write to a specific location such as a disk file or memory are called a Node Stream.Eg: FileInputStream, FileOutputStream.

Filter Streams

Filter streams are used to read data from one stream and write it to another.Eg: PrintStream

Byte StreamsByte streams work on eight bits of data.

Character Streams

Streams that work on 16-bit Unicode characters are called character streams.Eg:InputStreamReader,OutputStreamReader

Java Database Connectivity

JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. Java applications need to communicate with a database to perform tasks such as to •Store and update data in a database.•Retrieve the data stored in a database and present it in a proper format to users.

Java Database Connectivity

Sun Microsystems has introduced JDBC API as a part of JDK to enable Java Applications to communicate with a database. JDBC API takes care of converting Java commands to generic SQL queries.JDBC API submits queries to the JDBC Driver which in turn converts queries to a form that a particular DBMS/RDBMS can understand.

Java Applets

Applets are web based programs that can be downloaded and can execute on a computer. Applets run in a java enabled browser such as Internet Explorer, Netscape navigator etc. These are said to be java enabled because they have a built in java platform(JVM and Java API).

Life cycle of a Java AppletsLife cycle of an applets is implemented using the following methods.init() Method• is called the first time when an applet is loaded in the memory.•Using this can initialize variables and add components.start()Method• is called immediately after the init() and every time an applet receives focus.•use this method to restart a process.stop() Method •is called every time an applet loses its focus.•can use this method to reset variables and stop the threads that are running.destroy() Method•Is called when a user moves to another page.•Can use this method to perform clean up operations like closing a file.

Java AWT(Abstract Window Toolkit)

A class library is provided by the Java programming language which is known as Abstract Window Toolkit (AWT). A common set of tools is provided by the AWT  for graphical user interface design.

•A set of native user interface components•An event-handling model•Graphics and imaging tools, including shape, color, and font classes•Layout managers, for flexible window layouts that do not depend on a particular window size or screen resolution

AWT Components

Buttons Canvas Checkbox Checkbox Group ChoiceLabel

List Scrollbar Text AreaText Field

Basic User Interface Components

The super class of all graphical user interface objects is Component. The components are added to the Container object to create a Graphical User Interface (GUI).Visual controls such as text boxes, buttons, list boxes etc. are called components.Top level windows that hold these components are called containers.

Laying out an Interface Layout Management is a process that determines the size and position of the components in a container.

Layout Managers•Are special objects that determine how the components of a container are organized.•Java automatically creates and assigns a default layout manager to every container.

Laying out an Interface Commonly used layout managers in java are

1. Flow Layout2.Grid Layout3.Border Layout4.Card Layout5.Grid Bag Layout6.Box Layout

Event Driven Programming

The program waits for a user to perform an action. Each action that the user performs on the GUI, translates to a call to a function that handles the event. This approach is called event-driven programming. There are many types of events that are generated by your AWT application. These events are used to make the application more effective and efficient. Generally, there are twelve types of event are used in Java AWT.

The Delegation Event Model

A source generates an event and sends it to one or more listeners. The listener simply waits until it receives an event. Once received the listener processes the event and then returns.

EventAn event is an object that describes a state change in a source.

Components of an EventAn event object comprises of three components.1.Event object An event object contains the information related to the event such as category of the event, component that generated the event, and the time when the event occurred.2.Event Source3.Event Handler

Event ListenersA listener is an object that is notified when an event occurs. It has two major requirements.• It must be registered with one or more sources• It must implement methods to receive and process the notification

The methods that receive and process events are defined in a set of interfaces found in java.awt.event

Event ClassesJava.util.EventObject

Java.awt.AWTEvent

Item Event Adjustment Event Component Event Action Event Text Event

Focus Event Container Event Input Event Paint Event Window Event

Key Event Mouse Event

Adapter classes

Adapter classes help us in avoiding the implementation of the empty method bodies. Generally an adapter class is there for each listener interface having more than one method. Event package provides seven adapter classes.

Adapter classes

Adapter classes help us in avoiding the implementation of the empty method bodies. Generally an adapter class is there for each listener interface having more than one method. Event package provides seven adapter classes.