Tuesday, August 12, 2008

Access Modifiers

Access Modifiers

1. private
2. protected
3. default
4. public

public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

private access modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. 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.

protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. 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.

default access modifier

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.

Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers.

The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below.

package pckage1;

class BaseClass {

public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
private int getY() {
return y;
}
private void setY(int y) {
this.y = y;
}
protected int getZ() {
return z;
}
protected void setZ(int z) {
this.z = z;
}
int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}

public class SubclassInSamePackage extends BaseClass {

public static void main(String args[]) {
BaseClass rr = new BaseClass();
rr.z = 0;
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(20);
System.out.println("Value of x is : " + subClassObj.x);
//Access Modifiers - Public
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
/* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
//Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
}
}

Output

Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20

The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).

import pckage1.*;

public class SubClassInDifferentPackage extends SubclassInSamePackage {

public int getZZZ() {
return z;
}

public static void main(String args[]) {
SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage();
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access specifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : " + subClassObj.x);
//Access specifiers - Private
// if we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
/* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/
//Access specifiers - Protected
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.
/* System.out.println("Value of z is : "+subClassObj.z);

subClassObj.setZ(30);

System.out.println("Value of z is : "+subClassObj.z);*/
System.out.println("Value of z is : " + subClassDiffObj.getZZZ());
//Access Modifiers - Default
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.
/*

System.out.println("Value of a is : "+subClassObj.a);

subClassObj.setA(20);

System.out.println("Value of a is : "+subClassObj.a);*/
}
}

Output

Value of x is : 10
Value of x is : 30
Value of z is : 10

The third class is ClassInDifferentPackage.java which is present in a different package then the first one.

import pckage1.*;

public class ClassInDifferentPackage {

public static void main(String args[]) {
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : " + subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : " + subClassObj.x);
//Access Modifiers - Private
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private
/* System.out.println("Value of y is : "+subClassObj.y);

subClassObj.setY(20);

System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.
/* System.out.println("Value of z is : "+subClassObj.z);

subClassObj.setZ(30);

System.out.println("Value of z is : "+subClassObj.z);*/
//Access Modifiers - Default
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.
/* System.out.println("Value of a is : "+subClassObj.a);

subClassObj.setA(20);

System.out.println("Value of a is : "+subClassObj.a);*/
}
}

Output

Value of x is : 10
Value of x is : 30

Basic Language Elements

Java 1.5 Features

Java 1.5

The Java 1.5 released in September 2004.

Goals

Less code complexity
Better readability
More compile-time type safety
Some new functionality (generics, scanner)

New Features

Enhanced for loop
Enumerated types
Autoboxing & unboxing
Generic types
Scanner
Variable number of arguments (varargs)
Static imports
Annotations

Getting Started with Java

Java Architecture

The Java environment is composed of a number of system components. You use these components at compile time to create the Java program and at run time to execute the program. Java achieves its independence by creating programs designed to run on the Java Virtual Machine rather than any specific computer system.

  • After you write a Java program, you use a compiler that reads the statements in the program and translates them into a machine independent format called bytecode.
  • Bytecode files, which are very compact, are easily transported through a distributed system like the Internet.
  • The compiled Java code (resulting byte code) will be executed at run time.

Java programs can be written and executed in two ways:

  • Stand-alone application (A Java Swing Application)
  • Applet which runs on a web browser (Example: Internet Explorer)


Java source code

A Java program is a collection of one or more java classes. A Java source file can contain more than one class definition and has a .java extension. Each class definition in a source file is compiled into a separate class file. The name of this compiled file is comprised of the name of the class with .class as an extension. Before we proceed further in this section, I would recommend you to go through the ‘Basic Language Elements'.

Below is a java sample code for the traditional Hello World program. Basically, the idea behind this Hello World program is to learn how to create a program, compile and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}//End of main
}//End of HelloWorld Class

Output

Hello World

ABOUT THE PROGRAM

I created a class named "HelloWorld" containing a simple main function within it.
The keyword class specifies that we are defining a class.
The name of a public class is spelled exactly as the name of the file (Case Sensitive).

