Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, 7 November 2016

Which Non Access Modifier can be used which Non Access Modifier?





In Nutshell:
  • abstract cannot be used with any other Non Access Modifier
  • final can be used with all other Non Access Modifier except abstract
  • synchronized can be used with all other Non Access Modifier except abstract
  • native can be used with all other Non Access Modifier except abstract, strictfp
  • strictfp can be used with all other Non Access Modifier except abstract, native
  • static can be with all other Non Access Modifier except abstract

Tuesday, 4 August 2015

Applet Demo 1



Source Code:


import java.applet.*;
import java.awt.*;


public class Demo1 extends Applet
{
    public void init()
    {
        //Code to run automatically
        this.setSize(500, 500);
        this.setBackground(Color.CYAN);
    }
    public void paint(Graphics g)
    {
        
        
        //now draw graphics
        g.drawLine(0, 0, 100, 100);
        g.drawRect(0, 0, 100, 100);
        
        //change color of graphics
        g.setColor(Color.blue);
        g.drawString("Applet Demo", 0, 120);
    }
}

Monday, 3 August 2015

Getting Started with Java GUI Programming



Download the Netbeans IDE from filehippo.com/download_netbeans

Also download Java JDK(32-bit or 64-bit) according to your operating system. For 32-bit operating system download the 32-bit version of Java JDK and for 64-bit operating system download the 64-bit version of Java JDK

After downloading firstly install Java JDK and then Netbeans

Sunday, 2 August 2015

Learn Java Part 11

for each loop in java



What is for each loop?

for each loop in java is the enhanced version of for loop. It is introduced from JDK 5. It is used to iterate all elements of an array or Collection.




Syntax:



for ( data-type variableName :  array or collection )

{

    //statements

}


Consider the following program:

public class ForEachLoop
{
    public static void main(String[] args)
    {
        int[] array ={ 1, 2, 3, 4, 5 };
        System.out.println("Array elements: ");

        for(int element: array)
               System.out.print(element+"  ");

    }
}



Write the above program in Notepad and save it as ForEachLoop.java 

Compile and run it to get the following output:



Array elements: 

1  2  3  4  5



the loop for(int element: array)

fetches the elements of array and assign it to variable element so we can use element to access the elements of array



Consider the following program to access elements of multi-dimensional array



public class ForEachLoop
{
    public static void main(String[] args)
    {
     int[][] array ={ {1, 2, 3, 4,},{ 5,6,7,8} }; //array with 2 rows and 4 columns
        System.out.println("Array elements: ");
        for(int[] row: array)
            for(int element: row)
               System.out.print(element+"  ");
    }
}

Write the above program in Notepad and save it as ForEachLoop.java 

Compile and run it to get the following output:



Array elements: 

1  2  3  4  5  6  7  8



the loop for(int[ ] row: array)

fetches one row of array and assign it to variable row so we can use row to access one row(or one dimensional array) of array



the loop for(int element: row)

fetches the elements of row and assign it to variable element so we can use element to access the elements of row

Command Line Arguments




public class CommandLineArguments
{
    public static void main(String[] args)
    {
        System.out.println("Total number of Command Line Arguments: "+args.length);
        System.out.println("Command Line Arguments:");
        for(int i=0;i<args.length;i++)
            System.out.println(args[i]);
    }
}


Type the above program in Notepad and Save it as CommandLineArguments.java

Compile like this:



javac  CommandLineArguments.java



Run like this:



java  CommandLineArguments   Arguments



For example: 


java  CommandLineArguments   Hello World

output:



Total number of Command Line Arguments: 2

Command Line Arguments:

Hello

World






If you run like this:

java  CommandLineArguments

output:



Total number of Command Line Arguments: 0

Command Line Arguments:






Note: Each argument in command line arguments is seperated by a space

Learn Java Part 10

Monday, 22 June 2015

Learn Java Part 9

Learn Java Part 8

Program to calculate how many times a word occurs in a given string in just one line




//Program to calculate how many times a word occurs in a given string in just one line

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
class CountWord
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();  //Gets a string from user
     System.out.println("Enter the word to search for: ");
     String word=br.readLine();  //Gets a string from user

     int count=(s.length()-s.replace(word+"", "").length())/word.length();     

   System.out.println(word+" occurs in given string for: "+count+" times");
  }
}

Wednesday, 17 June 2015

Program to reverse each word of a given string




//Program to reverse each word of a given string

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
import java.util.*;  //for StringBuffer
public class WordReverse {
    public static void main(String[] args)throws IOException
    {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the string:");
    String str=br.readLine();
    StringTokenizer st=new StringTokenizer(str);
    String temp="";
    while(st.hasMoreTokens())
    {
        temp=temp+new StringBuffer(st.nextToken()).reverse().toString()+" ";
    }
        System.out.println("Reversed String is:");
        System.out.println(temp);
    }   
}




Output:



Enter the string:

Hello this is GsbProgramming

