Is Java Compiled or Interpreted or both?

Java is Compiled and Interpreted language.

Java program gets compiled when you compile it(with javac command). After Java Program gets compiled, .class file gets generated, which is in byte code format.

This .class file is Platform independent and can run on any platform, having JVM(Java Virtual Machine).

.class file is interpreted by JVM when you try to run the program(with java command).

Hence Java is Compiled and Interpreted Language.

Relatively, Interpreted languages run slower compared to Compile only languages.

PipedInput OutputStream example

PipedInputStream and PipedOutputStream are classes provided in java.io package. PipedInputStream is inherited from InputStream, and PipedOutputStream is inherited from OutputStream.
A piped input stream should be connected to a piped output stream, using connect() method(as shown in below example). Data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.

Below is an example, in which main thread reads characters from PipedInputStream, and other thread writes characters to PipeOutputStream.


import java.io.*;

class MyThread extends Thread{
    static String str = "Hello How are you";
    //creating one thread t1 which writes the data
        public void run(){
            for(int i=0;i<=str.length();i++){
            try{
                PipedInputOutput1.pout.write(str.charAt(i));
                Thread.sleep(1000);  //1000 milliseconds
            }catch(Exception e){
            System.out.println(e.getMessage());
            }
            } //end of for
        }  //end of run()

}

class PipedInputOutput1{
    final static PipedOutputStream pout=new PipedOutputStream();
    final static PipedInputStream pin=new PipedInputStream();

    public static void main(String args[])throws Exception{
        pout.connect(pin);//connecting the streams

        MyThread t1 = new MyThread();
        //creating another thread t2 which reads the data

        //starting both threads
        t1.start();

        try{
            for(int i=0;i<=MyThread.str.length();i++)
            {
                System.out.println((char)pin.read());
            }
        }catch(Exception e){
        System.out.println(e.getMessage());
        }
    }
}


You may also like to read:
SequenceInputStream purpose
Convert String to a Stream
How to take input from key board
Java Serialization example

SequenceInputStream example

SequenceInputStream is used to combine multiple input streams, and creates single SequenceInputStream. And reading from this SequenceInputStream reads the input streams one after another.
Below is simple example showing how to use SequenceInputStream

import java.io.*;
class SequenceInputStreamDemo{
  public static void main(String args[]) throws Exception{

     FileInputStream fin1=new FileInputStream("f1.txt");
     FileInputStream fin2=new FileInputStream("f2.txt");
     FileInputStream fin4=new FileInputStream("f3.txt");

     FileOutputStream fout=new FileOutputStream("f4.txt");

     SequenceInputStream sis=new SequenceInputStream(fin1,fin2);

     SequenceInputStream sis1 = new SequenceInputStream(sis,fin4);

     int i;
     while((i=sis1.read())!=-1)
     {
        fout.write(i);
     }
     sis.close();
     fout.close();
     fin1.close();
     fin2.close();
  }
}

Basic Java Assignments

Below are few Java assignments you can try to develop programs, and get more confidence in Java.
1a. Declare one dimensional array of primitive integers, of size 20.
Write a program to reverse the elements of array, and print reversed array.

1b. From a given integer, extract each digit, and display each digit. NOTE: integer can have any number of digits(ofcourse within integer range)

1c. Display all numbers between 1 and 40, except number, which is multiple of both 2 and 3.


2.Declare two dimensional arrays of primitive floats, with 6 rows and 8 columns.
Write a program to exchange row and column numbers, and print the final elements in rows and columns.

3.Write a class, with a method public void show(), and print Hello World message from this method.
In main method create object of above class, and invoke show() method.

4.In addition to above Assignment 3, add a default constructor[print message in constructor body] to the class.
In main method create object of above class, and invoke show() method. In output observe the order in which the messages are printed.

5.Write a class(say class A) with few data members, and methods.In another class write below methods which
a.takes object of class A as parameter,
b.create object of class A and return the object.

6.Method overload: write a class with 4 methods named add() with different number and type of parameters.add() methods need to return added value of parameters.
From main method invoke the 4 add() methods, get the return values, print them.

7.Write a class with four static methods(add, , each accepting 2 parameters )computes mathematical operation and prints the result.Invoke these static methods from main method.

8.Write a program with all usages of this keyword.
For eg. this(), this. , this

9.Invoke static method, and use static data members from another static method.
Also invoke non static method, and use non static data members from a static method.
observe the difference…

10.Serialization:Write an Employee class with id,name, father name, photo url as data members. use transient keyword for photo url. Serialize the object of Employee class and de serialize it. print data members of de serialized object.

