notes on java (1)

107
 The Java Programming Language Java is defined as General –Purpose, Object Oriented and Multithreaded Programming Language Features of J! The Java programming language is a high-level language that can be characterized by all of the following buzzwords: Simple Dynamic Robust Obect oriented !rchitecture neutral Secure Distributed "ortable #ultithreaded $igh performance "imple Java synta% is similar to &'&(( synta%) Ja va omits many rarely use d* poorly understo od* confusin g feature of &(() +n ava there is - #o Pointer and Pointer rithmetic - #o "tructure and no union - #o operator overloading - #o virtual base class - #o goto statement  ,o need to remove unreferenced ob ects because ava has automatic garbage collection) Object oriented Java is made up of obectsi)e)* there is no coding written outside class definition including main. method) Obect oriented design is a techni/ue for programming that focuses on the data0obect. and on the interface to that data) The obect oriented facilities of ava are essentially those of &(( such as encapsulation, pol$morphism, inheritance . The maor difference between &(( and ava lies in multiple inheritance* which ava replaced with simpler concept of interface %istributed&#et'or( "avv$ Java was designed with networ1ing in mind and comes with many classes to develop sophisticated +nternet communications) Java has e%tensive library of routines for coping with T&"'+" protocol li1e $TT" and 2T") Java applications can open and access obects across the ,et via 3R4s with the same ease as when accessing a local file system Multithreaded Java was designed to meet the real world re/uirement of creating interactive* networ1ed program) To accomplis h thi s* ava suppor t multit hre ade d pro gra mming* whi ch allows you to wri te a  program that do many things simultaneously #ultithreading is one of the reasons why ava is such an appealing language for server side development %$namic 5ith the help of OO"s ava provides inheritance and with the help of inheritance we reuse code that is predefined) Java is more dynamic language that &((* &) libraries can freely add new method and instance variable without any effect on their client rchitecture neutral The ava compiler generate an architecture-neutral obect file format* so that the compiled code is e%ecutable on many processor* given the presence of J 6#

Transcript of notes on java (1)

The Java Programming LanguageJava is defined as General Purpose, Object Oriented and Multithreaded Programming LanguageFeatures of JAVAThe Java programming language is a high-level language that can be characterized by all of the following buzzwords:

Simple Dynamic Robust

Object oriented Architecture neutral Secure

Distributed Portable

Multithreaded High performance

Simple

Java syntax is similar to C/C++ syntax.

Java omits many rarely used, poorly understood, confusing feature of C++. In java there is

No Pointer and Pointer Arithmetic

No Structure and no union No operator overloading

No virtual base class

No goto statement

No need to remove unreferenced objects because java has automatic garbage collection. Object oriented

Java is made up of objects(i.e., there is no coding written outside class definition including main() method.

Object oriented design is a technique for programming that focuses on the data(=object) and on the interface to that data. The object oriented facilities of java are essentially those of C++ (such as encapsulation, polymorphism, inheritance )

The major difference between C++ and java lies in multiple inheritance, which java replaced with simpler concept of interface

Distributed/Network Savvy Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications. Java has extensive library of routines for coping with TCP/IP protocol like HTTP and FTP. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file system

Multithreaded

Java was designed to meet the real world requirement of creating interactive, networked program. To accomplish this, java support multithreaded programming, which allows you to write a program that do many things simultaneously

Multithreading is one of the reasons why java is such an appealing language for server side development

Dynamic

With the help of OOPs java provides inheritance and with the help of inheritance we reuse code that is predefined.

Java is more dynamic language that C++, C. libraries can freely add new method and instance variable without any effect on their client

Architecture neutral

The java compiler generate an architecture-neutral object file format, so that the compiled code is executable on many processor, given the presence of JVM

Java compiler generates byte code instruction, which JVM can understand, and JVM easily translate byte code into native machine code. Portable

Unlike C, C++ in Java, there are no implementation dependent aspects of specification. For example, an in java is always a 32 bit integer, but in C++ / C, int can mean a 16-bit integer, or any other size, in different compiler

Because java having fixed size for number type eliminates a major porting headache. String are stored in standard Unicode format

Interpreted Compiler Combo Java enable the creation of cross platform programs by compiling into an intermediate representation called java byte code. This code can executed on any machine in which JVM has been ported High performance

Interpretation of bytecodes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques Robust

Compiler detects many problems, that are identified during runtime in other languages

Java is said to be strong , since it has Exception handling built-in strong type checking (that is, all data must be declared an explicit type) local variables must be initialized Secure

Because java is intended to be used in networked / distributed environment, we need to concern more about security of data. Java enable construction of virus free, tamper- free system

Java was designed to make certain kinds of attacks impossible, among them:

overrunning the runtime stack a common attack of worm and viruses

corrupting memory outside its own process space

reading or writing file without permission

JAVA PROGRAM STRUCTURE A Java program may contain many classes of which only one class defines a main method. Classes contain data members and methods that operate on the data members of the class Methods contain data type declarations and executable statements. The structure of the java isdocumentation section suggested

package statement optional

import statements optional

interface statements optional

Class definitions optional

main method class

{

main method definition

} Compulsory

1) Documentation section or Comment section

this section contains a set of comment lines giving the name of the program, the author and other details, which is used to refer at the later stage.

Comment lines are of 3 types. They are

1. Single line comment

this type of comment is identified by //

only one line can be commented.

e.g.,

// this is first program written in java program

2. Multi line comment

This is identified by /* .*/

Any no. of statements can be written.

e.g.,

/* this is a simple java program

file name is eg.java*/

3. Documentation comment

This is identified by /** .*/

Documentation comments allow the programmer to give information about the program in the program itself.

This type of comment is used to produce an HTML file that contains the documentation of the program.

This HTML file is obtain by running the program using javadoc utility program.

This javadoc program extracts information from the java program and then it creates HTML file.

In a documentation comment, we can use some of the tags.

e.g.,

/** This class demonstrates documentation comments

* @author IImca

* @param num

* @return n

*/

in the above e.g., @author , @param, @return are some of the tags used in documentation comments.

@author javadoc extracts the author name from this tag.

@param the parameters used in the program is known from this tag.

@return the variable to be returned is known from this tag.

2) Package Statement

