Friday, 10 May 2013

What is class and object in Java ?

What is class and object?

What is class and object in Java


  1.   A class is a template from which objects are created. That is objects are instance of a class.
  2.  When you create a class, you are creating a new data-type. You can use this type to declare objects of that type.
  3.  Class defines structure and behavior (data & code) that will be shared by a set of objects
A class is declared by use of the class keyword. Classes may contain data and code both.
The general form of al class definition:
            class ClassName
            {
                        type instance variable1;
                        type instance variable2;
                       
                        type methodname1 (parameter list)
                        {
                                    body of method;
                        }
                        type methodname2 (parameter list)
                        {
                                    body of method;
                        }
             }

The data or variable are called instance variable. The code is contained within methods.
The method and variables defined within a class are called member of the class.

Example of Class


class Box
{
 double width;
 double height;
 double depth; 
}
class BoxDemo
{
 public static void main (String args[])
 {
  Box mybox = new Box ();
  double vol;
  mybox.width =10;
  mybox.height = 20;
  mybox.depth = 30;
  vol = mybox.width * mybox.height * mybox.depth;
  System.out.println (“Volume is: - “+vol);
 }
}


  • Each object contains its own copy of each variable defined by the class.
  • So, every Box object contains its own copy of the instance variables width, height and depth.
  • To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable.

Declaring Object

•        Box mybox;     // declare ref. to object which contains null value.
•        mybox = new Box ();   // allocate a Box object.

General form of a new

            class var = new classname ();
            mybox = new Box ();
Where:
            class var =  variable of the class type.
            classname = name of the class.
The classname followed by parentheses specifies the constructor for the class.
A constructor defines what occurs when an object of a class is created.
Most classes explicitly define their own constructors within their class definition but if no explicit constructor is specified then java will automatically supply a default constructor.
This is the case with Box. This is default constructor.

Assigning Object Reference Variable

Box b1 = new Box ();
Box b2 = new b1;
After this executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object.
It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring,since they are the same object.

Introducing Methods

type name (parameter-list)
{
            body of method
}
Where:
Type : Specifies the type of data returned by the method.If the method does not return a value its ret urn type must be void.
Name: Specifies the name of the method.
Parameter-list: It is a sequence of type & identifiers pairs separated by commas.
Parameters are variables that receive the value of the argument passed to the method when it is called. If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using the following form of the return statement;
Return value;

Types of Methods

  1. Does not return value – void
  2. Returning a value
  3. Method which takes parameter

Garbage Collection in Java

Garbage Collection



  •   Objects are dynamically allocated by using the new operator.
  •  In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator.
  •  Java handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.
  • When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

Garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program. Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.


Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system. However, many systems use a combination of approaches, including other techniques such as stack allocation and region inference.

Resources other than memory, such as network sockets, database handles, user interactionwindows, and file and device descriptors, are not typically handled by garbage collection. Methods used to manage such resources, particularly destructors, may suffice to manage memory as well, leaving no need for GC. Some GC systems allow such other resources to be associated with a region of memory that, when collected, causes the other resource to be reclaimed; this is called finalization. Finalization may introduce complications limiting its usability, such as intolerable latency between disuse and reclaim of especially limited resources, or a lack of control over which thread performs the work of reclaiming.

Thursday, 9 May 2013

What is JVM ?


Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.
In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javaccompiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The javalauncher tool then runs your application with an instance of the Java Virtual Machine. An overview of the software development process.
Java Process

One characteristic of Java is portability, which means that computer programs written in the Java language must run similarly on any supported hardware/operating-system platform. This is achieved by compiling the Java language code, not to machine code but to Java bytecode – instructions similar to machine code but intended to be interpreted by a virtual machine (VM) written specifically for the host hardware. End-users commonly use a Java Runtime Environment (JRE) installed on their own machine for standalone Java applications, or in a Web browser for Java applets. Standardized libraries provide a generic way to access features such as graphics, threading, networking and much more. A major benefit of using bytecode is porting. However, the overhead of interpretation means that interpreted programs almost always run more slowly than programs compiled to native executables would, and Java suffered a reputation for poor performance. This gap has been narrowed by a number of optimization techniques introduced in the more recent JVM implementations.
Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code. Through the Java VM, the same application is capable of running on multiple platforms.
Java Cross Platform Support

Java Platform:
platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms.

Java Platform Simplified

The Java platform has two components:
  • The Java Virtual Machine
  • The Java Application Programming Interface (API)
Virtual Machine is the base for the Java platform and is ported onto various hardware-based platforms.
The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages.
As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. A platform is the hardware or software environment in which a program runs. We’ve already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms.
The general-purpose, high-level Java programming language is a powerful software platform. Every full implementation of the Java platform gives you the following features:
  • Development Tools: The development tools provide everything you’ll need for compiling, running, monitoring, debugging, and documenting your applications. As a new developer, the main tools you’ll be using are the javac compiler, the java launcher, and the javadocdocumentation tool.
  • Application Programming Interface (API): The API provides the core functionality of the Java programming language. It offers a wide array of useful classes ready for use in your own applications. It spans everything from basic objects, to networking and security, to XML generation and database access, and more. The core API is very large; to get an overview of what it contains, consult the Java SE Development Kit 6 (JDKTM 6) documentation.
  • Deployment Technologies: The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users.
  • User Interface Toolkits: The Swing and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces (GUIs).
  • Integration Libraries: Integration libraries such as the Java IDL API, JDBCTM API, Java Naming and Directory InterfaceTM (“J.N.D.I.”) API, Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote objects.

