Single Post

Header

Monday, December 21, 2015

Simple Java Programs

Simple Java Programs Covering Many Basic Concepts :

1.JavaPractise.java

package JavaBasics;

public class JavaPractise {

   
    public static void main(String[] args)
    {
        // Switch and Do While
        int a=20;
        switch(a)
        {
        case 19: System.out.println("This is 19");
                 break;
        case 20: case 21: System.out.println("This is 20 ");
                 break;
        default : System.out.println("This is default");
        }
      
        do {
            System.out.println("welcome to do while");
            a++;
        } while(a<23);
       
        // Arrays Examples
        int[] arr={23,34,45,55};
        System.out.println(arr[3]);
        String[] str={"india","welcome","java"};
        System.out.println(str[0]);
        int arr1[]=new int[4];
        arr1[2]=22;
        System.out.println(arr1[2]+ " " + arr1[0]);
        String[] s=new String[6];
        s[1]="java";
        System.out.println(s[1]+" "+s[0]);
       
       
    }

}

Output:

This is 20
welcome to do while
welcome to do while
welcome to do while
55
india
22 0
java null

2.StringClass.java

package JavaBasics;

public class StringClass {

   
    public static void main(String[] args)
    {
        char ch='a'; char ch1='c';
        int index,index1,index2;
        String str="Welcome";
        String str2="me";
        index=str.indexOf('a');
        index1=str.indexOf('c');
        index2=str.indexOf(str2);
        System.out.println(str.toUpperCase());
        System.out.println("the not found index is "+index);
        System.out.println("the char index is "+index1);
        System.out.println("the string index is "+index2);
       
       
        String dot=".com";
        String email="meme@me.com";
        if(email.endsWith(dot))
            {
            System.out.println("Valid email address");
            }
       String sub=email.substring(5,7);
       System.out.println(sub);
     //  int x=23; int y=34;
       String s1="abcd";
       String s2="Abcd";
       if(s1.equals(s2))
       {
           System.out.println("both are equal");
            
       }
       if(s1.contains("ab"))
       {
           System.out.println("the given sub string is present");
       }
       char c1=s1.charAt(0);
       System.out.println(c1);
      
       String trim="   Welcome to Java  ";
       System.out.println(trim);
       String aftertrim=trim.trim();
       System.out.println(aftertrim);
       String replace=trim.replace("Java","C++");
       System.out.println(replace);
      
         
    }

}

Output:

WELCOME
the not found index is -1
the char index is 3
the string index is 5
Valid email address
me
the given sub string is present
a
   Welcome to Java 
Welcome to Java
   Welcome to C++ 


3.StaticPublic.java

package JavaBasics;

public class StaticPublic {

    static int a=5;
    int b;
    int c=5;
    StaticPublic()
    {
        a++;
        System.out.println(a);
    }
    static {
        System.out.println("This will execute before the main method");
    }
    static int myMethod()
    {
           return ++a;
    }
   
      public static void main(String[] args)
    {
         StaticPublic obj=new StaticPublic();
    //      System.out.println(b);  Static method can not use non static members directly
          System.out.println("does this execute "+a+" and "+obj.b+obj.c);
          System.out.println("test"+a+obj.c+"test");
          System.out.println(a+obj.c);
          StaticPublic obj1=new StaticPublic();
          StaticPublic obj2=new StaticPublic();
          int r= StaticPublic.myMethod();
          System.out.println("Static method return value "+r);
         
    }

}

Output:
This will execute before the main method
6
does this execute 6 and 05
test65test
11
7
8
Static method return value 9

4.Broom.java

package JavaBasics;

class Cover

{
         static class InnerCover
             {
              void go()
                  {
                       System.out.println("I am the first Static Inner Class");
                  }
            }
 }

class Broom

{
         static class InnerBroom
        {
                  void go1()
                   {
                         System.out.println("I am second Static Inner Class");
                    }
         }

         public static void main(String[] args)
         {

            // You have to use the names of both the classes

            Cover.InnerCover demo = new Cover.InnerCover();

            demo.go();

           // Here we are accessing the enclosed class

            InnerBroom innerBroom = new InnerBroom ();

            innerBroom .go1();

          }
}


Output:

I am the first Static Inner Class
I am second Static Inner Class

5.ArrayListCollections.java

package JavaBasics;
import java.util.*;
public class ArrayListCollections {

  // use an ArrayList when you're not sure how many elements are going to be in a list of items.
    public static void main(String[] args)
    {
        ArrayList ls=new ArrayList();
        ls.add("book");
        ls.add("pen");
        ls.add("pc");
        // To go through each item in your ArrayList you can set up something called an Iterator.
        // This class can also be found in the java.util library
        Iterator ir=ls.iterator();
        while(ir.hasNext())
        {
            System.out.println(ir.next());
        }
        System.out.println("whole list is: "+ls);
        ls.remove(1);
        System.out.println("whole list is: "+ls);
        ls.remove("book");
        System.out.println("whole list is: "+ls);
        System.out.println("Single item is: "+ls.get(0));
    }

}

