Top 10 uses of Java Keywords

Keyword:

  • Keywords are predefined identifiers available directly throughout the JVM.
  • They have a special meaning inside java source code and outside of comments and strings.
  • For Example : public, static, void

Rules:

  • Keywords can not be used as user defined identifier by the programmer either for variable or method or class names, because keywords are reserved for their intended use.
  • All characters in keyword must be used in lower case.

Need of keywords:

  • Basically keywords are used to communicate with compiler and JVM about the operation we perform in java application.
  • In java we perform 10 different operations using keywords
  • They are:
  1. Creating Java file
  2. Storing data temporary
  3. Creating memory locations
  4. Controlling calculations
  5. Setting accessibility permissions
  6. Modifying default properties
  7. Object representation
  8. Establishing relations between classes
  9. Grouping classes
  10. Handling user mistakes
  • In java we have 50 keywords to perform all above 10 operations
  • Among them 47 introduced in java 1.0
  • In Java 1.2 new keyword "strictfp" was added.
  • In Java 1.4 new keyword "assert" was added
  • In Java 5 new keyword "enum" was added
  • Among 50 keywords 2 keywords are reserved words they can not be used in java program, because they defined but they are not implemented , those two are,
  1. goto
  2. const
     

1.Java Files

1.class
2.interface
3.enum

2.Data Types

4.byte
5.short
6.int
7.long
8.float
9.double
10.char
11.boolean
12.void

3.Memory Location

13.static
14.new

4.Control Statements

1.conditional

15.if
16.else
17.switch
18.case
19.default

2.loop

20.while
21.do
22.for

3.transfer

23.break
24.continue
25.return

5.Accessibility Modifiers

26.private
27.protected
28.public

6.Modifiers

28.static // used as modifier and class level memory allocation
29.final
30.abstract
31.native
32.transient
33.volatile
34.synchronized
35.strictfp

7.Object Representation

36.this
37.super
38.instanceof

8.Inheritance Relationship

39.extends
40.implements

9.Package

41.package
42.import

10.Exception Handling

43.try
44.catch
45.finally
46.throw
47.throws
48.assert

11.Unused keywords

49.const
50.goto


Default literals:

1.referenced literal
  ->null
2.boolean literals
->true
->false

Reading data from file using FIleInputStream

1.Reading the data from a file:

  • FileInputStream class is used to read data from a file.
  • It is two step process.
  1. Create  FileInputStream class object by using its available constructors.
  2. Then call read() method on this object till control reach end of file.
  • Means read() method must be called in loop, because it returns only one byte at a time .
  • Hence it must be called in loop for each byte available in the file till it returns "-1".
  • It returns  -1 if control reached end of the file.
FileInputStream class has below constructors to create its object:

  1.  public FileInputStrean(String name) throws FileNotFoundException
  2.  public FileInputStream(File file)  throws FileNotFoundException
  3.  public FileInputStream(FileDescriptor fd)

Rule:

  • To Create FileInputStream class object the file must be with the passed argument name . else this constructor throws java.io.FileNotFoundException.
  • FileInputStream  class constructor throws FileNotFoundException in below situations.
  • If the file is not existed with the passed name.
  • Passed file name is a directory rather than is a regular file.
  • If file does not have reading permissions.

 Java Program to read data from a file:

  1.  Create a file with name test.txt. with text "hello world" this is for example you can write any text.
  2. Creating stream object connecting to test.txt file.
    FileInputStream fis= new FileInputStream("test.txt");
  3. Reading all bytes from the file till control reaches end of file.
    int i=fis.read();
  4. Printing returned character.
    System.out.println(i);

Program #1: 

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.         int i;
  15.         while((i=fis.read())!=-1){
  16.            System.out.println((char)i);
  17.         }
  18.  
  19.     }
  20. }

Output:

  1. h
  2. e
  3. l
  4. l
  5. o
  6.  
  7. w
  8. o
  9. r
  10. l
  11. d

Program #2: Using read() method

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.        byte[] b=new byte[fin.available()];
  15.  
  16.        // Read data into the array
  17.         fin.read(b);
  18.         for (int i = 0; i < b.length; i++) {
  19.  
  20.             System.out.println((char)b[i]);
  21.  
  22.         }
  23.  
  24.     }
  25. }

Output:

  1. h
  2. e
  3. l
  4. l
  5. o
  6.  
  7. w
  8. o
  9. r
  10. l
  11. d

