Friday, October 21, 2011

Basic Of Java.♥

✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮● ────█──────────────────────────█ ──█─█─█──────────────────────█─█ ███─█─█────███───███───████──█─█ █─█─█─█──────█───█─█──────█──█─█ ███████────███████████████████─█ ──────────────────────────────── ●✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮✿⊱╮●


LECTURE NO: 1
Introduction of Java language

Java is a high-level, third generation programming language, like C, Fortran, Smalltalk, Perl, and many others.
Java is a programming language that was introduced by Sun Microsystems in June 1995.
It is a language for professional programmers.
Java is built upon C and C++. It derives its syntax from C. its object oriented features are influenced by C++.
Unlike C++ Java is not a superset of C. A Java compiler won't compile C code, and most large C programs need to be changed substantially before they can become Java programs.
                                           
       Brief History of Java Language
In January of 1991, James Gosling, Mike Sheridan, Patrick Naughton and several other individuals met to discuss the ideas for the Stealth Project.
The goal of the Stealth Project was to do research in the area of application of computers in the consumer electronics market.
The vision of the project was to develop "smart" consumer electronic devices that could all be centrally controlled and programmed from a handheld-remote-control-like device.
According to Gosling, "the goal was ... to build a system that would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work.
Members of the Stealth Project, which later became known as the Green Project, divided the tasks amongst themselves.
Mike Sheridan was to focus on business development,
Patrick Naughton was to begin work on the graphics system, and
James Gosling was to identify the proper programming language for the project.
Gosling began with C++, but soon after was convinced that C++ was inadequate for this particular project.
His extensions and modifications to C++ were the first steps towards the development of an independent language that would fit the project objectives.
He named the language "Oak" while staring at an oak tree outside his office window!
 The name "Oak" was later dismissed due to a patent search which determined that the name was copyrighted and used for another programming language, so another name had to be chosen“, and was later(in 1995) renamed Java, from a list of random words.
                                    
James Gosling
James Gosling is generally credited as the inventor of the Java programming language
He was the first designer of Java and implemented its original compiler and virtual machine
He is also known as the Father of Java
Between 1984 and 2010, Gosling was with Sun Microsystems.
On April 2, 2010, Gosling left Sun Microsystems which had recently been acquired by the Oracle Corporation.
                                
 Purpose of creating Java Language