Packages are group of classes or interfaces.

E.g.,

keyword user-defined package name

package student;

The package statement is optional.

3) Import statement

Import statement in java is equal to # include statement in C++.

E.g.,

import java.lang.Math;

This statement instructs the interpreter to load Math class which is floder lang inturn which in java folder

4) Interface statement

An interface is like a class, which includes a group of method declarations. This is also an optional section.5) Class definitions

Classes are the primary and essential elements of a Java program. A Java program may contain multiple class definitions.6) Main Method class

A main method is written inside the class. The main method creates objects of various classes and establishes communication between them.e.g.,

/* the program which has main method class part

class example

{

public static void main(String args[])

// main is a static method which can be accessed directly.

{

int a=10,b=20,c;

c=a+b;

System.out.println(The addition of two nos. =+c);

}

}

FEATURES OF OBJECT ORIENTED PROGRAMMING

There are four main features

1. Encapsulation

2. Inheritance

3. Polymorphism

4. Data hiding/data security

ENCAPSULATION

Wrapping of variables and methods into a single unit is known as encapsulation. It is the mechanism that binds together data and code that manipulates data, and keep both safe from outside interference and misuse

within the classes, the member of class (such as methods and fileds)may be qualified as private, public, protected or package proctected private member of the class is known only by with in the same object, outside it is not accessible When any member of the class declared public, it is visible to everywhere, regardless object in which it is defined POLYMORPHISM

The ability of an object to take more than one form is known as polymorphism

It provide ability to define more than one functions with same name, inside class as long as number of arguments and types of arguments are different Compiler will identify the calling method, in term of number of arguments, types of argument and order of arguments.

Polymorphism not only applicable for method but also applicable to constructors Method overriding is another concept supported by polymorphismINHERITANCE

It is the process by which one object can acquires the properties, methods of another object.

It provides the ability to reuse the definition existing class from new class. This avoid rewriting the same code again, those already exist It reduce programmer burden, if any modification done on parent class will automatically reflect on all Child classes.

It support concept of hierarchical classification of classes Parent, child, grandparent classification possible. OBJECT Object is actually an instance of class. Object could represent a person, place, bank account or any other item that is handled by the program. Every object consist attributes and functions CLASS

A Class is a template for an object. It helps to encapsulate entire set of data and code that operate on data into a single user defined data type General form of a class is class classname { // instance field declarationa type instance-variable-1;

type instance-variable-2;

type instance-variable-N;// method definition type methodname-1(parameter-list) { //body of method }

type methodname-2(parameter-list) {//body of method }

type methodname-N(parameter-list) {//body of method }

//constructor definition

classname(parameter-list) { //body of constructor }

.

}

The class body (the area between the braces) contains following item :

constructors for initializing new objects

field declarations that provide the state of the class and its objects called as instance field Syntax

datatype variablename[=value]; methods the procedure /code that operates on the data .

Syntax

accessspecifier returntype methodname(parameter list){}.

Exampleclass Box {

// instance field

double width, height, depth;

// constructor of 3 parameters

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

// method to compute and return volume

double volume() {

return width * height * depth;

}

}

OBJECTSDefn: Called as instance of a class

or

An object in Java is a block of memory that contains space to store all the instance variables.

Declaring objects or creating objects

Creating an object is referred as instantiating an object.

Once class is defined, you can create new data-type of that class. Obtaining object of the class is a two-step process:

1. Declare reference variable of class type.(i.e., the data type of a variable is a class name). Syntax

classname reference-variable; // only declarationNote: This declaration does not define object, instead it is indicating that b is reference variable of object Box, presently it is point to null object

2. Acquire an actual, physical copy of the object and assign its address to the reference variable This process is done by new operator new operator dymamically allocate memory for an object and return reference(i.e., address in memory allocate to it) to it(i.e. to the object)

This could be done using following syntax:

reference-variable = new classname([argument-list]);

Syntax for creating object

classname objectname; // declare

objectname = new classname(); // memory allocated to the object

or

classname objectname = new classname(); // two process in single step

e.g., for the above class Box , the object is created as

Box b; //declare b =new Box ();//memory allocated to the object or

Box b = new Box (); // two process in single step attempt to access the variable b after declaration statement , gets compile-time error.

Pictorial representation for the above object creation(the two-step process)

ActionStatementEffect or result

DeclareBox b;

b ( null (address is not allocated for object b

Object referenceb=new Box(); b(address is allocated bwidth=10,height=12.5,depth=9.0

Box(float,float,float){}

double volume(){}

METHODS Procedure or code that operates on instance fields

Methods of the class has all rights to access, set, modify instance field of class

Methods could have any access specifier such as public, private, protected, and package-protected It may have return type, and can have zero on more arguments. It general signature is

return-type methodname-1(parameter-list)

{ //body of method }

return-type and parameter-list can be of any valid java primitive data-type or type of user-defined class. If the method does not return a value, its return-type must be void Only non-void methods require to have return-statement within its body.

Syntax of return statement

return(value);

Different types of methods are1. Mutator Method : Methods that change the instance fields

2. Accessor Method: Methods that only access instance fields without modifying it

E.g., for mutator and accessor method

class student

{

String name;

void setname(String s) // Mutator method

{ name=s; }

String getname() // accessor method

{ return name; }

public static void main(String args[])

{

student stud=new student();

stud.setname(Sarveswaran);

System.out.println(Name of the Student is + stud.getname());

}

}METHOD OVERLOADING Defn

Creating methods that has

same name

different parameter lists(i.e., arguments)

different definitions(i.e., each method has different meaning)

is called method overloading.

Or

Defining two or more methods within the same class that share the same name, with different parameter declarations(either number of parameters or types of parameters are different) is called as overloaded methods/method overloading.

Method Overloading is one way where Java implements the concept Polymorphism(i.e., static binding/compile time binding).

Automatic type conversion will happen in invocation of overloaded methods, if exact method signature not found.

How overloaded method invocation is determined?

i) First, Java runtime system matches name of the method with the name of the methods exists in the object.

ii) If more than one method found with same name, method determination is done using number of arguments

iii) If more than one method found with same number of argument, method determination is done using type of the arguments

E.g.,

class OverloadDemo {

void test() {

System.out.println("No parameters");

}

void test(int a) {

System.out.println("a: " + a);

}

double test(double a) {

System.out.println("double a: " + a);

}

void test(double a, double b) {

System.out.println("a and b: " + a + " " + b);

}

}

class Overload {

public static void main(String args[]) {

OverloadDemo ob = new OverloadDemo();

double result;

ob.test();

ob.test(10);

ob.test(10, 20); // here intergers are automatically converted to double

ob.test(123.25);

}

}METHOD PARAMETERTwo way of argument passing to methods

Arguments are passed to methods in two ways call-by-value method copies the value of an actual argument into formal parameter

Therefore, changes made on formal-parameters within the method, does not affect the actual-parameters.

All java primitive types/ simple types are passed to method as passed-by-value

call-by-reference

reference to an argument is passed to the method, instead of value of an argument.

All java classs objects are passed to method as reference

Note: Java always uses call by value The follwing program demonstrates both featureclass MyObject {

int a;

MyObject(int i){

a=i;

}

}

class Test { // call by valuestatic void increment(int i){

i*=2;

System.out.println("increment:i="+i);

}// reference passed as call by valuestatic void increment(MyObject o){

o.a*=2;

System.out.println("increment:o.a="+o.a);

}

}

class ArgumentDemo {

public static void main(String args[]) {

int x = 15;

System.out.println("before call x="+x);

Test.increment(x);

System.out.println("after call x="+x);

MyObject mo = new MyObject(15);

System.out.println("\nbefore call mo.a="+mo.a);

Test.increment(mo);

System.out.println("after call mo.a="+mo.a);

}

}ACCESS SPECIFIERS Encapsulation provides access control (i.e., what part of the program can access the members of the class) Visibility control means restricting the access of the instance variables and methods of the class. Different types of access specifiers are

1) public

The instance variables and method declare as public can be accessed in

i) same class

ii) subclass(i.e., derived class) of same package

iii) other classes in same package

iv) subclass in other packages

v) Non-subclasses in other packages

to make instance variables and method as public , we have to specify it in the program.

e.g., public int a=10;

public void area(){ }2) friendly/package protected/package private/defualt When access specifier is not specified in the program, the accessibility is treated as friendly(i.e., default access specifier)

The accessibility of friendly variables and methods are

i) within same class

ii) subclass of same package

iii) other classes in same package e.g.,

int a;

void area(){}3) protected

The accessibility of protected fields are

i) within same class

ii) subclass of same package

iii) other classes in same package

iv) subclass in other packages

- e.g., protected int a=10;

protected void area(){ }

4) private

the methods and variables declared as private can be accessed only in the same class.

A method declared as private work as method declared as final.

e.g., private int a=10;

private void area(){ }

STATIC MEMEBERS creating a member (variable & method) that can be called without instance of the class, but accessed using class name itself.

To create such a member, precede its declaration with the keyword static When a member of the class is declared as static, it can be accessed before any objects of its class are created. You can declare both methods and variables as static The most common example of static member is main() method, main( ) declared as static because it must be called before any object exist

1. Static Field

Static variables are global variables for the objects created under same class

when object of the class are declared, no copy of static variable is made, instead all instance share the same static variables

Syntax of static variable

static datatype variablename [=value];

E.g.,

static int eid=101;

To access Static variables from other class, the general form is

classname.variablename;

e.g.:

circle-area = Math.PI * r * r;

2. Static method

Do not operate on objects

Methods declared as static has the following restrictions1) They can call only other static methods2) They must access only static data3) They cannot use this or super keyword in any way

Math is the class, which has all its methods and variables as static.

To call static method outside of it class, use the following general form

Classname.methodname([argument-list]);

e.g.:

root = Math.sqrt(10);

3. Static constants One common use of static is to create a constant value thats attached to a class. add the keyword final in there, to make name a constant (in other words, to prevent it ever being changed).

make name uppercase by convention, to indicate that its a constant

Syntax

static final datatype varname = value;

E.g.

static final double MAX = 5;

4. Static block/Static initialization block Used to dynamically initialize static variable during runtime using some computation

Static block gets executed only once, when the class is first loaded

Static block in java is executed before main method.

That is, Java execution starts from static blocks and not from main() method.

Static block can be placed anywhere within the class, but outside of any method, constructor in the class.

Can have any number of static blocks in the class

The general syntax of static block is:

static

{ //your static variable initialization code here }

Example Program that describe the features of Static Membersclass MyStatic {

static int a = 3;

static int b;

int c;

void setC(int tmp) {c=tmp; }

static void showAB( ) {

System.out.println("a = " + a);

System.out.println("b = " + b);

display( );

// setC(10); error because setC( ) is non static method

// System.out.println("c = " + c); error because c is non static variable

}

static void display() {

System.out.println("message from static display\n");

}

static {

System.out.println("Static block initialized.");

b = a * 4;

}

}

class StaticDemo

{

public static void main(String args[])

{

MyStatic.showAB( );

MyStatic.a=10;

//Mystatic.c=20; //error

MyStatic ms=new MyStatic( );

ms.c=20;

System.out.println("ms.c="+ms.c+",ms.a"+ms.a);

ms.showAB();

}

}CONSTRUCTORSDefn :

A constructor initializes instance variables while creating an object.

or

Constructor is automatically called immediately after the object is created, before the new operator completes. Constructor is always called with the new operator

Constructor cannot be called using object name or class name

Constructors are a special method, which has the same name as class name and accept zero or more arguments as parameters

They are used to initialize the data member of object, when it is created.

It must have access specifier as always public or package protected(i.e., default) Constructor has no return value because , the return-type of the classs constructor is always class type itself If your class does not contain constructor definition, java system will automatically define default constructor for your class Types of constructors

There are two types of constructors:

1. default constructor (no-arg constructor)

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

class_name(){}

2. Parameterized Constructor

A constructor that has parameters is known as parameterized constructor.

CONSTRUCTOR OVERLOADING Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by matching the parameters in the list and their type. A compiler time error occurs if the compiler cannot match the parameter or if more than one match is possible. This is called as overloading resolution.

Example demonstrates constructor and constructor overloading

/* Here, Box defines three constructors to initialize the dimensions of a box in various ways.*/