Program #3: Using read(destination, start-index, last-index) method

  1. package com.instanceofjava;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6.  
  7. public class FISDemo {
  8.  
  9.  public static void main(String[] args) throws FileNotFoundException, IOException
  10. {
  11.  
  12.       FileInputStream fis= new FileInputStream("E:\\test.txt");
  13.  
  14.       byte b1[]=new byte[fin.available()];
  15.       fin.read(b1,0,b1.length);
  16.  
  17.                     for(int i=0;i<b1.length;i++)
  18.                     {
  19.                     System.out.print((char)b1[i]);
  20.                     }
  21.  
  22.     }
  23. }



Output:

  1. hello world

Create Thread without extending Thread and implementing Runnable

Using AnonymousThread:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousThread
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(){
  9.  
  10.             public void run(){
  11.  
  12.                 for (int i = 0; i  <=10; i++) {
  13.                    System.out.println("run"+i);
  14.                 }
  15.  
  16.             }
  17.  
  18.         }.start();
  19.  
  20.         for (int i = 0; i  <=10; i++) {
  21.             System.out.println("main:"+i);
  22.         }
  23. }
  24. }

Output:

  1. main:0
  2. run:0
  3. main:1
  4. run:1
  5. main:2
  6. run:2
  7. main:3
  8. run:3
  9. main:4
  10. run:4
  11. main:5
  12. run:5
  13. main:6
  14. run:6
  15. main:7
  16. run:7
  17. main:8
  18. run:8
  19. main:9
  20. run:9
  21. main:10
  22. run:10

 

Using AnonymousRunnable:

  1. package com.instanceofjava;
  2.  
  3. public class AnonymousRunnable
  4. {
  5.  
  6. public static void main(String[] args)
  7.     {
  8.         new Thread(new Runnable(){
  9.  
  10.  
  11.     public void run(){
  12.  
  13.                 for (int i = 0; i  <=10; i++) {
  14.                    System.out.println("run"+i);
  15.                 }
  16.  
  17.             }
  18.  }
  19. ).start();
  20.  
  21.         for (int i = 0; i  <=10; i++) {
  22.             System.out.println("main:"+i);
  23.         }
  24. }
  25. }


Output:

  1. main:0
  2. run0
  3. main:1
  4. run1
  5. main:2
  6. run2
  7. main:3
  8. run3
  9. main:4
  10. run4
  11. main:5
  12. run5
  13. main:6
  14. run6
  15. main:7
  16. run7
  17. main:8
  18. run8
  19. main:9
  20. run9
  21. main:10
  22. run10

Top 7 Java 7 features

java 7 features with examples
Java 7 features


  1. String in switch statements
  2. Type inference for generic instance creation.
  3. The try with resources Statement.
  4. Multiple exception handling System.
  5. Underscored in Numeric literals
  6. Binary Literals with Prefix 0b
  7. java.nio.file package






1.String in switch statements:

  • Did you know previous to java 7 you could do a switch on
    1. char
    2. byte
    3. int
    4. Character
    5. Byte
    6. Integer

  • Java 7 adds String making the switch instruction much friendlier to String inputs
  • The alternative before was to do with if  else statements paired with a bunch of String equal() calls .
  • The result much cleaner and compact code.
  • Here the java 7 switch with string 
  • One of the java 7 new feature strings in switch 
 Example program on java 7 new feature string in switch:

  1. package com.instanceofjavaforus;
  2.  
  3. public class Demo{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  String color="green";
  8.  
  9. switch(color){
  10.  
  11.    case "white": System.out.println("white");
  12.       break;
  13.  
  14.    case "green": System.out.println("green");  
  15.       break;
  16.  
  17.    case "red": System.out.println("red"); 
  18.      break; 
  19.  
  20.    case "yellow": System.out.println("yellow"); 
  21.      break; 
  22.  
  23.    case "blue": System.out.println("blue");    
  24.        break;  
  25.  
  26.    case "pink": System.out.println("pink");
  27.       break; 
  28.  
  29.    case "violet": System.out.println("violet"); 
  30.        break;  
  31.  
  32.      
  33.    default: System.out.println("invalid color")
  34. }
  35. }



 

2.Type inference for generic instance creation:

  • Previously when we are using generics you had to specify the type twice, in the declaration and the constructor
  • Before java 7 to create arraylist of string type
  • List<String> str= new ArrayList<String>();
  • In java 7 you just use the diamond <> operator without the type.
  • List<String> str= new ArrayList<>();

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  List<String> lst= new ArrayList<>();
  8.   lst.add("ABC");
  9.   lst.add("XYZ");

  10. }
  11. }

 