In June 1991 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
Through C and C++ were available to work with these languages, the compiler was targeted for a particular CPU.
Compiler is expensive and lots of time to create. Hence, it was possible to have compliers for every CPU. An easy and cost efficient solution is needed. This software had to be small, fast, efficient and platform-independent i.e.: a code that could run on different CPUs, under different environments. This led to the creation of Java.
Java language was initially called Oak after an oak tree that stood outside Gosling's office; and was later(in 1995) renamed Java, from a list of random words. It was not intended to be an internet programming language. However, the advent of the World Wide Web created a demand for software that was portable across all platforms.  Java was then adapted as an Internet Programming Language.
JDK Versions
JDK 1.02 (1995), Java was first publicly released.
JDK 1.1 (1996)
Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
In 2002, JDK 1.4 (codename Merlin was released, the most widely used version.
In 2004, JDK 5.0 (codename Tiger) was released, the latest version.
                                                   
 JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications or applets.
Java Enterprise Edition (J2EE)
J2EE can be used to develop server-side applications such as Java servlets and Java Server Pages.
Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile devices such as cell phones.


Java Program Structure
The first section of a Java program identifies the environment information. To do this, it specifies the classes or packages that will be referred to in the program. This information is specified with the help of the ‘import’ statement. A program may have more than one import statement. An example of an import statement is given below:

import java.awt.*;

This statement imports the ‘awt package’, which is used to create GUI objects. Here java is the name of the folder, which contains the package ‘awt’. The ‘*’ symbol denotes that all the classes under this package are included.

In Java, all code, including variable and methods should be included with in a class. A single program may have several classes. These classes may extend other classes. A semicolon terminates program statements. The program may also include comments. The complier ignores the comments.

The First Java Program

Let us start our first java program. We shall start with a simple application. The program is given below to display a message:

// This is a simple program called “First.java”

class First
{
    public static void main(String args[])
    {
        System.out.println(“My first java program”);
     }
}

the file name plays a very important role in java. The java compiler inside on a .java extension. In java, the code must reside in a class. Hence, the classname and filename have to be the same. Java is case sensitive. So, the file name should match the class name.
to compile the source code, execute the program using the javac compiler specifying the name of the source file at the command line as shown below:

C:\jdk1.2.1\bin javac First.java

The java compiler creates a First.class file that contains the bytecodes. The code cannot be directly executed. The java interpreter is required to execute this code. The command is given as follows:
C:\jdk1.2.1\bin java First
The following output is the displayed:

My first program in java    

Analysing the First Program

//  This is a simple program called “First.java”

The symbol ‘//’ stands for a commented line. The compiler ignores a comment line. Java also support multi line comments.

The next line declares a class called ‘First’. To create a class, prefix the keyword class, with the classname (which is also the name of file).

class First

The class name generally begins with capital letter.

The keyword ‘class’ declares the definition of the class. ‘First’ is the identifier for the name of the class. The entire class definition is done with in the open and closed curely braces. This marks the beginning and end of the class definition block.

public static void main(String args[])

This is the main method, from where program will begin its execution. All java application should have one main method. Let understand what each word in this statement means.

The ‘public’ keyword is an access specifier/modifier. It indicates that the class member can be accessed from anywhere in the program. In this case, the main method is declared as public, so that JVM can access this method.

The ‘static’ keyword allows the main to be called, without needing to create an instance of the class. But, in this case, a copy of main method is available in memory, even if no instance of that class has been created. This is important, because the JVM first invokes the main method to execute the program. Hence, this method must be static.

The ‘void’ keyword tells the compiler that the method does not return any value when executed.

The ‘main()’ method performs a particular task, and it is the point from which all java applications start.

‘String args[]’ method is the parameter passed to the main method. The variables mentioned within the parenthesis of a method receive any information that is to be passed to the method. These variables are the parameters of that method.

‘args[]’ is an array of type string. The arguments passed at the command line are stored in this array. The code within the opening and closing braces of the main method is called ‘method block’.

System.out.println(“My first java program”);

This line displays the string, ‘My first java program’ on the screen. It is followed by the new line. The ‘println()’ method produces the output. This method displays the string that is passed to it, with the help of ‘System.out’. Here, ‘System’ is a predefined class that provides access to the system, and ‘out’ is the output stream connected to theconsole.

Passing Command Line Arguments

The following shows how to receive command line arguments in the main method:

Class Pass
{
    public static void main(String parameters[] )
    {
         System.out.println(“This is what the main menthod received”);
         System.out.println(parameters[0]);
         System.out.println(parameters[1]);
         System.out.println(parameters[2]);
     }
}

We can pass arguments to the main method during executing the program as follow:

C:\jdk1.2.1\bin java Pass We change Lives
This is what the main method received
We
Change
Lives



                           
                                                          Lecture 02
                                              Features of java language



Simple

Object Oriented

Platform-Independent

Robust 
Secure
Distributed

Multithreaded

Dynamic


1.Simple:

The designer of java language were trying to develop a language that a programmer could learn quickly. They also wanted the language to be familiar to most programmers, for ease of migration. Hence, the java language removed a number of complex features that existed in C and C++. Java does not have features such as pointers manipulation, operator overloading etc. Java does not use the goto statement, or header files. Constructs like ‘struct’ and ‘union’ also been removed from Java.
2.Object Oriented:


Everything is an object in java. The focus, therefore is on the data, and the methods that operate on the data in our application. Java does not concentrate only on procedures. The data and methods together describe the state, and the behavior of an object. In java, you will use the term method in place of functions.
3.Platform-Independent:
Platform-Independent refers to the ability of the program to move from one computer to another, without any difficulty. Java is platform-independent at the source level, and the binary level.
Platform independent at the source level allows you to move your source code from one system to another, compile the code, and run it cleanly on a system.
Platform independent at the binary level allows you to move your binary file on multiple platforms, without recompiling the code. Here, however, you need a Java Virtual Machine(JVM) to function as an interpreter.
4.Robust:
Java is strictly a typed language. Java checks your code at the time of compilation, and also  at the time of interpretation. Thus it eliminates certain type of programming errors.
Java does not have pointers and pointer arithmetic. It checks all access to array and string at runtime, to ensure that they are in bounds. It also checks the caste of objects from one type to another at runtime.
In traditional programming environments, the programmer had to manually allocate memory. By the end of the program, the programmer had to also free this memory. In java, the programmer does not need to bother about memory allocation. It is done automatically, as java provides garbage collection for unused objects.
5.Secure:
Virus are a great cause of worry in the world of computers. Prior to the advent of Java, programmer had to first scan files, before downloading and executing them. Often, even this precaution was no guarantee against viruses.
Java provides a controlled environment for the execution of the program. It provides several layers of security control.
In the first layer, the data and the methods are encapsulated in the class. Then it can be accessed only through the interface that the class provides. Java does not allow any pointer arithmetic. Hence, it does not allow direct access to memory. It disallows array overflow, prevent reading memory out of bounds and provides garbage collection. All these features help minimize safety and probability problems.
In the second layer, the compiler ensures that the code is safe, and follow the protocols set by Java before compiling the code.
The third layer is the safety provided by the interpreter. The verifier thoroughly screens the bytecodes to ensure that they obey the rules before executing them.
The fourth layer takes care of loading the classes. The class loader ensure that the class does not violate the access restrictions, before loading it into the system.  
6.Distributed:
Java can be used to develop applications that are portable across multiple platforms, operating systems, and graphic user interface. Java is designed to support network applications. Hence, Java is widely used as a development in an environment like the Internet, which has different platforms.
7.Multithreaded:
Java programs use a process called ‘Multithreading’ to perform many tasks simultaneously. Java provides the master solution for the synchronizing multiple processes. This build-in support for thread enables interactive applications on the Net to run smoothly.
8.Dynamic:
Java is a dynamic language designed to adapt to an evolving environment. Java programs carry a lot of runtime information to validate and access objects at runtime. This makes it possible to link code dynmically.


TYPES OF JAVA PROGRAMS

             We can built various categories of program in Java
            Applets are used to develop games and visual effects among a host of   
            other applications.

      Applets: Applets are java programs created specially to work with the internet. They run through a java-enabled browser such as Netscape, or IE. You can use any Java development editing tool to create an applet. The applet must be contained or embedded within a Web page or HTML file. When the web page or HTML file is displayed on a browser, the applet is loaded and executed.
Command Line Applications: These Java programs run from a command prompt. They do not display any GUI-based screen. Such programs show console –based output.
       GUI Applications: These Java programs run stand alone and accept    
             user input through a GUI-based screen.
             Servlets: Java is suitable for web based n-tier application                       development.     An Applet is a GUI-based client side program that can be run on a browser. In a web based application, the client sends a request to a server. The server process the request, and sends back a response to the client. They are known as Java servlets. They are also called server side applets.
              Packages:  These are the class libraries in Java. A programmer may create his or her own package, or use the built in packages available on the Java 2 platform. Java.awt, java.io and java.applet are some of the built-in packages.
Database Applications:  These programs use the JDBC API for database connectivity. They could either be applets or applications.

                                                         


                                                       


                                                        LECTURE 04
                                                JAVA DEVELOPMENT KIT

(Java Development Kit) A Java software development environment from Sun. It includes the JVM, compiler, debugger and other tools for developing Java applets and applications.
When Java programs are developed under the new version, the Java interpreter (Java Virtual Machine) that executes them must also be updated to that same version.
              
                                                JDK Tools





The JDK has as its primary components a collection of programming tools, including:
The Java Compiler , ‘javac 
  the compiler, which converts source code into Java bytecode.
Syntax: javac sourcecodename.java
The Java Interpreter, ‘java’
  the loader for Java applications. This tool is an interpreter and can interpret the class files generated by the javac compiler.
Syntax: java sourcecodename
The Java Dissembler, ‘javap
The javap command dissembles Java bytecode that has already been compiled. After dissembling the code, it prints the information about the member variables and methods of class.
Syntax: javap classname
The Documentation Tool, ‘javadoc
the documentation generator, which automatically generates documentation from source code comments. Its creates a HTML file based on tags. These HTML files store information about the class and methods in a program.
  Syntax: javadoc sourcecodename
The Java Debugger, ‘jdb
This is a debugging tool for the java environment. It is typically used to find out syntactical and logical errors.
  Syntax: jdb sourcecodename //if code is present on the local machine.
  jdb host-password sourcecodename  // if code is on a remote machineThe appletviewer, ‘appletviewer
this tool can be used to run and debug Java applets without a web
browser.
Syntax: appletviewer url


      Java Core API

API stands for “Application Programming Interface”.
An API is the definition of how a programmer can access the functionality contained within a code library.
Java comes with many code libraries that provide pre-written functionality for programmers.
Some of the most commonly referred packages are:
1)  java.lang: the java.lang package consists of classes that are at the core of java language. These include the basic datatypes, such as int, char etc. it also include classes that handle exceptions and errors. The System class that facilitates the standard input, output, and errors output streams also define in this package.
2)Java.applet: the java.applet package is the smallest package. It consists a single class called Applet class. This class must be the parent class of any applet application.
3)java.awt: This  package is also called Abstract Window Toolkit. It consists resources to create GUI- based applications.
4)java.io: This package provides the standard Input/output library for the java language.
5)java.util: This package provides a number of useful utilities classes. The classes in this package include Date, Stack, Vector etc.
6)Java.net: This package provides the capabilities to communicates with remote machine. It creates or connects to sockets, or to URLs.
7)Java.awt.event: This  package is useful in calling the event listeners, and to use events any way you want. A listener is an object that is notified when an event occur.
8)Java.sql: This package encompasses the JDBC, or Java DataBase Connectivety. JDBC allows you to access relational database like Oracle and Ms-SQL server.
9)java.swing: A new set of classes and interfaces used to create an advance GUI.
     
     JAVA DEVELOPMENT        ENVIRONMENT