All java programs begin execution with the method named main(). main method that gets executed has the following signature :

public static void main(String args[]).

Declaring this method as public means that it is accessible from outside the class so that the JVM can find it when it looks for the program to start it.

It is necessary that the method is declared with return type void (i.e. no arguments are returned from the method).

The main method contains a String argument array that can contain the command line arguments. The brackets { and } mark the beginning and ending of the class.
The program contains a line 'System.out.println("Hello World");' that tells the computer to print out on one line of text namely 'Hello World'. The semi-colon ';' ends the line of code.
The double slashes '//' are used for comments that can be used to describe what a source code is doing. Everything to the right of the slashes on the same line does not get compiled, as they are simply the comments in a program.

Java Main method Declarations

class MainExample1 {public static void main(String[] args) {}}
class MainExample2 {public static void main(String []args) {}}
class MainExample3 {public static void main(String args[]) {}}

All the 3 valid main method's shown above accepts a single String array argument.

Compiling and Running an Application

To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools. Download an editor like Textpad/EditPlus to type your code. You must save your source code with a .java extension. The name of the file must be the name of the public class contained in the file.

Steps for Saving, compiling and Running a Java

Step 1:Save the program With .java Extension.
Step 2:Compile the file from DOS prompt by typing javac .
Step 3:Successful Compilation, results in creation of .class containing byte code
Step 4:Execute the file by typing java

Java Development Kit

The Java Developer's Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries and packages, and tools

javadoc

The javadoc tool provided by Sun is used to produce documentation for an application or program,

Jar Files

A jar file is used to group together related class files into a single file for more compact storage, distribution, and transmission.

PATH and CLASSPATH

The following are the general programming errors, which I think every beginning java programmer would come across. Here is a solution on how to solve the problems when running on a Microsoft Windows Machine.

1. 'javac' is not recognized as an internal or external command, operable program or batch file

When you get this error, you should conclude that your operating system cannot find the compiler (javac). To solve this error you need to set the PATH variable.

How to set the PATH Variable?

Firstly the PATH variable is set so that we can compile and execute programs from any directory without having to type the full path of the command. To set the PATH of jdk on your system (Windows XP), add the full path of the jdk\bin directory to the PATH variable. Set the PATH as follows on a Windows machine:

a. Click Start > Right Click "My Computer" and click on "Properties"
b. Click Advanced > Environment Variables.
c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A typical value for PATH is:

"C:\jdk version\bin (jdk version is nothing but the name of the directory where jdk is installed)"

2. Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld


If you receive this error, java cannot find your compiled byte code file, HelloWorld.class.If both your class files and source code are in the same working directory and if you try running your program from the current working directory than, your program must get executed without any problems as, java tries to find your .class file is your current directory. If your class files are present in some other directory other than that of the java files we must set the CLASSPATH pointing to the directory that contain your compiled class files.CLASSPATH can be set as follows on a Windows machine:

a. Click Start > Right Click "My Computer" and click on "Properties"
b. Click Advanced > Environment Variables.

Add the location of classes’ folder containing all your java classes in User Variables.

If there are already some entries in the CLASSPATH variable then you must add a semicolon and then add the new value . The new class path takes effect in each new command prompt window you open after setting the CLASSPATH variable.

Javabeginner Tutorial

Javabeginner Tutorial

Table of Contents

Introduction to Java

About Java
Platform Independence
Java Virtual Machine
Object Oriented Programming
Java Features
Java Applications

Getting Started with Java
Java Architecture
Compiling and Running an Application
Java Development Kit
javadoc
JAR Files
PATH and CLASSPATH
Introduction to Java 1.5


Basic Language Elements
Keywords
Comments
Variable, Identifiers and Data Types
Classes
Objects
Interface
Instance Members
Static Members
Arrays


Java Operators
Java Operators
Assignment operators
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Compound operators
Conditional operators
Operator Precedence


Java Control Statements
Introduction to Control Statements
Selection Statements
Iteration Statements
Transfer Statements