3.The try with resources Statement:

 

  • The new try statement allows opening up a "resource" in atry block and automatically closing the resource when the block is done.
  • For example in the below piece of code we opened a file print line by line to stdout.
  • But pay close attention to the finally block.



  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  BufferedReader in=null;
  8. try{
  9. in= new BufferedReader(new filereader("test.txt"));
  10. String line=null;
  11. while((line=in.readLine())!=null)){
  12. System.out.println(line);
  13. }
  14. }catch(IOException e){
  15.  e.printStackTrace();
  16. }
  17. finally{
  18. try{
  19. if(in!=null)
  20. in.close();
  21.  }
  22. catch(IOException e){
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. }



  • when using a resource that has to be closed , a finally block is needed to make the clean up code is executed eve if there are exceptions thrown back.
  • The new try catch with resources allows us to automatically close these resources in a more compact set of code.

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7. try(
  8. BufferedReader  in= new BufferedReader(new filereader("test.txt"))
  9. )
  10. {
  11.  
  12. String line=null;
  13. while((line=in.readLine())!=null)){
  14. System.out.println(line);
  15. }

  16. }catch(IOException e){
  17.  e.printStackTrace();
  18. }
  19. }
  20. }

 

4.Multiple exception handling System:

  • Tired of repetitive error handling code ?
  • APIs like java.io and java.lang.reflect?


  1. package com.instanceofjava;
  2.  
  3. public class Demo{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  try{
  8. Class a= Class.forName("wrongclassname");
  9. Object instance=a.newInstance();

  10. }
  11. catch( ClassNotFoundException e){
  12. System.out.println("Failed to create instance") ;
  13. }
  14. catch( IllegalAccessException e){
  15. System.out.println("Failed to create instance") ;
  16. }
  17. catch( InstanctiationException e){
  18. System.out.println("Failed to create instance") ;
  19. }
  20.  

  21. }
  22. }

  • When the exception handling is basically the same, the improved catch operator now supports
    multiple exceptions in a single statement separated by "|".

  1. package com.instanceofjava;
  2.  
  3. public class Java7feture{
  4.  
  5. public static void main(String args[]){
  6.  
  7.  try{
  8. Class a= Class.forName("wrongclassname");
  9. Object instance=a.newInstance();

  10. }
  11. catch( ClassNotFoundException  | IllegalAccessException  | InstanctiationException ex ){
  12. System.out.println("Failed to create instance") ;
  13. }
  14.  

  15. }
  16. }

  

5.Underscored in Numeric literals:


  1. package com.instanceofjava;
  2.  
  3. public class Java7FeatureTutorial{
  4.  
  5. public static void main(String args[]){
  6.  
  7. int value = 1_000_000;  
  8.  
  9. long Atmcardnumber =  0123_4567_8901_2345L; //16 digit number
  10.  
  11. long ssn = 777_99_8888L;
  12.  
  13. double pi = 3.1415_9265;
  14.  
  15. float  pifloat = 3.14_15_92_65f;

  16. }
  17. }

6.Binary Literals with Prefix 0b:



  1. package com.instanceofjava;
  2.  
  3. public class Java7FeatureTutorial{
  4.  
  5. public static void main(String args[]){
  6.  
  7. // An 8-bit 'byte' value:
  8. byte byte = 0b00100001;
  9.  
  10. // A 16-bit 'short' value:
  11. short short = 0b0010001010001010;
  12.  
  13. // Some 32-bit 'int' values: 
  14. int a = 0b10100001010001011010000101000101;
  15.  
  16. int b= 0b101;
  17.  
  18. int c = 0B101; // The B can be upper or lower case.

  19. }
  20. }

 

7.java.nio.file package:

  • java 7 introduced java.nio and sub package java
  • java.nio.file
  • java.nio.file.attribute
  • Support for input output file. and to access default file system.  

You might like:

PrintStream Class

  • This class is filer output Stream  class, It adds functionality to another output stream , namely the ability to print representation of various data values conveniently.
  • It is the most convenient class in writing data to another output stream, because of below three reasons.

  1. Unlike other output stream's write() method , write() method of this class never throws an IOException.
  2. Calling flush() method is optional, it is called automatically.
  3. In addition to default write() methods  it is defined new methods called print() and println(). These two methods are overloaded to print all types of java data type values including object. Below are the overloaded print() and println() methods list.
  1. public void print(int x);
  2. public void print(long x);
  3. public void print(float x);
  4. public void print(double x);
  5. public void print(char x);
  6. public void print(boolean x);
  7. public void print(char[] x);
  8. public void print(String x); 
  9. public void print(Object x); 
  1. public void println(int x);
  2. public void println(long x);
  3. public void println(float x);
  4. public void println(double x);
  5. public void println(char x);
  6. public void println(boolean x);
  7. public void println(char[] x);
  8. public void println(String x); 
  9. public void println(Object x);  
  10. public void println();
  • PrintStream class object is created in System class using a static variable called out.
  • So we can access above methods from our class using System class's PrintStream object as shown below.
  • System.out.print("abc");
  • System.out.println("abc");
  • System is predefined class in java.lang package.
  • out is static referenced variable of type PrintStream class. It is created in System class to hold PrintStream class object.
  • println() and print() methods are non static methods defined in PrintStream class to print data.

