java core - detailed overview

41
Java http://thebuddhatree.blogspot.in/ 1. Introduction to Computers and Java Introduction Computers: Hardware and Software Machine Languages, Assembly Languages and High- Level Languages Introduction to Object Technology Operating Systems Programming Languages Java Development Environment Test-Driving Java Application 2. Introduction to Java Applications Introduction Write Your First Program in Java Modifying Your First Java Program Displaying Text Adding Integers Memory Concepts Arithmetic 3. Introduction to Classes, Objects, Methods and Strings • Introduction Declaring Class with Method and Instantiating Object of a Class Declaring a Method with Parameter Instance Variables, set getter Methods Primitive vs. Reference Types Initializing Objects with Constructors Floating-Point Numbers and double 4. Control Statements: Part 1 • Introduction • Algorithms Control Structures if Statement if...else Statement while Statement Compound Assignment Operators Increment and Decrement Operators Primitive Types

Upload: buddha-tree

Post on 16-Apr-2017

235 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java  core - Detailed Overview

Java

http://thebuddhatree.blogspot.in/

1. Introduction to Computers and Java

• Introduction• Computers: Hardware and Software • Machine Languages, Assembly Languages

and High- Level Languages • Introduction to Object Technology • Operating Systems • Programming Languages • Java Development Environment • Test-Driving Java Application

2. Introduction to Java Applications

• Introduction • Write Your First Program in Java • Modifying Your First Java Program • Displaying Text• Adding Integers • Memory Concepts • Arithmetic • Decision Making: Equality and Relational • Conditional Operators

3. Introduction to Classes, Objects, Methods and Strings

• Introduction • Declaring Class with Method and Instantiating

Object of a Class • Declaring a Method with Parameter • Instance Variables, set getter Methods • Primitive vs. Reference Types • Initializing Objects with Constructors • Floating-Point Numbers and double

4. Control Statements: Part 1 • Introduction • Algorithms • Control Structures • if Statement • if...else Statement • while Statement • Compound Assignment Operators • Increment and Decrement Operators • Primitive Types

Page 2: Java  core - Detailed Overview

Java

http://thebuddhatree.blogspot.in/

5. Control Statements: Part 2

• Introduction • Essentials of Counter-Controlled Repetition • for Repetition Statement • Examples Using the for Statement • do...while Repetition Statement • switch Multiple-Selection Statement • break and continue Statements • Logical Operators • Structured Programming Summary

6. Methods

• Introduction • Program Modules in Java • static Methods and static Fields • Methods with Multiple Parameters • Method-Call Stack and Activation Records • Argument Promotion and Casting • Java API Packages • Scope of Declarations • Method Overloading

7. Arrays and ArrayLists • Introduction • Arrays • Declaring and Creating Arrays • Arrays Examples • Enhanced for Statement • Passing Arrays to Methods • Multidimensional Arrays • Variable-Length Argument • Using Command-Line Arguments • Class Arrays • Collections and Class ArrayList

8. Classes and Objects: In Detail • Introduction • Controlling Access to Members • Referring to the Current Object’s Members with this Reference • Overloaded Constructors • Default and No-Argument Constructors • Setter and Getter Methods • Composition & Enumerations • Garbage Collection and Method finalize • static Class Members • static Import • final Instance Variables • Creating & Accessing package

Page 3: Java  core - Detailed Overview

Java

http://thebuddhatree.blogspot.in/

9. Inheritance

• Introduction • Superclass and Subclass • protected Members • Relationship between Superclass and Subclass • Constructors in Subclasses • Class Object

10. Polymorphism

• Introduction • Polymorphism Examples • Polymorphic Behavior • Abstract Class and Method • final Method and Class • Using Interfaces

11. Exception Handling • Introduction • Example: Divide by Zero • When to Use Exception Handling • Java Exception Hierarchy • finally Block • Obtaining Information from an Exception Object • Chained Exceptions • Declaring New Exception Types • Preconditions and Post-conditions • Assertions

12. Strings, Characters and Regular Expressions

• Introduction • Fundamentals of Characters and Strings • Class String • String operation• Class Character • Tokenizing Strings • Regular Expressions, Class Pattern and Class Matcher

13. Files, Streams and Object Serialization

• Introduction • Files and Streams • Class File • Sequential-Access Text Files • Object Serialization • Additional java.io Classes