The Development environment is divided into two parts: a Java Compiler, a Java interpreter. Unlike C and C++, the Java Compiler converts the source code into bytecodes, which are machine independent. Bytecode are chunks of java instructions broken down into bytes, which can be
decoded by any processor.
The Java  Interpreter is also called the JVM (Java Virtual Machine), or Java Runtime interpreter. It executes the Java Bytecodes. Java has become such a universal language, that soon every operating system will be equipped with the Java Virtual Machine.
The Java Runtime Environment (JRE), also known as Java Runtime, is part of the Java Development Kit (JDK), a set of programming tools for developing Java applications. The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.

  
                               Lecture 05
              
 




Lecture No: 5, 6, & 7
 Java Language Fundamentals

Basics of the Java Language:
A program is a specific set of ordered operations to be performed by a computer. A program can be compared to a recipe, which contains a list of ingredients called variables, and a list of directions called statements. The statements tell the computer what to do with the variables.
      Let’s start with the basics of java language, such as classes and methods, data        
      Types, variables, operators and control statements
Classes in Java:-
In Java, classes define a template for units that store data and code related to an entity. They form the basis of the entire Java language.Any data that you store, or any code that you write, is always defined within a class. When you define a class you actually define a data type. This new data type can be used to define variables called ‘objects’. Objects are instances of the class. In Java we can also define an inner class. This is a nested class, whose instance exits within an instance of its enclosing class. It has direct access to the instance members of its enclosing instance.When we declare a class, we need to specify the data and the method that constitute the class.
Declaring Classes in Java:-
When we declare a class, we need to specify the data and the methods that constitute a class.
Syntax:
class class_name
{
       datatype variable_name;
       :
       :
       method_name ()
{
       statement 1;
       staztement 2;
}

Nested Classes:- 
    Defining one class within another class is called ‘Nesting’.
     There are two types of nested classes.
     Static Classes:
     A static class is declared with the static keyword. The static class must access members of enclosing class through an object. Hence, static classes are rarely used.
Non Static Class:
           The inner class is the most important type of nested class. It is non-static. The definition of inner class is visible only within the context of outer class. The inner class can access all members of the enclosing class, but not vice versa.

