Top Banner
67
Welcome message from author
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
Page 1: Core Java
Page 2: 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

Page 3: Core Java

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.

Page 4: Core Java

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

Page 5: Core Java

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++.

Page 6: Core Java

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.

Page 7: Core Java

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).

Page 8: Core Java

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

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

} }

Page 9: Core Java

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.

Page 10: Core Java

Data types

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

Page 11: Core Java

Primitive Data types

• float• double• Boolean• char

• byte• short• int• long

Page 12: Core Java

Derived Data types

• class• array

Page 13: Core Java

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.

Page 14: Core Java

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[];

Page 15: Core Java

Arrays

Page 16: Core Java

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

Page 17: Core Java

Operators

• Unary Operators + Unary Plus

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

Operator

Page 18: Core Java

Operators• Assignment Operators = Simple Assignment Operator• Arithmetic Operators

+ Additive Operator (used for String Concatenation)

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

Page 19: Core Java

Operators

• Equality and Relational Operators == Equal to

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

Page 20: Core Java

Operators• Conditional Operators && Conditional AND

|| Conditional OR?: Ternary Operator

Page 21: Core Java

Control Statements

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

Page 22: Core Java

Loops

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

Page 23: Core Java

Classes and Objects

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

Page 24: Core Java

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.

Page 25: Core Java

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

Page 26: Core Java

MethodsMethod declarationeg

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

Method Signaturecomprises method’s name and parameter type

EgcalculateAmount(int, int)

Page 27: Core Java

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.

Page 28: Core Java

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.

Page 29: Core Java

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;

Page 30: Core Java

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;

Page 31: Core Java

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.

Page 32: Core Java

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.

Page 33: Core Java

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.

Page 34: Core Java

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.

Page 35: Core Java

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.

Page 36: Core Java

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.

Page 37: Core Java

Throwable Class and Its Subclasses

Page 38: Core Java

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.

Page 39: Core Java

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.

Page 40: Core Java

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.

Page 41: Core Java

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

Page 42: Core Java

extends

Implements

Page 43: Core Java

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(); }

}

Page 44: Core Java

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(); }

}

Page 45: Core Java

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.

Page 46: Core Java

File handling in Java

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

Page 47: Core Java

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.

Page 48: Core Java

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

Page 49: Core Java

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

Page 50: Core Java

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.

Page 51: Core Java

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.

Page 52: Core Java

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).

Page 53: Core Java

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.

Page 54: Core Java

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

Page 55: Core Java

AWT Components

Buttons Canvas Checkbox Checkbox Group ChoiceLabel

List Scrollbar Text AreaText Field

Page 56: Core Java

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.

Page 57: Core Java

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.

Page 58: Core Java

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

Page 59: Core Java

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.

Page 60: Core Java

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.

Page 61: Core Java

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

Page 62: Core Java

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

Page 63: Core Java

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

Page 64: Core Java

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

Page 65: Core Java

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.

Page 66: Core Java

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.

Page 67: Core Java