Page 4: Java  core - Detailed Overview

Java

http://thebuddhatree.blogspot.in/

14. Generic Collections • Introduction • Collections Overview • Type-Wrapper Classes for Primitive Types • Autoboxing and Auto-Unboxing • Interface Collection and Class Collections • Lists • Collections Methods • Sets • Maps • Properties Class • Synchronized Collections • Un-modifiable Collections • Abstract Implementations

14. Generic Classes and Methods • Introduction • Motivation for Generic Methods • Generic Methods: Implementation and Compile-Time Translation • Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type • Overloading Generic Methods • Generic Classes

Page 5: Java  core - Detailed Overview

Introduction to Java

http://thebuddhatree.blogspot.in/

o The Java programming language is a high-level language that can be characterized by all of the following

buzzwords:

• Simple

• Object oriented

• Distributed

• Multithreaded

• Dynamic

• Architecture neutral

• Portable

• High performance

• Robust

• Secure

o In Java, source code or program is written in plain text files ending with the .java extension.

o These files are then compiled into .class files by the java compiler.

o A .class file contains bytecodes — the machine language of the Java Virtual Machine (Java VM).

Page 6: Java  core - Detailed Overview

Introduction to Java

http://thebuddhatree.blogspot.in/

o The java launcher tool then runs the program with an instance of the Java Virtual Machine.

o Java VM is available on many different operating systems, the same .class files are capable of running

on multiple hardware platform.

o Java Platform - A platform is the hardware or software environment in which a program runs like

Microsoft Windows, Linux, Solaris OS, and Mac OS. Java is a software-only platform that runs on top of

other hardware-based platforms. It has two components –

• The Java Virtual Machine

• The Java Application Programming Interface (API)

o Install JDK

o Install Eclipse

o Write hello Java program

Page 7: Java  core - Detailed Overview

Introduction to Java

http://thebuddhatree.blogspot.in/

class HelloWorldApp {

public static void main(String[] args) {

System.out.println("Hello World!"); }

}

it's the entry point for your application and will subsequently invoke all the other methods required by your

program.

Comments

o/* text */ - The compiler ignores everything from /* to */

o/** documentation */ - This indicates a documentation comment.

o// text The compiler ignores everything from // to the end of the line.

Page 8: Java  core - Detailed Overview

Variables

http://thebuddhatree.blogspot.in/

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

Java defines following kind of variables –oInstance Variables (Non-Static Fields) - called as instance variables because their values are unique to each instance of a class (to each object). Declared in class but outside a method, constructor or code block.oClass Variables (Static Fields) - A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

oLocal Variables - a method will often store its temporary state in local variables. local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

oParameters The important thing to remember is that parameters are always classified as "variables" not "fields".

Naming Convention of variable –

oVariable names are case-sensitiveoA variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_“oWhite space is not permitted

Page 9: Java  core - Detailed Overview

Variables – Primitive Data Type

http://thebuddhatree.blogspot.in/

Java defines following kind of variables –

obyte: The byte data type is an 8-bit. It has a minimum value of -128 and a maximum value of 127

(inclusive).

oshort: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768

and a maximum value of 32,767 (inclusive).

oint: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -

2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

olong: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -

9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).

ofloat: The float data type is a single-precision 32-bit.

odouble: The double data type is a double-precision 64-bit.

oboolean: The boolean data type has only two possible values: true and false. Use this data type for simple

flags that track true/false conditions.

ochar: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and

a maximum value of '\uffff' (or 65,535 inclusive).

Page 10: Java  core - Detailed Overview

Array

http://thebuddhatree.blogspot.in/

Java defines following kind of variables –

oAn 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. After creation, its length is fixed.

oEach item in an array is called an element, and each element is accessed by its numerical index.

olength of the array is determined by the number of values provided between braces and separated by

commas.

o An array of 10 elements

Copying one array value to another array - Java provides arraycopy() method to copy data from one array

into another. Syntax –

arraycopy(Object src_array, int srcPos, Object dest_arrat, int destPos, int length) Searching an array for a specific value to get the index at which it is placed (the binarySearch() method).Comparing two arrays to determine if they are equal or not (the equals() method).Filling an array to place a specific value at each index (the fill() method).Sorting an array into ascending order.

Page 11: Java  core - Detailed Overview

Array

