Creating Objects

Creating Objects


                 Creating objects means to allocate memory space for all the instance variables of the objects. Step to create an object are,

1. Declare an object.
2. Define the object using new operator. The new operator dynamically allocates memory for an object and returns a reference to it.
The general form is
1. Declare an object.
2. Define the object using new operator. The new operator dynamically allocates memory for an object and returns a reference to it.


The general form is

classname obj;
obj=new classname();

Where
                classname           -              defined classname
                obj                         -              name of the object
                new                       -              keyword

Example

Student s1;  //this declares an object s1 of type student.
S1=new Student(); //this allocates memory space for object s1.
                 
The following figure shows the representation of student object in the memory.

Statement                                           Effect
Student s1;                                         s1
S1=new Student();                          

                The above two steps can be combined into one step as,
                Student s1=new Student();

Creating and Executing Java Program

Creating and Executing Java Program

     The following steps are follwed to create and execute a java program.


1 . Create the program using any text editor such as notepad or word pad etc. The general form for saving the created program in a  file is
                                                    
                                               filename.java
                       Where,  
                                     filename - Name of the class containing the main method
                                     java         - Keyword
     Ths file is called source file. If the program has more than one class, the file name must be the name of the main class.

 

Example
                                class Sample   // main class
                                { 
                                         public static void main(String args[])
                                         {
                                                 -------------------------
                                                 -------------------------
                                          }
                                  }
               Store this program as Sample.java

2 . Compile the created programs using java compiler. The general form of compile command is
                                                       
                                                      javac sourcefilename.java
                                 Where,
                                               javac                  - name of the java compiler
                                              sourcefilename - name of the already created source file.
   
     Java compiler creates a file called class file which cotains platform independent bytecodes of the program. The compiler automatically names the class file. The general form is
              
                                                      classname.class
                                   Where,
                                                classname - name of the main method class in our program
                                                class           - keyword

Example
                 Name of our source file - Sample.java
                 Compilation command   - javac Sample.java

          This create a class file as Sample.class

3 . Run the compiled program using java interpreter. The general form of run command is

                                                     java classname
                                    Where,
                                                 java           - name of the java interpreter
                                                classname - name of the main method class in our program

      Java Interpreter produces machine code from the bytecode and run the program.

Example
                 Name of our source file - Sample.java
                 Name of class file           - Sample.class

     To run the program give the run command at the command prompt as

                                                   c>java Sample

Java Virtual Machine

Java Virtual Machine

      Java compiler compiles the source code and produces a machine independent intermediate code called bytecode. This  code cannot be used dirctly by the computer. This intermediate codes are called java virtual machine (JVM).
      These intermediate codes can be used by any machine with the help of the correct interpreter. The interpreter produces the machine dependent code called machine code can be run by the computer.
       
--->sourcecode--->java compiler--->bytecode--->javainterpreter--->machinecode

     This shows the steps involved in executing a java pragram.

Charcteristics of Java Program

Charcteristics of Java Program

The following are the important characteristics of java program. They are

1 . Simple, small and familiar
2 . Object oriented
3 . Distributed
4 . Robust
5 . Secure
6 . Architecture neutral or platform independent
7 . Portable
8 . Compiled and interpreted
9 . High performance
10 . Multithreaded and interactive
11 . Dynamic and extensible

1 . SIMPLE, SMALL AND FAMILIAR
            Java is a simple small language. The syntax of java is just like C++ language. So it is very easy to learn. But programming in java is easier than C++ because
·         It does not use header files
·         It eliminates the use of pointers
·         It eliminates operator overloading and virtual base classes.
So java is a simple small object oriented language. Since java is a small language so we can write software that can run in small computers.

2 . OBJECT ORIENTED
            Java is a pure object oriented language. Everything in java is an object. All programs and data reside inside objects and classes. Object models in java is simple and easy to extend.

3 . DISTRIBUTED
            Java has strong networking facilities. So using java we can create applications on networks. Using java we can open and use the applications on the internet. This facility helps the users from different places to work together on a single application.

4 . ROBUST
            In many other languages attention is not given on memory management or exceptional behavior of a program in different situation. So most programs failed. But these issues are clearly dealt in java using the techniques called garbage collection and exception handling.
            In garbage collection java uses a thread to free the objects which are not in use. So the programmers do not have to worry about the memory management. In exception handling java uses exclusively written codes to correct the exception situation.

5 . SECURE
            Since java is used for programming on internet, security becomes an important issue. Before a java code from internet is interpreted, a security check is applied on it. This ensures that the java code does not contain any unwanted elements like viruses. Java has a facility to sign our java code before sending it. At the receiving end the receiver can tally the signature. If the signature matches, the codes reached correctly. If does not match the codes are not correct. This concept is called digitally signing.

