Concept of access specifiers,Simple programs in java

Access specifiers in java:
What are access specifiers:They are keywords that restricts the access of the instance variable(data) and methods within a package,inherited classes or within the class
There are basically 4 access specifiers in java:

  1. public:Gives access is in the package,other classes,within the class but cannot be accesses in another package.Free access to the variable in the whole project to be summed.
  2. private:Most restrictive,can access variable within the class only.Used for saving critical data.
  3. protected:Data and methods are access within the classes that are inherited to the current class only and within class access.
  4. default:Data and methods are accessible withing your package/project


Simple programs in java

Program to find the largest between two numbers:
Code:
class A
{
public static void main(String args[])
{
int a=5;
int b=10;
          if(a>b)
            {
           System.out.println("a is greatest");
            }
           else 
           System.out.println("b is greatest");
}
}
Output:b is greatest

Programs to show usability of methods:
Code:
class Method_demo
{
void foo()             //foo named method with return type as void and no arguments
{
System.out.println("foo  method called");
}
public static void main()
{
Method_demo md=new Method_demo();//creation of object named fd
fd.foo();//calling foo method,i.e executing block of code for foo method
}
}
Output:foo method called

Program to read a file using bufferedreader:

class ReadFile
{
String text;//to store the text
try
{
FileReader fr=new FileReader("C:\\Myfile.txt");//creating a file reader object to locate the file and load into memory
BufferedReader br=new BufferedReader(fr);//actually reading the file by bufferedreader in terms of bytes
while(br.readLine()!=null)
{
text=br.readLine();//copy the contents
System.out.println(text);//now show it!!
}
}
catch(IOExceptio ex)
{
ex.printStackTrace();
}
finally{
try
{
if(br!=null)
{
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}

}

Program to make character typed with delay:
class Type_writer{
String text="This is a text typed automatically by the computer."; //change the text of your choice
void main(String args[])

Type_writer tw=new Type_writer();
for(int i=0;i<=tw.text.length();i++){
System.out.print(tw.text.charAt(i));
Thread.sleep(500);//here is the interesting part,the thread will sleep for 500 milliseconds,i.e,1/2 seconds and display one character at a time
}
}
}

Comments

Popular posts from this blog

Four building blocks of Object oriented programming language

Exceptions and exceptional handling

Lists in java