http://thebuddhatree.blogspot.in/

Array Manipulation

oSearching an array for a specific value to get the index at which it is placed (binarySearch() method)

oComparing two arrays to determine if they are equal or not (the equals() method)

oFilling an array to place a specific value at each index (the fill() method)

oSorting an array into ascending order

OperatorSimple Assignment Operator :

o = : , int I =10; //This assign the value on the right to variable on the left

Arithmetic : o + : additive operator (also used for string concatenation)o - : subtraction operatoro * : multiplication operatoro / : division operatoro % : remainder operator

Conditional Operatorso && : Conditional ANDo || : Conditional OR

Page 12: Java  core - Detailed Overview

Operator

http://thebuddhatree.blogspot.in/

Equality / Relationalo = = : equal too ! = : not equal too > : greater thano > = : greater than on equal too < : less thano < = : less than or equal to

Unary Operatoro + : Unary plus operator; indicates positive value (numbers are positive without this, however)o - : Unary minus operator; negates an expressiono ++ : Increment operator; increments a value by 1o -- : Decrement operator; decrements a value by 1o ! : Logical complement operator; inverts the value of a boolean

Page 13: Java  core - Detailed Overview

Control Flow Statement

http://thebuddhatree.blogspot.in/

The statements inside source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.

oIf – then statement : It tells the program to execute a certain section of code only if a particular test evaluates to true. Example –

if (condition) {

}oIf – then - else statement : provides a secondary path of execution when an "if" clause evaluates to false. Example –

if (condition) {

} else if (condition) {

}else {

}

Page 14: Java  core - Detailed Overview

Control Flow Statement

http://thebuddhatree.blogspot.in/

The switch statement - the switch statement can have a number of possible execution paths. Example - int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break;

The while and do-while Statements - The while statement continually executes a block of statements while

a particular condition is true. Its syntax can be expressed as:

while (expression) {

statement(s)

} The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once

do { System.out.println("Count is: " + count); count++; } while (count < 11);

Page 15: Java  core - Detailed Overview

Control Flow Statement

http://thebuddhatree.blogspot.in/

The for statement - It provides a compact way to iterate over a range of values. often called as “for loop”.

Syntax –

for (initialization; termination; increment) {

statement(s)

}

oThe initialization expression initializes the loop, it's executed once, as the loop begins.

oWhen the termination expression evaluates to false, the loop terminates.

oThe increment expression is invoked after each iteration through the loop, it may increment or decrement

a value.

Page 16: Java  core - Detailed Overview

Object and Class

http://thebuddhatree.blogspot.in/

o Real-world objects share two characteristics: They all have state and behavior. E.g. Bicycles also have

state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal

cadence, applying brakes).

o An object stores its state in fields (variables in some programming languages) and exposes its behavior

through methods (functions in some programming languages). Methods operate on an object's internal

state and serve as the primary mechanism for object-to-object communication. Hiding internal state

and requiring all interaction to be performed through an object's methods is known as data

encapsulation

o Class - A class is the blueprint from which individual objects are created.

o In object-oriented terms, we say that your bicycle is an instance of the class of objects known as

bicycles.

Page 17: Java  core - Detailed Overview

Class

http://thebuddhatree.blogspot.in/

o class declarations includes following components -

• Modifiers such as public, private

• The class name, with the initial letter capitalized by convention

• The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can

only extend (subclass) one parent

• A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword

implements. A class can implement more than one interface.

• The class body, surrounded by braces, {}.

o Declaring member variable - Field declarations are composed of three components

• Zero or more modifiers, such as public or private

• The field's type

• The field's name

o Defining a method - A method declaration should have return type, name, a pair of parentheses, (), and

a body between braces, {}.

Page 18: Java  core - Detailed Overview

Class

http://thebuddhatree.blogspot.in/

o Overloading methods - methods within a class can have the same name if they have different

parameter lists

o Constructor - A class contains constructors that are invoked to create objects from the class blueprint.

Constructor declarations look like method declarations—except that they use the name of the class and

have no return type. Passing information to a Method or a Constructor –

o When you declare a parameter to a method or a constructor, you provide a name for that parameter.

This name is used within the method body to refer to the passed-in argument.

o The name of a parameter must be unique in its scope. It cannot be the same as the name of another

parameter for the same method or constructor, and it cannot be the name of a local variable within the