class Box {

double width, height, depth;

// constructor used when all dimensions specified

Box(double w, double h, double d) {

width = w;

height = h;

depth = d;

}

// constructor used when no dimensions specified

Box() {

width = height = depth = -1;// use -1 to indicate an uninitialized box

}

// constructor used when cube is created

Box(double len) {

width = height = depth = len;

}

double volume() {

return width * height * depth;

}

}

class OverloadCons {

public static void main(String args[]) {

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box();

Box mycube = new Box(7);

double vol;

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);

vol = mycube.volume();

System.out.println("Volume of mycube is " + vol);

}

}

FIELD INITIALIZATIONInstance Fields of a class can be initialized in different ways . they are

1. Initializing using constructora) Default field initialization(when default constructor in not specified)

If a instance field is not set explicitly in a constructor , and no default constructor is written, default constructor is create automatically and all the instance fields are initialized to default values.

Default values => int to 0, boolean to false, object reference to nullb) Using default constructor(creating default constructor explicitly)

Default constructor is created and all the instance fields are set to the default values or the values provided by the user2. Initializing during declaration/Explicit field initialization

a) Setting initial value during declaration

During declaration itself the initial value for the instance filed is assigned

E,g.,

class student

{

int sno=101;

String sname=siva;

}

b) Field initialization with a method call