11.Open file using FileInputStream, read one line at a time from file, and print lines on console.
Hint:use BufferedReader

12.Use SequenceInputStream, to combine input from four different files, and write all the content to fifth file.

13.Create a class with 2 data members of any type, along with get and set methods. Then declare an array of this class type, and store objects in the array. Now iterate(using for loop) through each object in array, print object details with get method.

14.in main method throw an exception, using throw keyword, catch the exception using catch block. In catch block, further throw the exception.Hint: use throws keyword also

15.Which is base class of all classes in Java?

16.Write a class which inherits from String class, observe it.Also try to inherit from StringBuffer, Integer, Float, classes also.

17.Write a program for Nested try blocks, and observe the execution flow.

18.In Collection, what is difference between Object based Collection and Generic version Collection? What are the scenarios in which each of them are preferred.

19.What is output of below program

public class Test{
    void sum(int i,int j)
    {
        int k=0;
        System.out.println("Hello");
        sum(i,j);
    }

    public static void main(String args[])
    {
        Test obj = new Test();
        obj.sum(10,20);
    }
}
Ans: Exception in thread "main" java.lang.StackOverflowError occurs
20.Using printStackTrace(), get the stack trace into a String, instead of printing to console
21.There is a file with some data as shown below
f1,f2
f4,f6
f2,f1
f2,f3
f3,f4

f1,f2 means f1 is friend of f2, and so on. Write a program to read contents of this file and remove duplicate entries, and write non duplicated entries to another file.

22. Is it possible to change the current object to which this is reference? In other words, is below statement  valid in Java
this = new Xyz();//Xyz is some class

23. A two dimensional Array with 4 rows and 5 columns, and type float. Add elements of each row, display total and average of each row.


Servlets interview Questions

  1. Using Servlets develop page view counter, count value can be maintained in database. Use cookies to find unique visits to the web page
  2. JSP write Filter, with a specific url pattern. And check that Filter need to get invoked only when request url matches the pattern
  3. Write a Filter, for JSP, which checks the ip address from where request has originated, return without processing request if the request ip address is in a specific range
  4. On webpage provide option to select background color of the page, store this back ground color in cookie. Later, when user displays the cookie value(background color), to display the webpage with selected back ground color
  5. Create custom JSP tag, use this custom tag in your JSP code


You may also like to read:
Core Java Assignments 1

How to declare constants in Java?

final keyword is used to declare constants.

final can be used to declare constants
1. which is a data member in a class.
2. in an interface
3. local within a method.

Declared constant can be primitive or non primitive data type


Below is an example

class Abc{
    public void show()
    {
        System.out.println("show() method in Abc class");
    }
}

interface Test{
    final int VAL = 45;
}

public class FinalKeywordDemo {
    final static float XYZ = 3.5f;
    final static Abc obj = new Abc();
    public static void main(String args[])
    {
        final int MAX_VALUE = 10;
        //final keyword is used to define constant values

        //obj = new Abc();//error, b'coz obj is final
        //MAX_VALUE = 20; //error, b'coz ABC is final
        //XYZ = 5.8f; //error

        System.out.println(MAX_VALUE+" "+XYZ+" "+Test.VAL);
    }
}


You may also like to read:
Purpose of final method
What is final class

List of Java Keywords

In the Java programming language, a keyword is one of 50 reserved words that have a predefined meaning in the language; because of this, programmers cannot use keywords as names for variables, methods, classes, or as any other identifier. Due to their special functions in the language, most integrated development environments such as NetBeans, Eclipse IDE for Java use syntax highlighting to display keywords in a different colour for easy identification.

 

