Single Post

Header

Monday, December 21, 2015

Java Simple Programs - 1


1. This Program  contains variables declaration and operators

public class JavaBasics {

public static void main(String[] args)
{
System.out.println("welcome to java");
        int a=20,b=30;  //This is Single Line Comment
        System.out.print("the value of a is "+a+" and b is "+b);
        int c=a+b; int d=a*b; float e=a/b; float f=a%b;
       // System.out.println(c+" "+d+" "+e+" "+f);
        int  x=c=a;
        System.out.println("c ="+c+" x= "+x);
        int y;
        x=1;
        y=x++;
        System.out.println("y ="+y+" x is "+x);
        x=1;
        y=++x;
        System.out.println("y ="+y+" x is "+x);
        boolean i =true;
        boolean j =false;
        System.out.println("or value is "+(i|j)+"and value is "+(i&j));  
}
}
output:
welcome to java
the value of a is 20 and b is 30c =20 x= 20
y =1 x is 2
y =2 x is 2
or value is trueand value is false

2.This Program contains the if-else statement,for and do-while loops

public class JavaLoops {


public static void main(String[] args)
{
int a=10,b=20,c=30;
if(a!=20) { System.out.println("a value is "+a); }
if(a>20){ System.out.println("a value is greater than 20 ");
} else { System.out.println("a value is less than 20 "); }
if(a>b && a>c) {
System.out.println("a is the biggest "+a);
} else if (b>a && b>c) {System.out.println("b is the biggest "+b); } 
else {System.out.println("c is the biggest "+c); }
for(int i=0;i<5;i=i+2) { System.out.println("i value is "+i); }
int x=7;
        while(x<9) { 
        System.out.println("x value is "+x); 
        x=x+1 ; }
        do { 
        System.out.println("x value is "+x);
             x++; } while(x<11) ; 
           
}
}

output:
i value is 4
x value is 7
x value is 8
x value is 9
x value is 10

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





Java interview programs

Java interview programs

1.
public class Program1 {
public static void main(String args[]) {
int x=5;
boolean b1 = true ;
boolean b2 = false;
if ((x==4) && !b2)
   System.out.print("1 ");
System.out.print("2 ");
if((b2=true) && b1)
System.out.print("3");
}

}

Output:
2 3

2.
public class Program2 {
static String s1 = "java";
     static String s2 = "java";
 
public static void main(String[] args) {
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}

Output:
true
true

3.
public class Program3 {
String s1 = "java";
     String s2 = "java";
public static void main(String[] args) {
System.out.print(s1==s2);
}
}

Output:Excption occurs
Cannot make a static reference to the non-static field s1
Cannot make a static reference to the non-static field s2

4.
public class Program4 {

public static void main(String[] args) {
String s1 = "java";
   String s2 = "java";
System.out.print(s1==s2);
}
}

Output:
true

5.
public class Program5 {
public static void main(String[]  args) {
String str1 = "123";
str1 += "10";
System.out.println(str1);
String str2 = "234";
str2.concat("10");
System.out.println(str2);
String str3 = "345";
str3=str3.concat("10");
System.out.println(str3);
}
}

Output:
12310
234
34510


6.
interface myInterface {
    int a= 8;
    void sample() ;
}

public class InterfaceA implements myInterface {
 //   a = 12;  syntax error
public void sample() {
System.out.println("test");
}
public static void main(String[]  args) {
InterfaceA obj = new InterfaceA();
obj.sample();
}

}

Output:
test

7.
 class A {
public void test() {
System.out.println("class A");
}
}

 class B extends A {
public void test() {
System.out.println("class B");
}
}

public class Overriding {

public static void main(String[] args) {
A a = new A();
a.test();
B b = new B();
b.test();
A a1 = new B();
a1.test();
// B b1 = new A(); cannot convert from A to B
    // b1.test();

}

}

Output:
class A
class B
class B