Difference between print() and println():

  • print() method places cursor in the same line after printing data, so that next coming output will be printed in the same line.
  • But println() method places cursor in the next line after printing data so that next coming output will be printed  in the next line.
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.print("A");
  9.        System.out.println("B");
  10.        System.out.println('C');
  11. }
  12. }




  1. AB
  2. C


Rule #1:

  • We can not call print method without passing arguments because we do not have no argument print method so it leads to Compilation Error.
  • But we can call println() method without passing arguments because we have no argument println() method , it prints new line.
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.println("A");
  9.        System.out.println();
  10.        System.out.println("B"); 
  11.        System.out.print();   // Compilation Error
  12.       System.out.println("B"); 
  13.  
  14. }
  15. }

Rule #2:

  • We cannot call print() or println() methods by passing null literal directly.
  • System.out.println(null);
  • It leads to Compilation Error : Ambiguous error. 
  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.
  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ }
What is the output of below program?

  1. package com.instanceofjavaforus;
  2.  
  3. public class PrintDemo{
  4.  
  5.  
  6.   public static void main(String[] args) {
  7.  
  8.        System.out.println(null); // Compilation Error
  9.        System.out.print(null); // Compilation Error
  10.      
  11.  
  12. }
  13. }

 

Difference between println(Object) and writeObject(Object) methods?

  • writeObject(Object) method serializes the given object and sends its state to underlying output stream. 
  • where as println(Object) method does not perform serialization instead it prints the passed object information that is returned by the toString() method.
  • It means println(Object) method internally calls toString() on given object to print the given object information .
  • If toString() method is not defined in the passed object's class it will call Object class toString() method which is originally defined.
  • toString() method in object class returns current object classname@hashcode in hexadecimal string format.

What is the output of below program?
  • toString() method is not overridden in Example class

  1. package com.instanceofjava;
  2.  
  3. public class Example{
  4.  
  5.   int x, int y;
  6.  
  7.   public static void main(String[] args) {
  8.  
  9.     Example obj = new Example();
  10.        obj.x=1;     
  11.        obj.y=2;
  12.        System.out.println(obj);
  13.       
  14. }
  15. }




  1. com.instanceofjava.Example@53601a4f



What is the output of below program?
  • toString() method is not overridden in Example class

  1. package com.instanceofjava;
  2.  
  3. public class Example{
  4.  
  5.   int x, int y;
  6.  
  7. public String toString(){
  8.    return "x="+x+" "+"y="+y;
  9. }
  10.  
  11.   public static void main(String[] args) {
  12.  
  13.     Example obj = new Example();
  14.      obj.x=1;
  15.      obj.y=2;

  16.        System.out.println(obj);
  17.       
  18. }
  19. }



InputStream vs OutputStream

  • For each type of source and destination in java.io package oracle given a separate class.

InputStream Class:

  • ByteArrayInputStream
  • FileInputStream
  • FilterInputStream
    • BufferedInputStream
    • DataInputStream
    • LineNumberInputStream
    • PushbackInputStream
  • ObjectInputStream
  • PipeInputStream
  • SequenceInputStream
  • StringBufferInputStream

IputStream Class Methods:

  • Since InputStream class is the super class for all input stream classes. It has below methods with general implementation for all sub classes.

1.public int available() throws IOException :

  • Checking available bytes to read.

2.public abstract int read() throws IOException :

  • Reading byte-by-byte.

3.public int read(byte[] b) throws IOException :

  • Reading all  bytes.

4.public int read(byte[] b, int off, int length) throws IOException :

  • Reading selected range of bytes.

5.public boolean markSupported() :

  • Checking is this Stream supports marking.

6.public void mark(int readLimit) :

  •  Marking current position of stream.

7.public void reset() throws IOException :

  • Placing the control at marked place.

8.public long skip(long n) throws IOException :

  • Skip reading given range of bytes.

9.public void close() throws IOException :

  • Closing the stream.