Keywords Usage of Keywords
abstract In front of a `class` keyword, prevents this class to be directly instantiated. In front of a method signature, allows the implementation of this method to be deferred to an inheriting class.
assert Assert describes a predicate (a true–false statement) placed in a java-program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort. Optionally enable by ClassLoader method.
boolean Defines a boolean variable for the values “true” or “false” only (NB: “null” as in class Boolean is not allowed).
break Used to end the execution in the current loop body.
byte Defines a byte variable representing a sequence of 8 bits. (NB: Only 1-byte-characters can be used, f.i. ‘€’ would produce an error).
case A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label; see switch.
catch Used in conjunction with a try block and an optional finally block. The statements in the catch block specify what to do if a specific type of exception is thrown by the try block.
char Defines a character variable capable of holding any character of the java source file’s character set (NB: Physical storage two byte).
class A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
const Although reserved as a keyword in Java, Const is not used and has no function. For defining constants in java, see the ‘final’ reserved word.
continue Used to resume program execution at the end of the current loop body. If followed by a label, continue resumes execution at the end of the enclosing labeled loop body.
default The default keyword can optionally be used in a switch statement to label a block of statements to be executed if no case matches the specified value. It is also a type of access specifier.
do The do keyword is used in conjunction with while to create a do-while loop, which executes a block of statements associated with the loop and then tests a boolean expression associated with the while. If the expression evaluates to true, the block is executed again; this continues until the expression evaluates to false.
double The double keyword is used to declare a variable that can hold a 64-bit double precision floating-point number. This keyword is also used to declare that a method returns a value of the primitive type double.
else The else keyword is used in conjunction with if to create an if-else statement, which tests a boolean expression; if the expression evaluates to true, the block of statements associated with the if are evaluated; if it evaluates to false, the block of statements associated with the else are evaluated.
enum A Java keyword used to declare an enumerated type. Enumerations extend the base class.
extends The extends keyword indicates that you are making a new class that derives from an existing class. It is a concept from inheritance.
final Define an entity once that cannot be changed nor derived from later. More specifically: a final class cannot be subclasses, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression on an executed command. All methods in a final class are implicitly.
finally Used to define a block of statements for a block defined previously by the try keyword. The finally block is executed after execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught, or execution left method in the middle of the try or catch blocks using the return keyword.
float The float keyword is used to declare a variable that can hold a 32-bit single precision floating-point number. This keyword is also used to declare that a method returns a value of the primitive type.
for The for keyword is used to create a for loop, which specifies a variable initialization, a boolean expression, and an incrementation. The variable initialization is performed first, and then the boolean expression is evaluated. If the expression evaluates to true, the block of statements associated with the loop are executed, and then the incrementation is performed. The boolean expression is then evaluated again; this continues until the expression evaluates to false.

The for keyword can also be used to create a so-called “enhanced for loop”, which specifies an array or Iterable object; each iteration of the loop executes the associated block of statements using a different element in the array or Iterable.

 

goto Although reserved as a keyword in Java, goto is not used and has no function.
if The if keyword is used to create an if statement, which tests a boolean expression; if the expression evaluates to true, the block of statements associated with the if statement is executed. This keyword can also be used to create an if-else statement.
implements Included in a class declaration to specify one or more interfaces that are implemented by the current class. A class inherits the types and abstract methods declared by the interfaces.
import Used at the beginning of a source file to specify classes or entire Java packages to be referred to later without including their package names in the reference. The import statements can import static members of a class.
instanceof A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface.
int The int keyword is used to declare a variable that can hold a 32-bit signed two’s complement integer. This keyword is also used to declare that a method returns a value of the primitive type int.
interface Used to declare a special type of class that only contains abstract methods, constant (static final) fields and static interfaces. It can later be implemented by classes that declare the interface with the implements keyword.
long The long keyword is used to declare a variable that can hold a 64-bit signed two’s complement integer. This keyword is also used to declare that a method returns a value of the primitive type long.
native Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language.
new Used to create an instance of a class or array object. Using keyword for this end is not completely necessary (as exemplified by Scala), though it serves two purposes: it enables the existence of different namespace for methods and class names, it defines statically and locally that a fresh object is indeed created, and of what runtime type it is (arguably introducing dependency into the code).
package A group of types. Packages are declared with the package keyword.
private The private keyword is used in the declaration of a method, field, or inner class; private members can only be accessed by other members of their own class.
protected The protected keyword is used in the declaration of a method, field, or inner class; protected members can only be accessed by members of their own class, that class’s subclasses or classes from the same package.
public The public keyword is used in the declaration of a class, method, or field; public classes, methods, and fields can be accessed by the members of any class.
return Used to finish the execution of a method. It can be followed by a value required by the method definition that is returned to the caller.
short The short keyword is used to declare a field that can hold a 16-bit signed two’s complement integer. This keyword is also used to declare that a method returns a value of the primitive type short.
static Used to declare a field, method, or inner class as a class field. Classes maintain one copy of class fields regardless of how many instances exist of that class. static also is used to define a method as a class method. Class methods are bound to the class instead of to a specific instance, and can only operate on class fields. (Classes and interfaces declared as static members of another class or interface are actually top-level classes and are not inner classes.)
strictfp A Java keyword used to restrict the precision and rounding of floating point calculations to ensure portability.
super Used to access members of a class inherited by the class in which it appears. Allows a subclass to access overridden methods and hidden members of its superclass. The super keyword is also used to forward a call from a constructor to a constructor in the superclass.
switch The switch keyword is used in conjunction with case and default to create a switch statement, which evaluates a variable, matches its value to a specific case, and executes the block of statements associated with that case. If no case matches the value, the optional block labelled by default is executed, if included.
synchronized Used in the declaration of a method or code block to acquire the mutex lock for an object while the current thread executes the code. For static methods, the object locked is the class’s Class. Guarantees that at most one thread at a time operating on the same object executes that code. The mutex lock is automatically released when execution exits the synchronized code. Fields, classes and interfaces cannot be declared as synchronized.
this Used to represent an instance of the class in which it appears. this can be used to access class members and as a reference to the current instance. The this keyword is also used to forward a call from one constructor in a class to another constructor in the same class.
throws Used in method declarations to specify which exceptions are not handled within the method but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of RuntimeException must be declared using the throws keyword.
throw Causes the declared exception instance to be thrown. This causes execution to continue with the first enclosing exception handler declared by the catch keyword to handle an assignment compatible exception type. If no such exception handler is found in the current method, then the method returns and the process is repeated in the calling method. If no exception handler is found in any method call on the stack, then the exception is passed to the thread’s uncaught exception handler.
transient Declares that an instance field is not part of the default serialized form of an object. When an object is serialized, only the values of its non-transient instance fields are included in the default serial representation. When an object is deserialized, transient fields are initialized only to their default value. If the default form is not used, e.g. when a serialPersistentFields table is declared in the class hierarchy, all transient keywords are ignored.
try Defines a block of statements that have exception handling. If an exception is thrown inside the try block, an optional catch block can handle declared exception types. Also, an optional finally block can be declared that will be executed when execution exits the try block and catch clauses, regardless of whether an exception is thrown or not. A try block must have at least one catch clause or a finally block.
void The void keyword is used to declare that a method does not return any value.
volatile Used in field declarations to specify that the variable is modified asynchronously by concurrently running threads. Methods, classes and interfaces thus cannot be declared volatile, nor can local variables or parameters.
while The while keyword is used to create a while loop, which tests a boolean expression and executes the block of statements associated with the loop if the expression evaluates to true; this continues until the expression evaluates to false. This keyword can also be used to create a do-while loop.
   