6 . ARCHITECTURE NEUTRAL OR PLATFORM INDEPENDENT
            Java compiler generates an architecture neutral or platform independent code called byte code. These codes can be run in any type of system. The figure given below shows this.

                     source code --> java compiler --> byte code           

7 . PORTABLE
            Java compiler generates a code called byte code and this code can be used by any machine. In java the size of the primitive data types are machine independent. So java is a portable language.

8 . COMPILED AND INTERPRETED
            Generally computer languages are either compiled or interpreted. But java combines both compiler and interpreter. So java is a two stage as shown below.
  
source code --> compiler --> byte code --> interpreter --> machine code
        
         Java compiler generates a machine independent code called byte code. These codes are not machine code. But java interpreter generates machine code from byte code that can be directly executed by the machine that is running the java program.

9 . HIGH PERFORMANCE
            Since java interpreter uses byte codes, the performance is high. The speed is also comparable to other languages lake C, C++.

10 . MULTITHREADED AND INTERACTIVE
            Multithreaded means handling more than one job at a time. Java supports multithreading.  Java also supports constructing interactive programs.

11 . DYNAMIC AND EXTENSIBLE
            Java is a dynamic language. So it is capable of linking dynamically new classes, methods and objects. Java also supports functions written in other languages such as C and C++. These functions are called native methods. During run time native methods can be linked dynamically.

Introduction to Java

Introduction to Java



     Java is a platform independent object oriented language. It was developed by James Gosling and Patrick Naughton of Sun Microsystems, USA in 1991. 

     It was the first programming language which was not dependent on any particular hardware or operating system. It was initially named as Oak and later renamed as Java in 1995. 

      Java language is to nest suited for developing web based applications.

Getting Values of Variables

Getting Values of Variables



 The values of the variable are displayed on the VUD by using the following two methods

                     i.            Print ( )
                   ii.            Println ( )

Print ( ) method prints the output on a line until a newline character is encountered.

Println ( ) method prints the output on a line and the control comes to the new line.

The above two methods are invoked by using the object systems. Out as shown below.


                                                        System.out.print  ( );
                                                        System.out.println ( );

Example:

System.out.print (“Good”)
System.out.print (“Luck”)

The output is 
                       Good Luck

System.out.println (“Good”)
System.out.println (“Luck”)

The output is 
                    Good
                     Luck

System.out.print (“Good\n”)
System.out.print (“Luck”)

The output is 
                         Good
                         Luck

Java variables:

A variables refers to the name given to the memory location to store data. A particular memory location is given only one name. yet this name is called a variable because this memory location can store sequence of different values during the execution of the same program.

Rules:
1. A variable name is formed with alphabets, digits, underscore( _ ), dollar sign.

2 . The first character must be an alphabet.


3 . Variable name can be of any length.


4 . Both upper case and lower case letters are used. But they are not treated as same.


5 . It should not be a keyword word.

Example:
1.       The following are some valid variable names.

AO          BASIC_PAY         volume                 B12

2.       The following are some invalid variable names.

Variable
Reason for invalidity
AB
9A
While
Period ( ) not allowed
The first character should be an alphabet
Reserved word

Declarations of Variables

Declarations of Variables

     All variables present in the problem must be declared before it is used. This is done with the help of declaration statement. The general form is

Data-type variable list;
                       Where,
                                  Data-type            -              valid data type such as int, char etc.
                                  Variable unit        -              list of variable separated by comma.


Example:              
               
          Int  a, b, c;
This declares a, b and c as integer variables and allocate memory space.

Use of declaration:

i.                     It gives name to memory location
ii.                   It allocates memory space
iii.                  It gives the types of data

Giving Values to variables:
               
        Giving values to already declared variables is called assigning values to variables.  this is done with the help of assignment operator (=). The general form is

Variable name  =             value;

Example:

1.                   X     =             20;
2.                   PI    =             3.14;

Initializing variable:
The process of assigning initial values to variables is called initializing variables. This is done at the time of declaration. the general form is

Data-type variable = initial value;

Example:
1.       Int  a11                 =             100;
2.       Char sex               =             ‘F’;
3.       Double pay         =             80.32;
4.       Int a, b                  =             20;

Program to get IP address in java

Program to get IP address in java

    getLocalHost() function is used to display Name and IP address of local system.
    getByName(" ") function is used to display Name and IP address of a given website.
    getAllByName() function is used to display more than one IP address of  a given website. 

import java.net.*;
public class Main{

    public Main(){
    }
    