method or constructor.

o A parameter can have the same name as one of the class's fields

Passing Primitive Data Type Arguments

o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the

values of the parameters exist only within the scope of the method. When the method returns, the

parameters are gone and any changes to them are lost.

Page 19: Java  core - Detailed Overview

Class

http://thebuddhatree.blogspot.in/

o When you declare a parameter to a method or a constructor, you provide a name for that parameter.

This name is used within the method body to refer to the passed-in argument.

o The name of a parameter must be unique in its scope. It cannot be the same as the name of another

parameter for the same method or constructor, and it cannot be the name of a local variable within the

method or constructor.

o A parameter can have the same name as one of the class's fields

Passing Primitive Data Type Arguments

o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the

values of the parameters exist only within the scope of the method. When the method returns, the

parameters are gone and any changes to them are lost.

Passing Reference Data Type Arguments

o Reference data type parameters, such as objects or array, are also passed into methods by value. This

means that when the method returns, the passed-in reference still references the same object as

before. However, the values of the object's fields can be changed in the method.

Page 20: Java  core - Detailed Overview

Object

http://thebuddhatree.blogspot.in/

A Java program creates many objects, which interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Creating objects – Point originOne = new Point(23, 94);

Declaring a variable to Refer an object – This notifies the compiler that you will use name to refer to data whose type is type

type name;

Instantiating a Class - The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Point originOne = new Point(23, 94);

Initializing an object – constructor is called which initializes the member variable of class Point originOne = new Point(23, 94);

Page 21: Java  core - Detailed Overview

Object

http://thebuddhatree.blogspot.in/

o Using Objects – Once an object is created, You may use the value of one of its fields, change one of its

fields, or call one of its methods to perform an action.

o Object fields are accessed by their name - objectReference.fieldName

o Calling an Object Method - Object method is invoked using objectreference.methodname() or

objectreference.methodname(argumentlist) and provide argument to the method into parenthesis.

Return a Value from Method - A method returns to the code that invoked it when it

• completes all the statements in the method,

• reaches a return statement, or

• throws an exception

• A method's return type is declared in its method declaration. Within the body of the method, the return

statement is used to return the value.

• A method declared void doesn't return a value. It does not need to contain a return statement

Page 22: Java  core - Detailed Overview

Inheritance

http://thebuddhatree.blogspot.in/

o It allows classes to inherit commonly used state and behavior from other classes.

o each class is allowed to have one direct superclass, and each superclass has the potential for an

unlimited number of subclasses:

o It defines an is-a relationship between a superclass and its subclasses. This means that an object of a

subclass can be used wherever an object of the superclass can be used. Class Inheritance in java

mechanism is used to build new classes from existing classes. The inheritance relationship is transitive:

if class x extends class y, then a class z, which extends class x, will also inherit from class y.

o The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends

keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

}

Page 23: Java  core - Detailed Overview

Inheritance

http://thebuddhatree.blogspot.in/

A hierarchy of bicycle classes

o Private members of the superclass are not inherited by the subclass and can only be indirectly

accessed.

o Members that have default accessibility in the superclass are also not inherited by subclasses in

other packages, as these members are only accessible by their simple names in subclasses within the

same package as the superclass.

o Since constructors and initializer blocks are not members of a class, they are not inherited by a

subclass.

o A subclass can extend only one superclass

Page 24: Java  core - Detailed Overview

Inheritance – this & super

http://thebuddhatree.blogspot.in/

o The two keywords, this and super to help you explicitly name the field or method that you want. Using

this and super you have full control on whether to call a method or field present in the same class or to

call from the immediate superclass. This keyword is used as a reference to the current object which is

an instance of the current class. The keyword super also references the current object, but as an

instance of the current class’s super class.

o Note that the this reference cannot be used in a static context, as static code is not executed in the

context of any object.

Page 25: Java  core - Detailed Overview

Interface & Abstract Class

http://thebuddhatree.blogspot.in/

o Abstract classes are used to declare common characteristics of subclasses.

o An abstract class cannot be instantiated.

o It can only be used as a superclass for other classes that extend the abstract class.

o Abstract classes are declared with the abstract keyword.

o It is used to provide a template or design for concrete subclasses down the inheritance tree.

o An abstract class can include methods that contain no implementation. These are called abstract