Java Access Modifiers
Introduction to Java Access Modifiers
public access modifier
private access modifier
protected access modifier
default access modifier


Classes and Objects
Class Variables – Static Fields
Class Methods – Static Methods
Instance Variables
Final Variable, Methods and Classes
Introduction to Java Objects
Method Overloading


Java Constructors
Overloaded Constructors
Constructor Chaining


Object Serialization
Introduction to Object Serialization
Transient Fields and Serialization
Input and Output Object Streams


Java Class Inheritance
Java Class Inheritance
this and super keywords


Java Object Casting
Object Reference Type Casting
instanceof Operator


Abstract class and Interface
Abstract Class in java
Java Interface
Polymorphism


Java Method Overriding


Java String Class
String Class
Creation of Strings
String Equality
String Functions


Java toString() Method
Java toString() Method

Java String Comparison
Compare String objects to determine Equality

Java StringBuffer
StringBuffer Class
Creation of StringBuffer's
StringBuffer Functions


Java Exception Handling
Exceptions in Java
Exception Classes
Exception Statement Syntax
Rules for try, catch and finally Blocks
try, catch and finally
Defining new Exceptions
throw, throws statement
Handling Multiple Exceptions


Java Singleton Design Pattern

Singleton
Implementing the Singleton Pattern


Java Threads Tutorial
Introduction to Threads
Thread Creation
Thread Synchronization
Synchronized Methods
Synchronized Blocks
Thread States
Thread Priority
Thread Scheduler
Yielding
Sleeping and Waking Up
Waiting and Notifying
Joining
Deadlock


Java Collections Framework
Core Collection Interfaces
Concrete Classes
Standard utility methods and algorithms
How are Collections Used
Java ArrayList
Java LinkedList
Java TreeSet
Java HashMap
Java Vector
Java HashTable
Java HashSet


Java Date Util
Java Date API
Java Date Source Code


Java Swing Tutorial
Intoduction to Java Swing
JFrame
JInternalFrame
JWindow
JOptionPane
JLabel
JTextField
JPasswordField
JTextArea
JButton
JRadioButton
JCheckBox
JComboBox
JList
JTabbedPane
JMenuBar
Scrollable JPopupMenu
JToolBar
BorderLayout
FlowLayout
GridLayout
GridBagLayout
Java Look and Feel
Swing Calculator
Swing Address Book

OOPS Concepts

OOPS:
  • Object Oriented Programming or OOP is the technique to create programs based on the real world.
  • Unlike procedural programming, here in the OOP programming model programs are organized around objects and data rather than actions and logic.
  • In OOP based language the principal aim is to find out the objects to manipulate and their relation between each other.
  • Another important work in OOP is to classify objects into different types according to their properties and behavior.

What Is an Object?

  • An object is a software bundle of related state and behavior.
  • Objects are the basic unit of object orientation with behavior, identity.
  • Objects in programming language have certain behavior, properties, type, and identity.
  • An object is expressed by the variable and methods within the objects.
  • Again these variables and methods are distinguished from each other as instant variables, instant methods and class variable and class methods.
  • Attributes are defined by variables and Behaviors are represented by methods

What Is a Class?

  • A class is a blueprint or prototype from which objects are created.
  • It is the central point of OOP and that contains data and codes with behavior.
  • In Java everything happens within class and it describes a set of objects with common behavior.
  • The class definition describes all the properties, behavior, and identity of objects present within that class.

What Is Inheritance?

  • Inheritance provides a powerful and natural mechanism for organizing and structuring your software.
  • classes inherit state and behavior from their superclasses, ie. derive one class from another
  • This is the mechanism of organizing and structuring software program.
  • Though objects are distinguished from each other by some additional features but there are objects that share certain things common.
  • In object oriented programming classes can inherit some common behavior and state from others.
  • Inheritance in OOP allows to define a general class and later to organize some other classes simply adding some details with the old class definition.
  • This helps in a better data analysis, accurate coding and reduces development time.