    public static void main(String[] args) {
    try
    {    
     InetAddress add= InetAddress.getLocalHost();


     System.out.println("LOCAL HOST NAME & IP ADDRESS: "+add);
     InetAddress add1=InetAddress.getByName("facebook.com");
     System.out.println("NAME AND IP ADDRESS OF THE STRING: "+add1);
     InetAddress ias[]=InetAddress.getAllByName("google.com");
     for(int i=0;i<ias.length;i++)
     {
         System.out.println(ias[i]);
     }
     String s=add.getHostName();
     System.out.println("NAME OF THE HOST: "+s);
     String s1=add.getHostAddress();
     System.out.println("ADDRESS OF HOST: "+s1);
     byte[] a=add.getAddress();
     for(int j=0;j<a.length;j++)
     {
     System.out.println(a[j]);
    }
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
}
}

Output:
LOCAL HOST NAME & IP ADDRESS: nw1-120/165.165.1.120
NAME AND IP ADDRESS OF THE STRING: facebook.com/69.63.189.11
google.com/74.125.236.50
google.com/74.125.236.49
google.com/74.125.236.52
google.com/74.125.236.51
google.com/74.125.236.48
NAME OF THE HOST: nw1-120
ADDRESS OF HOST: 165.165.1.120
-91
-91
1
120
BUILD SUCCESSFUL (total time: 0 seconds) 

Program for Display Alphabets & Sorted Numbers in Java

Program for Display Alphabets & Sorted Numbers in Java

import java.io.*;
class Alpha
{
    public static void main(String args[])
    {
        String s[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int n=s.length;
        for(int i=0;i<n;i++)
        {
            System.out.print(s[i]);
        }
        int s1[]={1,54,26,8,32,65};
        int n1=s1.length;

       
        System.out.println(" ");
System.out.println("Sorted Numbers: ");
        for(int i=0;i<n1;i++)
        {
            for(int j=i+1;j<n1;j++)
            {
                if(s1[i] > s1[j])
                {
                    int temp=s1[i];
                    s1[i]=s1[j];
                    s1[j]=temp;
                }
            }
        }
        for(int i=0;i<n1;i++)
        {
            System.out.println(" "+s1[i]);
        }
    }
}

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ 

Sorted Numbers:

1 8 26 32 54 65

Program for Gallons to Liter Conversion in java

Program for Gallons to Liter Conversion in java

import java.io.*;
class Conversion
{
    public static void main(String args[])
    {
        double ans;
        for(int i=1;i<=20;i++)
        {
            ans=i*3.84;


            System.out.println(+i+" Gallons = "+ans+"Litres");
        }
    }
}

Output
1 Gallons = 3.84Litres
2 Gallons = 7.68Litres
3 Gallons = 11.52Litres
4 Gallons = 15.36Litres
5 Gallons = 19.2Litres
6 Gallons = 23.04Litres
7 Gallons = 26.88Litres
8 Gallons = 30.72Litres
9 Gallons = 34.56Litres
10 Gallons = 38.4Litres
11 Gallons = 42.239999999999995Litres
12 Gallons = 46.08Litres
13 Gallons = 49.92Litres
14 Gallons = 53.76Litres
15 Gallons = 57.599999999999994Litres
16 Gallons = 61.44Litres
17 Gallons = 65.28Litres
18 Gallons = 69.12Litres
19 Gallons = 72.96Litres
20 Gallons = 76.8Litres

Program for Escape Sequence in Java

Program for Escape Sequence in Java

import java.io.*;
class Escape
{
    public static void main(String args[])
    {
        System.out.println("P    Q    P&Q    P|Q      P^Q");
        int i,x,y,z;
        int p[]={0,0,1,1};
        int q[]={0,1,0,1};
        for(i=0;i<4;i++)


        {
            x=p[i]&q[i];
            y=p[i]|q[i];
            z=p[i]^q[i];
            System.out.println(+p[i]+"    "+q[i]+"    "+x+"        "+y+"       "+z );
           
        }
       
    }
}

Output

P    Q    P&Q    P|Q      P^Q
0    0         0        0       0
0    1         0        1       1
1    0         0        1       1
1    1         1        1       0

Program for Type Conversion in Java

Program for Type Conversion in Java

import java.io.*;
class Typeconversion
{
    public static void main(String args[])
    {
        double i;
        float sum1=0.0f,sum=0.0f;
        for(i=1;i<=20;i++)
        {
            sum1=(float)i;
            sum+=(1/sum1);

          
        }
        i--;
        System.out.println("I = "+i+"numbers");
       
        System.out.println("Sum of (1/I) = "+sum);

    }
}

Output

I = 20.0numbers

Sum of (1/I) = 3.5977397

Program to Implement Library Funtions in Java

Program to Implement Library Funtions in Java


import java.io.*;
import java.math.*;
class three
{
                public static void main(String args[])
                {
                                System.out.println("Square Root of 44 is "+Math.sqrt(44));
                                System.out.println("Sin of 90 is "+Math.sin(90));
                                System.out.println("Cos of 0 is "+Math.cos(0));
                                System.out.println("Tan of 45 is "+Math.tan(45));

                                System.out.println("Absolute value of 78 is "+Math.abs(78));
                                System.out.println("MaXimamum of 60 and 77 is "+Math.max(60,77));
                                System.out.println("Mininmum of 89 and 22 is "+Math.min(89,22));
                                System.out.println("Log of 65 is "+Math.log(66));
                                System.out.println("Floor of 43.89 is "+Math.floor(43.89));
                                System.out.println("Ceil of 456.77 is "+Math.ceil(456.77));
                }
}



Output:

Square Root of 44 is 6.6332495807108
Sin of 90 is 0.8939966636005579
Cos of 0 is 1.0
Tan of 45 is 1.6197751905438615
Absolute value of 78 is 78
MaXimamum of 60 and 77 is 77
Mininmum of 89 and 22 is 22
Log of 65 is 4.189654742026425
Floor of 43.89 is 43.0
Ceil of 456.77 is 457.0

Program to Implement Number Pattern in Java

Program to Implement Number Pattern in Java

class Pattern
{
                public static void main(String args[])
                {
                                int twod[][]=new int[4][];
                                twod[0]=new int[1];
                                twod[1]=new int[2];
                                twod[2]=new int[3];
                                twod[3]=new int[4];

                                int i,j,k=0;
                                for(i=0;i<4;i++)
                                {
                                                for(j=0;j<i+1;j++)
                                                {
                                                                twod[i][j]=k;
                                                                k++;
                                                }
                                }
                                for(i=0;i<4;i++)
                                {
                                                for(j=0;j<i+1;j++)
                                                {
                                                                System.out.print(twod[i][j] + " ");
                                                }
                                                System.out.println();
                                }
                               
                }
}


Output:
0
1 2
3 4 5
6 7 8 9

Program to Identify Protocol, Host, File, Path of a URL in Java

Program to Identify Protocol, Host, File, Path of a URL in Java