Hierarchical Inheritance

In Hierarchical Inheritance, there is common Base class for more than one derived class. Below is an Example of Hierarchical Inheritance

class A8
{
	public A8(int i)
	{
		System.out.println("A8() constructor:"+i);
	}

	public void show()
	{
		System.out.println("show() in A8");
	}
}

class B8 extends A8
{
	public B8()
	{
		super(0);
		System.out.println("B8() constructor");
	}

	public void met1()
	{
		System.out.println("met1() in B8");
	}
}

class C8 extends A8
{
	public C8()
	{
		super(20);
		System.out.println("C8() constructor");
	}

	public void met2()
	{
		System.out.println("met2() in C8");
	}
}

public class HierarchicalInheritance {
public static void main(String args[])
{
	B8 obj = new B8();
	System.out.println();
	C8 obj1 = new C8();

	obj.show();
	obj.met1();

	obj1.show();
	obj1.met2();
}
}


Output:
A8() constructor:0
B8() constructor

A8() constructor:20
C8() constructor
show() in A8
met1() in B8
show() in A8
met2() in C8

You may also like to read:
Java Multilevel Inheritance
What is final class

inherit String class

String class can never be a base class, as it is declared final. Due to some optimizations taking place while creating a String object, which Developers of Java do not want Application developers to inherit from String class or override its methods. Hence String class is declared as final.

Click here for detailed description of final class

Also note that all wrapper classes like java.lang.Integer, java.lang.Float, java.lang.Short, etc… are final as well. Hence they cannot be base classes.

How to override toString() Method

As known Object class is base class of all classes in Java. Object class provides some methods, which are useful for each and every Java class. Among the methods provided by Object class toString() is one of the important method.

Below is declaration of toString() method
public String toString();

Below is an example showing how to override toString()

//Overriding toString() method
class A2{
	int i,j;

	public A2(int i,int j)
	{
		this.i = i;
		this.j = j;
	}
	
//toString() actually is being implemented in Object class
	public String toString()
	{
		return " "+i+" "+j;
	}

}


public class OverrideToString {
public static void main(String args[])
{
	A2 oa = new A2(10,20);
	System.out.println("Check Value:"+oa.toString());
}
}

Output:
Check Value: 10 20

Output of above program, on commenting toString() implementation in A1 class:
Check Value:A2@1f33675

You may also like to read: Difference between String and String Builder