Assigning initial value to the instance field by calling a method e.g.,

class Employee

{

int assigneno()

{

int eno=10;

return eno;

}

// empno =10 is initialized by calling assigneno() method

int empno=assingeno(); }

3. Using Instance initialization block Class declaration can contain arbitrary blocks of code which is executed whenever an object of that class is created. This arbitrary block is called as initialization block This block can contain operations(i.e., executable statements/initialization of instance field) that are common to all objects

is invoked after the parent class constructor is invoked.

E.g.,

class bike

{

int speed;

bike()

{

System.out.println(Speed is + speed);

}

// instance initialization block

{

System.out.println(inside initialization block);

speed =100;

}

public static void main(String args[])

{

bike b=new bike(); // when b is created instance initialization block is executed

}

}

Output

Inside initialization block

Speed is 100

Finalize() method

is in System class is a method that is called just before an objects final destruction by the garbage collector

Syntax

protected void finalize() throws Throwable

is invoked each time before the object is garbage collected to free the resource used by the objects any object not created with new operator use finalize() for cleanup process

Note: neither finalization nor garbage collection is guaranteed.

PACKAGESDefinition

A package can be defined as a grouping of related type(classes , interfaces) providing access protection and name space managementPackages are container for classes; they are used for the following reason:

To avoid name collision of classes developed by different programmer, different software company