methods. The abstract method declaration must then end with a semicolon rather than a block.

o Syntax to create abstract class -

abstract class Vehicle {

int numofGears;

String color;

abstract boolean hasDiskBrake();

abstract int getNoofGears();

}

oA big Disadvantage of using abstract classes is not able to use multiple inheritance.

Page 26: Java  core - Detailed Overview

Interface & Abstract Class

http://thebuddhatree.blogspot.in/

o Interface is used to define a generic template and then one or more abstract classes to define partial

implementations of the interface.

o Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields

(which are implicitly public static final). Interface definition begins with a keyword interface.

o An interface can not be instantiated.

o Java does not support multiple inheritance, but it allows you to extend one class and implement many

interfaces.

o If a class that implements an interface does not define all the methods of the interface, then it must be

declared abstract and the method definitions must be provided by the subclass that extends the

abstract class.

o Syntax to create interface -

interface Shape {

public double area();

public double volume();

}

Page 27: Java  core - Detailed Overview

Exception Handling

http://thebuddhatree.blogspot.in/

Exceptions in java is a condition that is caused by a run-time error in the program. Java creates an exception

object and throws. Most common run-time errors are –

o Dividing an integer by zero

o Accessing an element that is out of the bounds of an array

o Attempting to use a negative size of an array

o Converting invalid string to a number

o File not found

Common Java Exceptions

o ArithmeticException – Caused by main errors such as division by zero

o ArrayIndexOutOfBoundException – Caused by bad array indexes

o FileNotFoundException – Caused by an attempt to access a nonexistent file

o IOException - Caused by general I/O failures

o NullPointerException – Caused by referencing a null object

o StringIndexOutOfBoundsException – Caused when a program attempts to access a nonexistent

character position in a string

Page 28: Java  core - Detailed Overview

Exception Class Hierarchy

http://thebuddhatree.blogspot.in/

Page 29: Java  core - Detailed Overview

Exception Handling

http://thebuddhatree.blogspot.in/

checked exception - Exceptional conditions that a well-written application should anticipate and recover

from. Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked

exceptions, except for those indicated by Error.

Error - These are exceptional conditions that are external to the application, and that the application

usually cannot anticipate or recover from. For example, a hardware or system malfunction.

Runtime Exception - These are exceptional conditions that are internal to the application, and that the

application usually cannot anticipate or recover from. These usually indicate programming bugs, such as

logic errors or improper use of an API.

Page 30: Java  core - Detailed Overview

Exception Handling

http://thebuddhatree.blogspot.in/

Exception Handling mechanism –

Page 31: Java  core - Detailed Overview

Collection Framework - Introduction

http://thebuddhatree.blogspot.in/

o A collection represents a group of objects, known as its elements. This framework is provided in the

java.util package.

o Objects can be stored, retrieved, and manipulated as elements of collections.

o Collection is a Java Interface. It can be used in various scenarios like Storing phone numbers, Employee

names database etc. They are basically used to group multiple elements into a single unit.

o Some collections allow duplicate elements while others do not.

o Some collections are ordered and others are not.

o A Collections Framework mainly contains the following 3 parts

o A Collections Framework is defined by a set of interfaces, concrete class implementations for most of

the interfaces and a set of standard utility methods and algorithms. In addition, the framework also

provides several abstract implementations, which are designed to make it easier for you to create new

and different implementations for handling collections of data.

Page 32: Java  core - Detailed Overview

Collection Framework – Interface Details

http://thebuddhatree.blogspot.in/

Core Collection Interfaces

The core interfaces that define common functionality and allow collections to be manipulated independent

of their implementation. The 6 core Interfaces used in the Collection framework are:

1. Collection

2. Set

3. List

4. SortedSet

5. Map

6. SortedMap

7. Iterator (Not a part of the Collections Framework)

Note: Collection and Map are the two top-level interfaces.

Page 33: Java  core - Detailed Overview

Collection Interface

http://thebuddhatree.blogspot.in/

Page 34: Java  core - Detailed Overview

Collection Interface

http://thebuddhatree.blogspot.in/

Page 35: Java  core - Detailed Overview

Collection Detail

http://thebuddhatree.blogspot.in/

ArrayLilst

oArrayList supports dynamic arrays that can grow as needed.

oArray lists are created with an initial size. When this size is exceeded, the collection is automatically