                     Data Types:-
Java provides several data types that are commonly supported on all platforms. For example, the int(integer) in Java is represented as 4 bytes in the memory on all machines.
The data types in the Java programming language are divided into two categories:
primative & refrence datatype.

Literals:-
Interger Literals: Any whole value is an integer literals e.g 1,20,42, and 85. There are all decimals values meaning they are describing a base 10 numbers. There are two other bases which are used in integer literals, octal(base 8), and Hexadecimal(base 16).
      Octal values are denoted in Java by a leading zero value. E.g: 04, 075, 0115 are   
      octal values.                                                                                                               
     Hexadecimal value are denoted in Java by a leading zero-x. E.g: 0x75, 0x42.
                   
                             Long Literals: To specify a long literals, you will need to explicitly tell
                             the compiler that the literal value is of type Long. You do this by
                             appending an upper or lower case L to literal. E.g: 922568L, 98765l are  
                             long literals.
                             Floating Point Literals:  it represent decimal values. Floating point
                             numbers can expressed in standard and scientific notation.
    Standard notation are 2.0, 3.14159, 0.667.
    Scientific notation uses standard notation plus a suffix that specifies a    
    power  of 10 by which the number is to multiply. E.g: 6.002E23, 2e-05
    You should appending a upper or lower case F to specify a floating    
     point literals.





A few Words about String