To import classes: Classes stored in a package are explicitly imported into new class definition from its location, without making copy of that in your folder

Packages are also used to control accessibility of the classes, members of the classesPackages are classified into two types

1. Predefined packages

2. User-defined packages

1. Predefined packages

Predefined packages are those which are developed by SUN micro systems and supplied as a part of JDK (Java Development Kit) to simplify the task of java programmer. some of the predefined packages arejava.lang , java.util, ,java.awt, java.io

2. User defined packages /defining packages To create a package simply include a package command at the top of the every source file

A package statement must be the first statement in the java source file.

Any classes declared within that file will belong to specified package.

A source file must have only one package statement If you omit package statement in your java source code, the classes for your souce code are put into the default package, which has no name

The general form of the package statement is:

package ;here pkg is the name of the package.

For example:

package mypackage;

The package name and folder name in which your java file stored must have the same name Hierarchy of packages can also be created

This is done by creating a hierarchy of folder, and separating each package name using period(.).

The general form of multileveled package is shown here

package pkg1[.pkg2[.pkg3]]; For example:

package pack1.subpack1;Note: package in java is converted into directory (i.e., folder) during executione.g., java.util.* is converted as java\util\.* Simple example of package

packagemypack;

classSimple{

publicstaticvoidmain(Stringargs[]){

System.out.println("Welcometopackage");

}

}Note: the above program must be saved in folder mypack and the name of the source file must be Simple.javaTo Run the package program