What is Java ? and Features of JAVA

Java features

What is Java?

u Java is a programming language that:
n  Is exclusively object oriented
n  Has full GUI support
n  Has full network support
n  Is platform independent
n  Executes stand-alone or “on-demand” in web browser as applets

Features of JAVA

  1. Simple
  2. Secure
  3. Portable
  4. Object-oriented
  5. Robust
  6. Multithreaded
  7. Architecture-natural
  8. Interpreted
  9. High performance
  10. Distributed
  11. Dynamic

  1. Simple

v  Java was designed to be easy for the professional programmer to learn and use effectively.
v  Assuming that you have some programming experience, you will not find java hard to master.
v  If you already understand the basic concepts of object oriented programming, learning java will be even easier.
v  If you are an experienced C++ programmer, moving to java will require very little effort. Because java inherits the C/C++ syntax and many of the object oriented features of C++, most programmers have little trouble learning Java.

  1. Security


v  Security is the benefit of java. Java system not only verifies all memory access but also ensure that no viruses are communicated with an applet.

      3. Portable

      The most significant contribution of java over other language is its portability.
      Java programs can be easily moved from one computer system to another.
      Java ensures portability in two ways:
      1. Java compiler generates byte code instruction that can be implemented on any machine.
      2.   The size of the primitive data types is machine-independent.

  1. Object-Oriented


vJava is a true object oriented language. All program code and data reside within object       and classes. The object model in java is simple and easy to extend.

  1. Robust(healthy, strong)


v  The multiplatform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a high priority in the design of java.
v  To gain reliability, java has strict compile time and run time checking for codes.
v  To better understand how java is robust, consider two main reasons for program failure: memory management mistakes and mishandled exceptional conditions.

  1. Multithreaded


v  Java was designed to meet the real-world requirement of creating interactive, networked programs.
v  To accomplish this, java supports multithreaded programming, which allows you to write programs that do many things simultaneously.
v  The java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems.
v  Java’s easy to use approach to multithreading allows you to think about the specific behavior of your program, not the multitasking subsystem.

  1. Architecture-Neutral


v  A central issue of java programmers was that code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow- even on the same machine.
v  Operating system upgrades, and changes in core system resources can al combine to make a program malfunction.
v  The java designer made several hard decisions in the java language and the java virtual machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any time, forever.”


  1. Interpreted


v  Usually a computer language is either compiled or interpreted. Java combines these approaches thus making java a two-stage system.
v  Java compiler translates source code into byte code instructions. Byte codes are not machine instructions and so java interpreter generates machine code that can be directly executed by the machine that is running the java program.
v  We can thus say that java is both a compiled and an interpreted language.

  1. High Performance


Java performance is impressive for an interpreted language, mainly due to the use    of intermediate byte code.

  1. Distributed


v  Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.
v  Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.

  1. Dynamic


v  Java is capable of dynamically linking in new class libraries, methods and object.

v  Java can also determine the type of class through a query, making it possible to either dynamically link or abort the program. 

Concept of Redirection and Piping in Unix

 Most UNIX commands expect input to come from a file(s), and produce output to anther file(s).  “One of these files is the standard input, and is the place from which a program expects to read its input.  Another is called the standard output, and it is the file to which the program writes its results.  The third file is the diagnostic output (also called Standard error), and it is a file to which program writes any error responses.  Generally, the standard input is taken to be the keyboard (input is typed by the user), the standard output is the terminal screen.

Concept of Redirection



(1) Redirection Input:


            There are two possible sources of input for UNIX commands.  Programs such as ls and find get their input from the command line in the form of options and filenames.  Other programs, such as cat, can get their data from the standard input as well as from the command line.  Try the cat command with no options on the command line:

$cat

            There is no response.  Because n files are specified with the command, cat waits to get its input from your keyboard, the standard input file.  The program will accept input lines from the keyboard until it sees a line which begins with Ctrl+D, which is the end of file signal for standard input.

            To redirect the standard input, you use the < operator.  For example, if you wanted cat to get its input from output.txt you could use the command.

$cat<output.txt

            The difference between this command and

$cat output.txt

            is a subtle one.  In filenames provided as options to a command, you can use filename substitution.  When redirecting input, you must use the name of an existing file or device.

(2) Redirection Output:


            Now, let’s say that you want to send the output of cat to a file, to save our shopping list on disk.  The shell lets you redirect standard output to a file name, by using the “>” symbol.  Here’s how it works:

$cat amg.txt>output.txt

            The > operator causes a new file to be created.  If you had already created a file named output.txt, it would be deleted and replaced with the new data.  If you wanted to add the new data to the old output, you could use the >> operator.  For example.