  In java, String is a predefine class not a simple type. Rather string defines an object.

  String type used to declare string variables. You can also declared array of string. A quoted string constant can be assign to a String variable. E.g:

           String str=“Java is an Object Oriented Programming Language”;
                           System.out.println(str)
Here str is an object of String class.
TYPE CASTING

  A situation may arise,  where you have to add a variable of the integer data type to a variable of the float data type. To handle such situations. Java has borrowed the typecasting feature of its predecessors. C and C++ . in type casting. One data type is converted into another  data type. This feature must be used carefully since incorrect usage can lead to data loss.
         The following code adds a float value to an integer, and stores the result in integer.
  Float c = 34.89675f;
  Int b= (int)c + 10;
 —  First, the float value in c is converted ta an integer value 34. it is then added to 10, and the resulting value, 44 is stored in b.

  In Java Type casting are divided into two types :

  Widening (small range to wide range) conversions do not lose information about the magnitude of a value. Widening conversions change a value to a type that accommodates a wider range than the original type.

  Narrowing (wide range to small range) conversions lose information above the magnitude of the value being converted. They are not allowed in assignments. In the above example., the value after the decimal place is lost.

Variables

  Variables are the basic unit of storage in a Java program. A variable is define by a combination of an identifier, a type, and an optional initialize. In addition, all variables have a scope, which define their visibility and a lifetime.



Declaring a Variable:

                                    Type  identifier=value; 



Dynamic Intialization: Java allows variables to be initialized dynamically, using an expresion valid at the time the variable is declared.

                                    E.g: double c=(a+b)*d;



Methods in Classes

  A method is define as an actual implementation of an operation on an object. It can also be define as a specification of the manner in which the requested operation is to be carried out.

  The syntax of defining or declaring a method is:



access-specifier  modifier  datatype method_name(parameters_list)



Access Specifier: Limits access to the method. In Java there are three access specifier i.e. public, protected, and private.

Modifier: Allow programmer to assign properties to the method.

Datatype: datatype of the value that the methods returns. If no value is being returned, the datatype should be void.

Method_name: it is the name of method.

Parameters_list: Contain the name of parameters that are passed to the method, and its datatype.



Methods Modifiers

  Static: A static method can be accessed without creating an instance of the class. It can used only static data and methods.

  Abstract: An abstract method does not have code, and has to be implemented in the subclass. These types of methods are useful in inheritance.

  Final: States that the method can not be inherited or overridden.

  native - If a method is declared native it specifies that the method implementation is written in some "native" language such as C or C++

  synchronized - This is used for multithreaded applications. Its permits only one thread access to a block of code at a time.



Example of static methods:

  public class MethodExample{

    int i;

    static int j;

    public static void staticMethod(){

      System.out.println("you can access a static method this way");

    }

    public void nonStaticMethod(){

      i=100;

      j=1000;

      System.out.println("Don't try to access a non static method");

    }

    public static void main(String[] args) {

      j=1000;

      staticMethod();

    }

  }

Operators in Java



         Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:



Arithmetic Operators


<><></><><></><><><>   <></><><></><><><>   <></><><><>   <></><><><> <></> <><><>  <> </> <><><>   <></><><><>   <></><><><>  <></> <><><>  <> </> <><><>   <></><><><>   <></><><><> <></> <><><>  </> <><><>  <></><><><>   <></><><><>  <></> <><><>  <> </> <><><>   <></><><><>   <></><><><> <></> <><><>  <> </> <><><>   <></><><><>   <></><><><>  <></><><><>   <></><><><> <></><><><>  <></> <><><> <></>

Operator

Description

+

Addition - Adds values on either side of the operator

-

Subtraction - Subtracts right hand operand from left hand operand

*

Multiplication - Multiplies values on either side of the operator

/

Division - Divides left hand operand by right hand operand

%

Modulus - Divides left hand operand by right hand operand and returns remainder

++

Increment - Increase the value of operand by 1

--

Decrement - Decrease the value of operand by 1
  The Relational Operators 
<><></><><></><><></><><></><><></><><></><><><> <></><><></><><></><><></><><></><><></><><></><><></><><></><><></><><></><><></><><></><><></><><></> <><></>

Operator

Description

==

Checks if the value of two operands are equal or not, if yes then condition becomes true.

!=

Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
 


The Logical Operators



<><><><><><> </><><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </>

Operator

Description

&&

Called Logical AND operator. If both the operands are non zero then then condition becomes true.

||

Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

<><></><><></><><></><><></> <><></>
^
Logical XOR: return true if one value is true and other is false.



The Assignment Operators

<><><><><><> </><><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </>

Operator

Description

=

Simple assignment operator

+=

Add and Assignment Operator

-=

Subtraction  and Assignment Operator

*=

Multiply and Assignment Operator

/=

Division and Assignment Operator

%=

Module and Assignment Operator



The Bitwise Operators

<><><><><><> </><><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </>

Operator

Description

~

Bitwise NOT

&

Bitwise  AND

|

Bitwise  OR

^

Bitwise  XOR

>>

Shift right

<<

Shift Left



Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as :