i) Compile using javac

D:\sathiya\javac Simple.java

ii) Run using java

D:\sathiya\java mypack.Simple

WelcometopackageSetting a class path

By default java runtime(i.e., interpreter) looks for .class files only in the current directory, Because java runtime uses the current working directory as its starting point To import classes in the package from anywhere, add a path of parent directory of your package, where it residing into environment variable classpath.

For example if your package pkg1.pkg2 is residing in d:\sathiya then you have to set classpath has

set classpath=%classpath%;d:\sathiya;.;Importing package/class importation

A class can use all classes from its own package and all public classes from other packages.

Accessing public classes from other packages can be done in

a) Using fully qualified name Add full package name in front of every class name

b) Using import statement

Can import certain classes from a package or whole package

Syntax

import pkg1[.pkg2].(classname | * );you specify classname or *. Here * indicates that the java compiler should import the entire package into memory

In java source file, import statements must occur immediately following package statement and before any class definitionse.g.1:

import java.util.Scanner; // (or) import java.util.*;

class Employee

{

public static void main(String args[])

{

String name;

Scanner input=new Scanner(System.in );

System.out.println(input.nextInt());

}

}

e.g.2 (without import statement using fully qualified name)class Employee

{

public static void main(String args[])

{

String name;

java.util.Scanner in=new java.util. Scanner(System.in );

System.out.println(input.nextInt());

}

}

Static import

the static import facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name. syntax

import static packagename; e.g.,

import static java.lang.System;

Program that implements import static

import static java.lang.System;

classStaticImportExample

{

publicstaticvoidmain(Stringargs[])

{

out.print("Hello");//NownoneedofSystem.out

out.println(" Java");

}

}

Output:

Hello JavaIntroducing Access controls

important attribute of encapsulation is access control.

Through encapsulations access control, you can control what part of the program can access the member of the class, which help to prevent misuse of member of the class

Java supports rich set of access-specifier that defines various level of visibility of class members. They are : public, private, protected, and default (package protected) Visibility/accessibility control means restricting the access of instance variables and methods of the class from outside world Java contains 4 categories of visibility for class members as shown in the table:Access locationprivatedefault/package private/package protectedprotectedpublic

Within the same classYesYesYesYes

subclasses in the same packagesNoYesYesYes

non-subclass in the same package NoYesYesYes

subclass in other package NoNoYesYes

non-subclass in other packageNoNoNoYes

Note: A Class has only two possible access levels: default and public

When a class is declared a public, it can be accessed in the package or from other packages.

If class is declared without access-specifier(i.e., default), it can be accessed from other classes within the package, but not from other packages

Example program for package

The following programs has to be stored in the pack1\subpack1 folder

Parent.java

package pack1.subpack1;