     The getProtocol() function is used to return a protocol which is accessing a given URL.
     The getHost() function is used to display the Host name of a given URL.
     The getPort() function is used to display a  Port number.
     The getFile() function is used to display the File name which is present given URL. 
     The getQuery() function is used to display the content which is present after question mark (?) of a given URL.

import java.net.*;
public class Main {
   
    public Main() {
    }
   
    public static void main(String[] args) {
    try
    {      
        URL a=new URL("http://www.google.com?hello%2osachin%20");


        URL a1=new URL("http://www.google.com/adsense");
        String str=a.getProtocol();
        System.out.println("The Protocol is: "+str);
        String str1=a.getHost();
        System.out.println("The Host is: "+str1);
        String str2=a1.getFile();
        System.out.println("The File is: "+str2);
        String str3=a.getQuery();
        System.out.println("The Query is: "+str3);
        String str4=a1.getPath();
        System.out.println("The Path is: "+str4);
        String str5=a1.getRef();
        System.out.println("The Reference is: "+str5);
        int n=a.getPort();
        System.out.println("The Port Number is: "+n);
    }
    catch(Exception e)
    {
    System.out.println(e);}}
   
}

Output

The Protocol is: http
The Host is: www.google.com
The File is: /adsense
The Query is: hello%2osachin%20
The Path is: /adsense
The Reference is: null
The Port Number is: -1
BUILD SUCCESSFUL (total time: 0 seconds)

Program to know the HTML content of a Website in Java

Program to know the HTML content of a Website in Java

   This is the program to display or retrive the HTML content of a URL or Website. In the URL object 'a' is used to pass the URL name or address as argument to URL class. By using the BufferedReader and InputStreamReader the HTML content is retrived . openStream() is used open the given URL.

import java.io.*;
import java.net.*;
public class Main {
   
        public Main() {
    }
   
    public static void main(String[] args) {
        try{
            String obj;
            URL a=new URL("http://165.165.80.80");

            BufferedReader b=new BufferedReader(new InputStreamReader(a.openStream()));
            while((obj=b.readLine())!=null)
            {
                System.out.println(obj);
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
   
}
Output

<html>
<head>
<title>&lt;----- SKCET Library -----&gt;</title><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css">
<!--
body {
        background-color: #9CAFD1;
        margin-left: 0px;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 0px;
}
-->
</style>

<link href="_img/Style.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
.style4 {
        font-family: "Times New Roman", Times, serif;
        font-weight: bold;
        color: #003366;
        font-size: 14px;
}
.style5 {
        font-size: 12px;
        color: #003366;
}

Creating Objects

Creating Objects                  Creating objects means to allocate memory space for all the instance variables of the objects. S...