                        variable x = (expression) ? value if true : value if false

Following is the example:      

                        public class Test { public static void main(String args[])

{

int a , b;

a = 10;

b = (a == 1) ? 20: 30;

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

b = (a == 10) ? 20: 30;

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

} }



Operator Precedence

The expression that you write will generally consists of several operators. The rules of precedence decide the order in which each operator is evaluted in such expression. The table below lists the order in which operators are evaluated in Java.

<><><><><><> </><><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </> <><><><><><> </><><><><><><> </><><><><><><> </> <><><><><><> </>

Order

Operator

1

Unary operator like ++ and --

2

Arithmetic and shift operators like *, /, +, <<, >>

3

Relational operators like >, <, >=, <=, ==, !=

4

Logical and Bitwise operators

5

Assignment Operators like =, *=, /=, += -=



Switch-case statement

         The switch-case statement can be used in place of the if-else statement. It is used in situations where the expression being evaluated results in multiple values.

         Syntax:

Switch(expression)

{

Case ‘value1’: action1 statement;break;

Case ‘value2’: action2 statement;break;

Case ‘valueN’: actionN statement;break;

default:

Default_action statement;

}

Example:





While loop

         While loops are used when a loop is to be executed as long as a certain condition is True. The number of times a loop executed is not predetermined, but depends on the condition.

         Syntax: while(condition)

                        {

                                    action statement;

                                    :

                                    :

                        }

Example: class WhileDemo

                        {  int a=5, fact=1;

                           while(a>=1)

                        {

                                    fact*=a;

                                    a--;;

                        }

                                    System.out.println(“The Factorial of 5 is ”+fact);

                        }



Do-while loop

         The do-while loop execute certain statements till the specified condition is True. These loops are similar to the while loops, except that a do-while executes atleast once, even if the specified condition is False.

         Syntax:

                        do{

                        action statement;

                        }while(condition)



For Loop

All loops have some common features: a counter variable that is initialized before the loop begins, a condition that tests the counter variable, and a statement that modify the value of counter variable. The for loop provides a compact format for incorporating these features.

Synatx:

                        for(initialization statement; conditional statement; increament/decreament)

                        {

                                    action statement(s);

                        }



Class Constructors



Ø  A constructor is a special method that is very different from the basic method types.

Ø  A constructor executes as a normal method or function, but it cannot return any value.

Ø  It is generally used to initialize the member variables of class, and is called whenever an object of the class is create.

Ø  Constructor has the same name as class name.

Ø  In Java, constructors are of two types:

  Implicit constructor: when programmer do not define a constructor for a class, the JVM provides a default constructor. This default constructor is called implicit constructor. Default constructor is a nothing doing constructor with no arguments.

  Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.

  So, for example, if you have a class B that has a constructor “B (int n)”, you cannot create a object of B by “new B()” because you didn't define it and Java didn't create it automatically. It is a compilation error.



Explicit constructors

Those constructor which are define by programmer in the class definition. While creating an object of class, the values that you pass and the parameters of constructor should match, in terms of number, sequence, and data type.

There can be more than one explicit constructors in a class, distinguished by their parameters. When the class is initialized, Java will call the right constructor with matching arguments and type.



Examples

// a class with 3 constructors, differing by their parameters

class t2 {

t2 () {

System.out.println("empty arg called!");}

t2 (int n) {

System.out.println("int one called!");}

t2 (double n) {

System.out.println("double one called!");}

             }



class t1 {

public static void main(String[] arg) {

// creating 3 objects of t2.

// when each object are created, Java automatically calls the right constructor

t2 x = new t2();

t2 y = new t2(3);

 t2 z = new t2(3.0); }

 }



While in explicit constructors, the first line of a constructor must either be a call on another constructor in the same class (using this keyword), or a call on the superclass constructor (using super keyword).

ž  this(...) - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.

ž  super(...). Use super to call a constructor in a parent class. Calling the constructor for the superclass must be the first statement in the body of a constructor.



Call constructor and fields using this keyword

class A