public class Parent {

private int a=10; int b=20;

protected int c=20;

public int d=40;

public int getA() // method helps to access private variable a from other classes

{ return a; }

}

SamePackage.java

package pack1.subpack1;

public class SamePackage {

public static void main(String args[]) {

Parent p = new Parent(); // error, private variable not accessible outside its class // System.out.println(Private variable + p.a); // used public method to access a of same class

System.out.println(Private variable: + p.getA());

System.out.println(Default variable: + p.b);

System.out.println(Protected variable : + p.c);

System.out.println(Public variable: + p.d);

}

}

Note : Here both the classes Parent and SamePackage are stored in the same package pack1.subpack1, so that SamePackage.class, can access member of Parent : b, c and d , but not a Output

Private variable: 10

Default variable: 20

Protected variable: 30

Public variable: 40

THE STRING CLASS Strings are a sequence of characters.

Java does not have primitive string type. Java library contains pre-defined class called String class In the Java programming, strings are objects. The String class is immutable, so that once it is created a String object cannot be changed. String class is in java.lang package

String class is declared as final(i.e, this class cannot be inherited from other class)

String Constructors/Creating Strings

String object can be constructed a number of way.

1. The most direct way to create a string is to write:

String greeting = "Hello world!";

here, "Hello world!" is a string literala series of characters that is enclosed in double quotes.

Whenever compiler encounters a string literal in your code, the compiler creates a String object with its valuein this case, Hello world!.

You can also create string using a constructor. The constructor of the String is listed below:

2. String( ); - When you invoke default constructor, it creates string with no character in it.

e.g.:

String s=new String( ); // s=null

3. String(String str); - It will create new String object from the existing object str e.g.:

String s1=Welcome;

String s2=new String(s1); // s2=Welcome

4. String(char c[]); - It will create new String object from character array c. In the following example string object is created from character array:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};

String helloString = new String(helloArray);

System.out.println(helloString); // print hello

Finding length of the stringa) int length() - This method is used to find number of characters stored in a string objectString s= "welcome ";

int len=s.length();

System.out.println( length of s is+len); // len = 7

Character Extraction

String class provides a number of ways to extract characters from string object.a) char charAt(int index);

used to retrieve single character from the specified index. This will raise ArrayIndexOutofBounds exception, if the value of index is more than the length of the string E.g., String s=welcome;

char ch=s.charAt(4);

System.out.println(ch=+ch); \\ch=ob) char[ ] toCharArray(); - converts all the characters in a String object into a character array. String s=abcd;

//c=abcd\0

char c[]=s.toCharArray( ); for(char tmp:c)

System.out.print(tmp+,); // will print a,b,c,d;

String Comparison

The String class includes several methods that compare strings or substrings within stringsa) boolean equals(Object str)

used to compare two strings for equality. Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive e.g., String s1=Hello;

String s2=new String(Hello);

String s3=new String(hello);

System.out.println(s1.equals(s2)=+ s1.equals(s2)); //return true

System.out.println(s1.equals(s3)=+ s1.equals(s3)); //return false

System.out.println(s1.equalsIgnoreCase(s3)=+ s1.equalsIgnoreCase(s3));

//return true

b) boolean equalsIgnoreCase(String str); used to compare two strings without case sensitive.

c) equals( ) versus ==

It is important to understand that the equals( ) method and the == operator perform two different operations. equals( )==

The equals( ) method compares the characters inside a String objectThe == operator compares two object references to see whether they refer to the same instance

It is a method It is an operator

The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

String s1 = "Hello";String s2 = new String(s1);String s3=s1;System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));

System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));System.out.println(s1 + " == " + s3 + " -> " + (s1 == s3)); The above code fragment will print:

Hello equals Hello -> true

Hello == Hello -> false // s1 and s3 refers to different address in memoryHello == Hello -> true // s1 and s3 refers to same address in memoryd) int compareTo(String str) - The Shing method compareTo( ) will compare the content of invoking string with str and return the following values:

< 0, If the invoking string object is less than parameter str

= 0, If the invoking string object is , equal to parameter str

> 0, If the invoking string object is greater than parameter str

String s1 = "Bala";

String s2 = "Arun";

if(s1.compareTo(s2)==0)

System.out.println( both s1 and s2 are equal);

else if(s1.compareTo(s2)