enlarged. When objects are removed, the array may be shrunk.

oIt stores an “ordered” group of elements where duplicates are allowed.

oAccessing elements are faster with ArrayList, because it is index based.

oList arraylistA = new ArrayList();

LinkedList

oIt provides a doubly linked-list data structure.

oA LinkedList is used to store an “ordered” group of elements where duplicates are allowed.

oList linkedListA = new LinkedList();

oIt is slow access.

Vector

oimplements a grow able array of objects. Like an array, it contains components that can be accessed using

an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and

removing items after the Vector has been created.

Page 36: Java  core - Detailed Overview

Collection Detail

http://thebuddhatree.blogspot.in/

HashSet

oThe HashSet class implements the Set interface

oit does not guarantee that the order will remain constant over time.

HashMap

oHashMap is a implementation of the Map interface.

oIt stores data in key-value mapping

oThis class makes no guarantees as to the order of the map

oThis implementation provides constant-time performance for the basic operations (get and put)

Page 37: Java  core - Detailed Overview

Access Specifier

http://thebuddhatree.blogspot.in/

o The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class

can control what information or data can be accessible by other classes.

o To take advantage of encapsulation, access should be minimized whenever possible.

o Public - Fields, methods and constructors declared public are visible to any class in the Java program,

whether these classes are in the same package or in another package.

o Private - Fields, methods or constructors declared private are strictly controlled, which means they

cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all

fields private and provide public getter methods for them.

o protected - Fields, methods and constructors declared protected in a superclass can be accessed only by

subclasses in other packages. Classes in the same package can also access protected fields, methods and

constructors as well, even if they are not a subclass of the protected member’s class.

o default - Java provides a default specifier which is used when no access modifier is present. Any class,

field, method or constructor that has no declared access modifier is accessible only by classes in the

same package. The default modifier is not used for fields and methods within an interface.

Page 38: Java  core - Detailed Overview

Multithreading

http://thebuddhatree.blogspot.in/

o Java provides built-in support for multithreaded programming. A multithreaded program contains two

or more parts that can run concurrently. Each part of such a program is called a thread, and each thread

defines a separate path of execution.

o A multithreading is a specialized form of multitasking.

o A process consists of the memory space allocated by the operating system that can contain one or more

threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until

all of the non-daemon threads are done executing.

o Thread can be created in two ways –

1. Create Thread by Implementing Runnable interface – Define a class that implements Runnable

interface. Define run() method with the code to be executed by the thread.

2. Create Thread by Extending Thread – Define a class that extends Thread class and override run()

method.

Page 39: Java  core - Detailed Overview

Multithreading ..

http://thebuddhatree.blogspot.in/

Life Cycle of a Thread -

1. Newborn State: When thread object is created, the thread is born and is said to be in newborn

state. At this state, we can do things –

Schedule it for running using start() method

Kill it using stop() method

2. Runnable State : The thread is ready for execution and is waiting for the availability of the

processor. Yield() method is used to allow a thread to relinquish control to another thread of

equal priority before its turn comes.

3. Running State: it means processor has given its time to the thread for execution. The thread runs

until it relinquishes control on its own or it is preempted by a higher priority thread.

A thread can be suspended using suspended() method and can be revived using resumed

method. This is useful when we want to stop execution of a thread for some time but do not

want to kill it.

A thread is made to go out of queue using sleep(millisecond) method, it will be back in

runnable state as soon as time period is elapsed.

Page 40: Java  core - Detailed Overview

Multithreading …

http://thebuddhatree.blogspot.in/

4. Blocked State: A blocked thread is considered not runnable but not dead and therefore fully

qualified to run again. This happens when a thread is suspended, sleeping or waiting.

5. Dead State : A running thread ends its life when it has completed executing its run() method. It is

natural death. We can kill a thread by sending stop() method.

Thread Priorities

oEvery Java thread has a priority that helps the operating system determine the order in which threads are

scheduled.

oJava priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant

of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

oThreads with higher priority are more important to a program and should be allocated processor time

before lower-priority threads. However, thread priorities cannot guarantee the order in which threads

execute and very much platform dependentant.

Page 41: Java  core - Detailed Overview

Thank You!!

Blog - http://thebuddhatree.blogspot.in/Like Us on YouTube Like Us on Google +Like Us on Google QA GroupLike Us on Facebook