  int a,b;

      A(int x, int y)

      {

      a=x;

      b=y;

              System.out.println(“Constructor with arguments”);

      System.out.println(a+b);

      }

     

A()

      {

      this(10,3);

      System.out.println("Contructor with no arguments");

              System.out.println(this.a);

      }

}



public class B

{

  public static void main(String args[])

  {

      A a=new A();

  }

}
                             

                                    Lecture 08
Reference Data Types

žIn Java, a reference data type is a variable that can contain the reference or an address of dynamically created object. These type of data type are not predefined like primitive data type.The reference datatypes are arraysclasses and interfaces.
Array Type:


žAn array is a special kind of object that contains values called elements. The java array enables the user to store the values of the same type in contiguous memory allocations. The elements in an array are identified by an integer index which initially starts from and ends with  one less than number of elements available in the array. 
žIt is a reference data type because the class named as Array  implicitly extends java.lang.Object.
Declaring Array Variables
 To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference.
Here is the syntax for declaring an array variable
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays:
žAfter declared, create an array by using the new operator with the following syntax:
 arrayRefVar = new dataType[arraySize];
 OR
žDeclaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

             int [] a = new int [10];
In the above statement, an array variable "a" is declared of  integer data type that holds the memory spaces according to the size of int. The index of the array starts from a[0] and ends with a[9]. Thus, the integer value can be assigned for each or aparticular index position of the array. 
Alternatively you can create arrays as follows:
String [] b = {"reference","data", "type"};
In this statement,  the array "b" is declared of string data type that has the enough memory spaces to directly holds the three string values.  Thus each value is assigned for each index position of the array. 
 dataType[]   arrayRefVar = new dataType[arraySize];

int[]  arr =new int[100];
Processing Arrays:
žWhen processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

žpublic class TestArray {
public static void main(String[] args) {
ždouble[] myList = {1.9, 2.9, 3.4, 3.5};
ž// Print all the array elements
žfor (int i = 0; i < myList.length; i++) {
žSystem.out.println(myList[i] + " "); }
ž// Summing all elements
ždouble total = 0; for (int i = 0; i < myList.length; i++) {
žtotal += myList[i]; }
žSystem.out.println("Total is " + total);
ž// Finding the largest element
ždouble max = myList[0];
žfor (int i = 1; i < myList.length; i++) {
žif (myList[i] > max)
žmax = myList[i];
ž}
žSystem.out.println("Max is " + max);
ž} }
The foreach Loops
žJDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop.žThis is mainly used for Arrays. This loop enables us to traverse the complete array sequentially without using an index variable.

žExample:
žThe following code displays all the elements in the array myList:
žpublic class TestArray
{
ž public static void main(String[] args)
ž{
ž double[] myList = {1.9, 2.9, 3.4, 3.5};
ž// Print all the array elements
žfor (double element: myList)
ž{
ž System.out.println(element);
ž}
ž }
ž}
The break Keyword:

žThe break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
žThe break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.
žExample:
žpublic class Test {
žpublic static void main(String args[]){
žint [] numbers = {10, 20, 30, 40, 50};
žfor(int x : numbers ){
žif( x == 30 )
ž{ break; }
žSystem.out.print( x );
žSystem.out.print("\n");
ž}
ž } }
The continue Keyword:

žThe continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
žIn a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
žIn a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
žExample:
žpublic class Test {
žpublic static void main(String args[]){
žint [] numbers = {10, 20, 30, 40, 50};
žfor(int x : numbers ){
žif( x == 30 )
ž{ continue; }
žSystem.out.print( x );
žSystem.out.print("\n");
ž}
} }


  1. INHERITANCE

Inheritance is one of the conerstones of object oriented programming because it allows the creation of hierarchical classification.

Inheritance permits a class to share the attributes, and operations define in one or more classes. This class can then be inherited by other, more specific classes.