Reversed String is:

olleH siht si gnimmargorPbsG 

Saturday, 13 June 2015

Program to calculate how many times a word occurs in a given string




//Program to calculate how many times a word occurs in a given string

import java.io.*;  //for IOException, BufferedReader, InputStreamReader
class CountWord
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine();  //Gets a string from user
     System.out.println("Enter the word to search for: ");
     String word=br.readLine();  //Gets a string from user

     int count=0,pos=0;
     while(true)
     {
        pos=s.indexOf(word,pos);
        if(pos==-1)
            break;
        else
        {
            count++;
            pos++;
        }
      }

   System.out.println(word+" occurs in given string for: "+count+" times");
  }
}


Program to calculate the frequency of each character in given String


//Program to calculate the frequency of each character in given String

import java.io.*; //for IOExecption, BufferedReader, InputStreamReader
class CharacterFrequency
{
  public static void main(String args[]) throws IOException
  {
     System.out.println("Enter the string: ");
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     String s=br.readLine(); //gets a string from user
     String temp=s;
     System.out.println("\nFollowing are the characters in string");
    
     while(temp.length()!=0)
     {
        char ch=temp.charAt(0);
        int count=0;
        for(int i=0;i<temp.length();i++)
          if(temp.charAt(i)==ch)
            count++;
        System.out.println(ch+": "+count);
     temp=temp.replace(ch+"","");  //replaces the current character with empty string
     }
  }
}

Monday, 8 June 2015

Printing different patterns of Stars with the help of nested for loop

Naming, Compiling and Running Java Files Containing More Than One Class Definitions



Today we will see how to name, compile and running java files containing more than one class definitions.



1). Consider the following program.















class ClassOne
{
     public static void main(String[] args)
     {
         ClassTwo.methodOfClassTwo();
     }
}
class ClassTwo
{
     static void methodOfClassTwo()
     {
         System.out.println("From Class Two");
     }
}


Naming : You can save this program with any name. It can be ClassOne.java or it can be ClassTwo.java or it can be anything.java.



Compile : You have to compile this program with the name you have given like >javac ClassOne.java or >javac ClassTwo.java or >javac anything.java.

When you compile a java file, the number of .class files
generated will be equal to number of class definitions in it. i.e If a
java file has one class definition, one .class file will be generated.
If it has two class definitions, two .class file will be generated and
so on.

Running : That means for the above program, two .class files will be generated. Then which one to run? is it >java ClassOne or is it >java ClassTwo…..    It must be >java ClassOne, because execution of any java program start with main() method. If you try to run >java ClassTwo, you will get an error: Main method not found in class ClassTwo, please define the main method as public static void main(String[] args).



2). Now consider same example with litte modification, just declare ClassOne as public.

















public class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}
Naming : The name of above java file must be and only
“ClassOne.java”. You can’t give any other name. If you give any other
name you will get compile time error : class ClassOne is public, should be declared in a file named ClassOne.java.

Compile : Only one name is allowed here so you have to compile with that name i.e >javac ClassOne.java.

Running : That must be >java ClassOne. because this is only class that has main() method.





3). Now make little more modifications to the program. Declare ClassTwo as public and ClassOne as default.



class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
public class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}


Naming : You have to save this file with name as “ClassTwo.java”. If you give any other name you will get compile time error becuase ClassTwo is public.

Compile : It must be >javac ClassTwo.java.

Running : You must name this program as ClassTwo.java, you must compile this program as >javac ClassTwo.java but you have to run it as >java ClassOne not as >java ClassTwo. Because only ClassOne has main() method. ClassTwo doesn’t have main() method. If you run it as >java ClassTwo, you will get run time errorMain method not found in class ClassTwo, please define the main method as public static void main(String[] args).



4). Now make little more modifications to the program. Declare both the classes as public.
















public class ClassOne
{
     public static void main(String[] args)
     {
          ClassTwo.methodOfClassTwo();
     }
}
public class ClassTwo
{
     static void methodOfClassTwo()
     {
          System.out.println("From Class Two");
     }
}


Naming : Whatever you give the name, whether it is ClassOne.java or
ClassTwo.java or anything.java,  you will get compile time error.
Because One java file should contain only one or zero public class. It should not contain more than one public class.



5) Look at the following program.

















class ClassOne
{
     public static void main(String[] args)
     {
          System.out.println("From Class One");
     }
}
class ClassTwo
{
     public static void main(String[] args)
     {
          System.out.println("From Class Two");
     }
}
Naming : You can save this program with any name. It can be ClassOne.java or it can be ClassTwo.java or it can be anything.java as there is no public class.



Compile : You have to compile this program with the name you have given i.e >javac ClassOne.java or >javac ClassTwo.java or >javac anything.java.

Running : Notice that both the classes have main() method. You can run both the classes with their name. i.e  If you trigger >java ClassOne, you will get From Class One as output. If you trigger >java ClassTwo, you will get From Class Two as output.