Output:

book
pen
pc
whole list is: [book, pen, pc]
whole list is: [book, pc]
whole list is: [pc]
Single item is: pc

6.InheritanceOverriding.java

package JavaBasics;

class A
{
    int x;
    public void method(int a)
    {
        System.out.println("This is in class A"+a);
    }
    public void sample()
    {
        System.out.println("This is sample method");
    }
}
class B extends A
{
    public void method(int b)
    {  
        x=6;
        System.out.println("This is in class B "+b+ "and x is "+x);
    }
}

public class InheritanceOverriding
{

    public static void main(String[] args)
    {
        B obj=new B();
       
        obj.method(8);
        obj.sample();
    }

}

Output:

This is in class B 8and x is 6
This is sample method

7.ReadTextFile.java

package JavaBasics;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.*;

public class ReadTextFile
{

    public int nooflines() throws IOException
    {
        FileReader fr=new FileReader("D:\\sample.txt");
        BufferedReader br=new BufferedReader(fr);
        String line1;
        int i=0;
        while((line1=br.readLine())!=null)
        {
            i++;
        }
   
        br.close();
        return i;
    }
   
    public void writeFile() throws IOException
    {
        try {
        FileWriter fw=new FileWriter("D:\\file2.txt");
        BufferedWriter bw=new BufferedWriter(fw);
        fw.write("I am writing this line to file");
        fw.append("This is for appending further");
       
        fw.close();
        }
        catch(Exception e)
        {
            System.out.println("Error Message"+e.getMessage());
        }
    }
   
    public static void main(String[] args) throws IOException
    {
        FileReader fr=new FileReader("D:\\sample.txt");
        BufferedReader br=new BufferedReader(fr);
        String line1=br.readLine();
       
        System.out.println(line1);
        String str[]=new String[10];
        for(int i=0;i<4;i++)
        {
            str[i]=br.readLine();
        }
        System.out.println(str.length);
        for(int j=0;j<str.length;j++)
        {
            System.out.println(str[j]);
        }
        br.close();
        ReadTextFile n=new ReadTextFile();
        int number=n.nooflines();
        System.out.println("the number of lines in the text file is "+number);
        n.writeFile();
    }

}

Output:
abcd
10
bcde
cdef
null
null
null
null
null
null
null
null
the number of lines in the text file is 3

8.ThisJavaProgram.java

package JavaBasics;
/*
 1.this keyword is used to refer current class instance variables
 2.Used to call current class constructor and this() should put at the beginning
*/

public class ThisJavaProgram
{
   int a;
   double b;
  
   ThisJavaProgram(int a,double b)
   {
       this(); 
       this.b=b;
     
   }
   ThisJavaProgram()
   {
       System.out.println("default constructor");
   }
   public void display()
   {
       System.out.println(a+ " "+b);
   }
   public void test()
   {
       display();
   }
   
    public static void main(String[] args)
   {
        ThisJavaProgram obj=new ThisJavaProgram(20,30);
        obj.display();
        obj.test();

    }

}

Output:
default constructor
0 30.0
0 30.0

9.SuperClass.java

package JavaBasics;

/*
 1.super is  used to refer to the parent class instance variable
 2.super() is used to invoke parent class constructors
 3.super is used to invoke immediate parent class methods
 */

class ParentClass
{
    int a=10;
    ParentClass(int x)
    {
        System.out.println("This is ParentClass Constructor "+x);
    }
    public void display()
    {
        System.out.println("This is ParentClass Method");
    }
   
}

class BaseClass extends ParentClass
{
    int a=20;
    BaseClass()
    {
        super(5);
        System.out.println("This is Child Class Constuctor");
        System.out.println("The value of a in ParentClass is "+super.a);
        super.display();
    }
   
   
}

public class SuperClass
{

    public static void main(String[] args)
    {
        BaseClass obj=new BaseClass();
       

    }

}

Output:
This is ParentClass Constructor 5
This is Child Class Constuctor
The value of a in ParentClass is 10
This is ParentClass Method


10. (a) OnlyClass.java

package JavaBasics;

public class OnlyClass
{
   public int a;
   public String str;
   public void myMethod()
   {
       a=20;
       str="india";
       System.out.println(a+" "+str);
              
   }
   
}

(b) AnotherClass.java

package JavaBasics;

public class AnotherClass {

    public String myMethod2()
    {
        return "java";
    }
   
    public static void main(String[] args)
    {
        OnlyClass obj=new OnlyClass();  // Since it is in the same package, import is not required
        obj.myMethod();
        AnotherClass obj2=new AnotherClass();
        System.out.println(obj2.myMethod2());
    }

}

Output:
20 india
java





No comments:

Post a Comment