$cat amg.txt>>output.txt

            This will add content of amg.txt to output.txt file both file must be exists at specified path.


Concept of Piping


Suppose that you wanted a directory listing that was sorted by the mode file type plus permissions.  To accomplish this, you might redirect the output from ls to a data file and then sort that data file.  For example.

$ls –l>tempfile

$sort<tempfile

-rw-rw-r-         1          marsha             adept   1024    Jan 20 14:14 Lines.dat
-rw-rw-r-         1          marsha             adept   3072    Jan 20 14:14 Lines.idx
-rw-rw-r-         1          marsha             adept   256      Jan 20 14:14 Pages.dat

            Although you get the result that you wanted, there are three drawback to this method:

            You might end up with a lot of temporary file in your directory.  You would have to go back and remove them.  The sort program does not begins its work until the first command is complete.  This is not too significant with the small amount of data used in this example, but it can make a considerable difference with larger files.  The final output contains the name of your temp file, which might not be what you had in mind.

            Fortunately, there is a better way.

            The pipe symbol (|) causes the standard output of the program on the left side of the pipe to be passed directly to the standard input of the program on the right side of the pipe symbol.  Therefore, to get the same results as before, you can use the pipe symbol.  For example

$ls –l|sort

-rw-rw-r-         1          marsha             adept   1024    Jan 20 14:14 Lines.dat
-rw-rw-r-         1          marsha             adept   3072    Jan 20 14:14 Lines.idx
-rw-rw-r-         1          marsha             adept   256      Jan 20 14:14 Pages.dat

            To connect two or more operation within the same stream at that time pipe sign is used to perform such a operation in unix.



Wednesday, 8 May 2013

Useful Commands in Ubuntu

A comprehensive list of commands needed when using Ubuntu:



Command privileges.

    sudo command - run command as root
    sudo su – root shellopen
    sudo su user – open shell as a user
    sudo -k – forget your password sudo
    gksudo command – sudo visual dialog (GNOME)
    kdesudo command – sudo visual dialog (KDE)
    sudo visudo – edit / etc / sudoers
    gksudo nautilus – root file manager (GNOME)
    kdesudo konqueror – root file manager (KDE)
    passwd – change your password 

Command Network


    ifconfig – displays information network
    iwconfig – displays information from wireless
    sudo iwlist scan – scan wireless networks
    sudo /etc/init.d/networking restart – reset the network
    (file) /etc/network/interfaces – manual configuration
    ifup interface – bring online interface
    ifdown interface – disable interface 

Commands Display
    sudo /etc/init.d/gdm restart – reset X (Gnome)
    sudo /etc/init.d/kdm restart – reset X (KDE)
    (file) /etc/X11/xorg.conf – show Configuration
    sudo dpkg-reconfigure - reconfigure xserver-xorg-phigh - reset configuration X
    Ctrl+Alt+Bksp – X display reset if frozen
    Ctrl+Alt+FN – switch to tty N
    Ctrl+Alt+F7 – switch back to X display 

Commands Service System.

    start service – service to start work (Upstart)
    stop service – service to stop working (Upstart)
    status service – check if service is running (Upstart)
    /etc/init.d/service start – start service (SysV)
    /etc/init.d/service stop – stop service (SysV)
    /etc/init.d/service status – check service (SysV)
    /etc/init.d/service restart – reset service (SysV)
    runlevel – get current runlevel 

Commands for Firewall.
    ufw enable – turn on the firewall
    ufw disable – turn off the firewall
    ufw default allow – allow all connections by default
    ufw default deny – drop all connections by default
    ufw status – current rules and
    ufw allow port – to allow traffic on port
    ufw deny port – port block
    ufw deny from ip – ip block 

Command System.


    lsb_release -a – get the version of Ubuntu
    uname -r – get kernel version
    uname -a – get all the information kernel 

Commands for Package Manager.


    apt-get update – refresh updates available
    apt-get upgrade – update all packages
    apt-get dist-upgrade – version update
    apt-get install pkg – installing pkg
    apt-get remove pkg – uninstall pkg
    apt-get autoremove – removing packages obsotletos
    apt-get -f install – try to fix packages
    dpkg –configure -a – try to fix a broken package
    dpkg -i pkg.deb – install file pkg.deb
    (file) /etc/apt/sources.list – list of repositories APT 

Special Packages For commands.
    ubuntu-desktop – Setting the standard Ubuntu
    kubuntu-desktop –KDE Desktop  
    xubuntu-desktop – desktop XFCE
    ubuntu-minimal – core earnings Ubuntu
    ubuntu-standard – the standard utilities Ubuntu
    ubuntu-restricted-extras – not free, but useful
    kubuntu-restricted-extras – ditto KDE
    xubuntu-restricted-extras – ditto XFCE
    build-essential – packages used to compile
    linux-image-generic – latest generic kernel image
    linux-headers-generic – latest headlines 

Applications commands.

    nautilus – File Manager (GNOME)
    dolphin – File Manager (KDE)
    konqueror – Web browser (KDE)
    kate – text editor (KDE)
    gedit – text editor (GNOME)