In the terminology of Java, a class that is inherited is called super class. The class that does the inheriting is called subclass.

INHERITANCE BASICS: To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. 
Example: //A Simple example of inheritance
//create a super class
class A
{
   int i,j;
   void showA()

   { System.out.println("i and j"+i+" "+j);}
}
//create a sub class by extending class A
class B extends A
{
  int k;
  void showB()
  {
    System.out.println("k: "+k);}

  void sum()
  {
    System.out.println("i+j+k= "+(i+j+k));}
 }

class simpleinheritance
{
    public static void main(String args[])
   {
       A obj1=new A();
       B obj2=new B();

    // The super class may be used by itself
   obj1.i=10;
   obj1.j=20;
   System.out.println("Variables of super class: ");
   obj1.showA();

// The subclass has access to public members of its super class
   obj2.i=7;
   obj2.j=8;
   obj2.k=9;
   System.out.println()"Contents of subobject: ");
   obj2.showA();
   obj2.showB();
   obj2.sum();
}}

MEMBER ACCESS AND INHERITANCE
Although a subclass includes all of the members os its superclass, it connot access those members that have been declared as private:

Example:
class A
{
   int i;  //by default public
private int j;
void setij(int x, int y)
{
    i=x;j=y;}
}
class B extends A
{
   int total;
   void sum()
  { total=i+j;}
}
class Access
{
   public static void main(String s[])
   {
    B obj=new B();
  obj.setij(10,12);
  obj.sum();
  System.out.println("Total = "+obj.total);
}}

Remember:  A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.

USING SUPER KEYWORD
USING SUPER KEYWORD TO CALL SUPER CLASS CONSTRUCTORS
class A
{
 int x;
  float y;
 A(int a, float b)
 {
   x=a;
   y=b;
   System.out.println("Class A Constructor"); 
   System.out.println(x+" "+y);
 }}
class B extends A
{  B()
   {
   super(9,5.6f); 
   System.out.println("B class Constructor");
 }}
class constuctorsExp
{
  public static void main(String args[])
  {   B b=new B();
  }}

USING SUPER KEYWORD TO CALL SUPER CLASS MEMBERS
public class Superclass
{
public void printMethod()
{
System.out.println("Printed in Superclass."); } }
//Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass { 

public void printMethod() { 
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}

Multilevel Hierarchy: Up to this point, we have been using hierarchies that consist of only a super class and a sub class. However, we can built hierarchies that contain as many layers of inheritance as we like. For example, given three classes called A, B and C, C can be the sub class of B, which is sub class of A. When this type of situation occurs, each sub class inherits all the traits found in all of its superclasses. In this case, C inherits all the aspects of B and A. To see how a multi-level hierarchy is useful, consider the following example:

class A
{
                char ch='A';
                void Alphabets()
                {  while(ch!=91)
                   {
                                System.out.print("\t"+ch);
                                ch++;
                   }
                }
}

class B extends A
{  char ch1='a';
  void Smallabc()
  {
                System.out.println("\n");
                while(ch1!=123)
                {             
         System.out.print("\t"+ch1);
                   ch1++;
                }}
}
class C extends B
{
                char ch2='[';
                void Characters()   
                {
                System.out.println("\n");
                while(ch2!=97)
                {             
                                System.out.print("\t"+ch2);
                                ch2++;
                }             
                }}

class Multilevel
{
  public static void main(String a[])
  {
     C obj=new C();
     obj.Alphabets();
     obj.Smallabc();
     obj.Characters();
   }}

When Constructors are Called?
When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy called? The answers is that in a class hierarchy, constructors are called in order of derivation, from super class to sub class. If there is no explicit constructors in any class, then the default or parameter less constructors of each super class are executed. The following program illustrates when constructors are executed.
Example:
Class A {
     A() {
         System.out.println(“Inside A’s constructors”);
       }
}
Class B extends A {
   B() {
      System.out.println(“Inside B’s constructors”);
       }
}
Class C extends B {
   B() {
      System.out.println(“Inside C’s constructors”); 
       }
}
Class CallingConst{
  Public static void main(String a[])
  {
     C obj=new C();
  }
}


 

Method Overriding with examples:  Done in Lecture 05

1) Why Overridden Methods?
2) In Java, is there any procedure to prevent methods from overridden and inheritance.  Describe with suitable examples.
3) How JVM works? Explain in step by step form.