OutputStream Class:

  • ByteArrayOutputStream
  • FileOutputStream
  • FilterOutputStream
    • BufferedOutputStream
    • DataOutputStream
    • PrintStream
  • ObjectOutputStream
  • PipeOutputStream

OutputStream class methods:

  • Since OutputStream is the super class of all binary output stream classes it has below method with general implementation for all sub classes.

1.public abstract void write(int i)throws IOException:

  • Writing one by at time to an output stream.

2.public void write(byte[] b) throws IOException :

  • Writing stream of bytes to an output stream.

3.public void write(byte []b , int off, int length) throws IOException :

  • Writing range of stream of bytes to an output stream.

4.public void flush() throws IOException :

  • Flush all bytes to destination from output Stream.

5.public void close() throws IOException :

  • Close output stream.

FileInputStream and FileOutputStream:

  • These classes are used to read and write data as byte from File.
  • Basically these two streams are used as basic data source and destination for other streams.

DataInputStream and DataOutputStream:

  • These two classes are used to read and write data as primitive data.
  • Basically these two streams are used to add capability to another input stream and output stream to read and write data as primitive types.

ObjectInputStream and ObjectOutputStream:

BufferedInputStream and BufferedOutputStream:

  •  These two classes are used to read and write data as buffers.
  • Basically these two streams are used to improve reading and writing performance of other streams.

SequenceInputStream:

  • This class is used to read data from multiple InputStreams Sequentially.

 PrintStream: 

  • PrintStream class is filter output stream class .
  • Its adds functionality to another OutputStream, namely the ability to print representations of various data values conveniently.


Basic steps to perform IO Operations:

  • Create stream class object based on source and destination.
  • Call read() method to read data from the source.
  • Call write() method to write data to the destination.
For instance , to perform IO Operations on files we must create
  • FileInputStream
  • FileOutputStream or
  • FileReader
  • FileWriter  Streams class objects
-
You might like:

Multiply two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Multiply2Matrices{
  6.  
  7.    public static void main(String args[])
  8.    {
  9.  
  10.       int m, n, p, q, sum = 0, c, d, k;
  11.  
  12.       Scanner in = new Scanner(System.in);
  13.  
  14.       System.out.println("Enter the number of rows and columns of first matrix");
  15.  
  16.       m = in.nextInt();
  17.       n = in.nextInt();
  18.  
  19.       int first[][] = new int[m][n];
  20.  
  21.      System.out.println("Enter the elements of first matrix");
  22.  
  23.       for ( c = 0 ; c < m ; c++ )
  24.          for ( d = 0 ; d < n ; d++ )
  25.             first[c][d] = in.nextInt();
  26.  
  27.       System.out.println("Enter the number of rows and columns of second matrix");
  28.  
  29.       p = in.nextInt();
  30.       q = in.nextInt();
  31.  
  32.      if ( n != p )
  33.          System.out.println("Matrices with entered orders can't be multiplied with each other.");
  34.       else
  35.       {
  36.          int second[][] = new int[p][q];
  37.          int multiply[][] = new int[m][q];
  38.          System.out.println("Enter the elements of second matrix");
  39.  
  40.          for ( c = 0 ; c < p ; c++ )
  41.             for ( d = 0 ; d < q ; d++ )
  42.                second[c][d] = in.nextInt();
  43.  
  44.          for ( c = 0 ; c < m ; c++ )
  45.          {
  46.             for ( d = 0 ; d < q ; d++ )
  47.             {   
  48.                for ( k = 0 ; k < p ; k++ )
  49.                {
  50.                   sum = sum + first[c][k]*second[k][d];
  51.                }
  52.                multiply[c][d] = sum;
  53.                sum = 0;
  54.             }
  55.          }
  56.  
  57.          System.out.println("Multiplication of entered matrices:-");
  58.  
  59.          for ( c = 0 ; c < m ; c++ )
  60.          {
  61.             for ( d = 0 ; d < q ; d++ )
  62.                System.out.print(multiply[c][d]+"\t");
  63.             System.out.print("\n");
  64.          }
  65.  
  66.       }
  67.  
  68.    }
  69. }  

OutPut:


  1. Enter the number of rows and columns of first matrix
  2.  
  3. 2 2
  4.  
  5. Enter the elements of first matrix
  6.  
  7. 2 2
  8. 2 3
  9.  
  10. Enter the number of rows and columns of second matrix
  11.  
  12. 2 2
  13.  
  14. Enter the elements of second matrix
  15.  
  16. 1 1
  17. 1 1
  18.  
  19. Multiplication of entered matrices:-
  20.  
  21. 4    4    
  22. 5    5  


Select Menu