Abstraction -
  • The process of abstraction in Java is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface).
  • It refers to the act of representing essential features without including the background details.
  • for example:If a customer wants to buy a car.he looks at its color,perfomance etc but he doesnt look at things like how these are functioning internally etc.

  • The technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept. A Java programmer makes use of abstraction to specify that a couple of functions form the same kind of task and can be merged to perform a single function.
  • Abstraction along with two other techniques, information hiding and encapsulation are the most significant techniques in software engineering. All of these three functionalities are known to reduce complexities in processing and programming.

Encapsulation -
  • This is an important programming concept that assists in separating an object's state from its behavior. This helps in hiding an object's data describing its state from any further modification by external component.
  • In Java there are four different terms used for hiding data constructs and these are public, private, protected and package.
  • As we know an object can associated with data with predefined classes and in any application an object can know about the data it needs to know about. So any unnecessary data are not required by an object can be hidden by this process.
  • It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented.
Abstraction Vs Encapsulation :
  • Abstraction means implementation hiding and Encapsulation means data hiding.


Polymorphism -
  • It describes the ability of the object in belonging to different types with specific behavior of each type.
  • So by using this, one object can be treated like another and in this way it can create and define multiple level of interface.
  • Here the programmers need not have to know the exact type of object in advance and this is being implemented at runtime.
There are two types of polymorphisms.

1.Compile-time polymorphism:
what object will be assigned to the present variable.
This will be evaluated at compile time.

2.Run-time polymorphism:
what object will be assigned to the present variable.
This will be evaluated at runtime depending on condition.



what are the oops concept in java explain with real time examples?
OOPS Concepts are mainly 4
1.Abstraction
2.Encapsulation
3.Inheritance/Delegation
4.Polymorphism

Abstraction:-Hiding non-essential features and showing the
essential features

(or)
Hiding unnecessary data from the users details,is called
abstraction.
Real Time example:TV Remote Button

in that number format and power buttons and other buttons
there.just we are seeing the butttons,we don't see the
button circuits.i.e buttons circutes and wirings all are
hidden.so i think its good example.



Encapsulation:

Writing Operations and methods stored in a single
class.This is Called Encapsulation

Real Time Example:Medical Capsule
i.e one drug is stored in bottom layer and another drug is
stored in Upper layer these two layers are combined in
single capsule.



Inheritance:
The New Class is Existing from Old Class,i.e SubClass is
Existing from Super Class.

Real Time Example: Father and Son Relationship



Polymorphism:

Single Form behaving differently in different Situations.

Example:- Person

Person in Home act is husband/son,
in Office acts Employer.
in Public Good Citizen.



what actually is the difference between Encapsulation & Data hiding & Data Abstraction

Data hiding is just a means by which one hides away data from the
external world... example, the lungs of a person is not seen by anyone,
but used for the internal working of the human being!

Data Encapsulation allows to package all the contents of the object.
They may or may not be public to the external world. Example, the skin
is part of the human, and so is the lung. Together all the components
of the human make up one whole being!

Data Abstraction is the means by which one displays only
what is required to the user. Sample - the mood of a person to a girl,
a snake, a cat, a father, or a boss. Though they are all emotions, they
differ based on the stimuli, and hence a portion of the whole is
displayed to the person who requests it.



Monday, August 11, 2008

Introduction to Java

What is the Java Virtual Machine? What is its role?
  • Java was designed with a concept of ‘write once and run everywhere’.
  • The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system.
  • When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files.
  • The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM.
  • A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler.
  • The JVM must be implemented on a particular platform before compiled programs can run on that platform.


Since Java is an object oriented programming language it has following features:

  • Reusability of Code
  • Emphasis on data rather than procedure
  • Data is hidden and cannot be accessed by external functions
  • Objects can communicate with each other through functions
  • New data and functions can be easily added

Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.

OOP Concepts

Four principles of Object Oriented Programming are
Abstraction
Encapsulation
Inheritance
Polymorphism

Abstraction

Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.

Encapsulation

* Hides the implementation details of a class.
* Forces the user to use an interface to access data
* Makes the code more maintainable.

Inheritance

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism

Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.