Java IO Streams Interview Questions and Answers

Java IO Streams Interview Questions (or) Java IO Interview Questions
Java Io Streams: Java Io streams are used to store and read data from the files and read the data from the keyboard. A stream is a logical connection between a java program and a file. A stream can be defined as a continuous flow of data between the java program and persistence media.

1) What is Stream?

A) A stream is a logical connection between a java program and a File.
(or)
A stream can be defined as a continuous flow of data between the java program and persistence media.

2) How many types of Streams are there?

A) There are two types of Streams they are:
1) Input Stream.
2) Output Stream.

3) What is the Input Stream?

A) The Stream that allows data to come into Java application from the persistent media is called an Input Stream. Input Stream is used to read the data from persistent media.

4) What is Output Stream?

A) The Stream that allows data to send out from the Java application to be stored into the persistent media is called Output Stream. Output streams are used to write data in persistent media from a Java application.

5) How data is sent to Streams in Java?

A) In Java data is send to Streams in the format of Bytes or Characters.

6) How many types of Java Streams are there in Java?

A) There are two types of Java Streams are there in Java. They are:
1) Binary Stream.
2) Character Stream.

Java IO Streams Interview Questions (or) Java IO Interview Questions
7) What is Binary Stream?

A) The Stream which read and write data in the format of bytes is called Binary Streams.

8) What is Character Stream?

A) The Streams which read and write data in the format of characters is called Character Streams.

9) What is Sequence Input Stream?

A) This class is used to read data from multiple Input Streams Sequentially.

10) What is File InputStream?

A) File InputStream is a subclass of InputStream and Closeable, Autocloseable interfaces. File InputStream class is used to read data from a File.

Java IO Streams Interview Questions (or) Java IO Interview Questions
11) What is File OutputStream?

A) File OutputStream is a subclass of OutputStream and Closeable, Flushable, AutoCloseable interfaces. File OutputStream is used to write data to a File.

12) What are the limitations of File InputStream and File OutputStream?

A) File InputStream and File OutputStream allow User to read and write data Only in the format of bytes. It is not possible to read (or) write data in the format of primitive data or objects.

13) What is Data InputStream?

A) Data InputStream is used to read data as primitive types.

14) What is Data OutputStream?

A) Data OutputStream is used to write data as primitive types.

15) What are the limitations of Data InputStream and Data OutputStream?

A) Using Data InputStream and Data OutputStream user cannot read and write objects from persistent media. They have the capability only to read data up to primitive data types.

Java IO Streams Interview Questions (or) Java IO Interview Questions
16) What is Object InputStream?

A) Object InputStream is used to read data as an Object.

17) What is Object OutputStream?

A) Object OutputStream is used to write data as Object.

18) What is Serialization?

A) Serialization is the process of converting objects into a stream of bytes and sending them to OutputStream. Using Serialization we can store object state permanently in the destination.

19) What is Deserialization?

A) Deserialization is the process of converting a stream of bytes into the original location.

Java IO Streams Interview Questions (or) Java IO Interview Questions
20) What is Marker Interface?

A) The Interface using which user can explicitly mention (or) Mark certain properties to an Object is known as Marker Interface.

21) Explain about Transient Keyword?

A) At the time of serialization if we don’t want to save the original value of a variable then it should be declared as Transient. The transient keyword is applicable to only for variables.

Java For Loop and Types of For loops and For-each loop with the Examples

Java For Loop:
The for statement is the most commonly used looping statement. The statement includes initialization an expression that specifies an initial value for an index, and the condition expression determines whether the loop is continued or not and the last iteration expression allows the index to be modified at the end of each pass.
Types of for loops: There are two types of for loops. They are:
for() loop.
for-each loop (enhanced for loop).
Syntax of for() loop:
for(initialization; condition; iteration)
{
//codes to be Executed//
}

Java For Loop Example:
Java For Example programs:
class Forexample
{
public static void main(String[] args)
{
int i;
for(i = 1; i<=10; i++) { System.out.println(“value of i = ” +i); } System.out.println(“Example of For Loop”); } } Java For output: value of i = 1 value of i = 2 value of i = 3 value of i = 4 value of i = 5 value of i = 6 value of i = 7 value of i = 8 value of i = 9 value of i = 10 Example of For Loop Explanation of the above program: Variable of type int (integer) is declared. Now in for loop first it is initialized as 1. Now the condition is checked 1 is less than 10. So the value is printed. The loop continues until the value of “i” becomes “11” the condition (11<=10) is false so the control jumps out of for loop. In the above, we explained using Increment operator. Java For Loop using Decrement operator we use for loop: Java For loop programs: class Forexample1 { public static void main(String[] args) { int i; for(i = 4; i>=1; i–)
{
System.out.println(“value of i = ” +i);
}
}
}

Java For loop output:
value of i = 4
value of i = 3
value of i = 2
value of i = 1
For-each loop(enhanced for loop): It is a specially designed loop to iterate the elements of arrays and collections.
Syntax:
for(Type variable : array)
{
//code to be executed//

}

Java For – Each loop programs:
class ForEachExample
{
public static void main(String[] args)
{
int i[] = {1,2,3,4,5};
for(int j : i)
{
System.out.println(“j = ” +j);
}
}
}
Java For – Each loop output:
j = 1
j = 2
j = 3
j = 4
j = 5
Nested for loops: Nested for loops allow loops to be nested. That is one for loop present inside another for a loop.
Nested for loop Program in Java:
Java Nested For loop programs:
class NesExample
{
public static void main(String[] args)
{
int i,j;
for(i = 0; i < 2; i++)
{
for(j = i; j < 2; j++)
{
System.out.print(“*”);
}
System.out.println();
}
}
}
Java Nested loop output:

**
*

Switch Statement in Java | Java Switch With Examples

Switch statement in Java: If several options are available then it isn’t recommended to take nested if-else we should go for switch statement so that readability of the code will be improved. “Switch” is a keyword, by using which we can create a selection statement with multiple choices. Multiple choices can be constructed by using a “Case” keyword.
Syntax:
Switch(expression)
{
case exp1:
statements;
break;
case exp2:
statements;
break;
…………….
…………….
…………….
case expression:
statements;
break;
default:
statements;
}

Explanation: In the above syntax, switch, case, break are keywords. Expr1, expr2 is known as “case labels”. Statements inside case expression need not be closed in braces. Break statement causes an exit from the switch statement.

The following rules apply to a switch statement:
1) The expression used in a switch statement must have an integral or enumerated type.
2) You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
3) The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
4) When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
5) When the break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
6) Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
7) A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Program:
import java.util.Scanner;
class SwitchExample
{
public static void main(String[] args)
{
int number;
Scanner in = new Scanner(System.in);
System.out.println(“Enter a number”);
number = in.nextInt();
switch(number)
{
case 1:
System.out.println(“Welcome to TutorialWeb.org”);
break;
case 2:
System.out.println(“I am Java programmer”);
break;
case 3:
System.out.println(“Java programming in TutorialWeb.org”);
break;
default:
System.out.println(“Switch Program Example”);
break;
}
}
}
Output:
Enter a number
1
Welcome to TutorialWeb.org

Explanation:
1) The integer value “1” is assigned to a number variable.
2) After switch case decides then 1st case block of code gets executed.
3) Switch case executes code from top to bottom. It will validate case number with the variable number.
4) If no match is found then it will jump to the next case. It checks until found if the case is not found, the default will be executed.
Program:
import java.util.Scanner;
class SwitchMonthExample
{
public static void main(String[] args)
{
int number;
Scanner in = new Scanner(System.in);
System.out.println(“Enter a number”);
number = in.nextInt();
switch(number)
{
case 1:
System.out.println(“January”);
break;
case 2:
System.out.println(“February”);
break;
case 3:
System.out.println(“March”);
break;
case 4:
System.out.println(“April”);
break;
case 5:
System.out.println(“May”);
break;
case 6:
System.out.println(“June”);
break;
case 7:
System.out.println(“July”);
break;
case 8:
System.out.println(“August”);
break;
case 9:
System.out.println(“September”);
break;
case 10:
System.out.println(“October”);
break;
case 11:
System.out.println(“November”);
break;
case 12:
System.out.println(“December”);
break;
default:
System.out.println(“Enter number between 1 to 12”);
break;
}
}
}

Output:
Enter a number
7
July

Java Polymorphism and Types of Polymorphism in Java with Examples.

Polymorphism in Java
What is Polymorphism in Java?

Defining the multiple functions (or) methods with the same name associated with the same object is called as polymorphism.

Types of polymorphism: There are two types of polymorphism. They are:

1) Static polymorphism (or) Compile time polymorphism.

2) Dynamic polymorphism (or) Run-time polymorphism.

Static polymorphism (or) Compile time polymorphism: Defining multiple functions (or) methods with the same name within the same class by changing the data types of the parameters is called as Static polymorphism (or) Compile time polymorphism.

Example using program:

class StaticPoly
{
void fun1()
{
System.out.println(“Fun1() of Static Polymorphism”);
}
void fun1(int x)
{
System.out.println(“Fun1(int x) of Static Polymorphism”);
}
void fun1(int x, int y)
{
System.out.println(“Fun1(int x, int y) of Static Polymorphism”);
}
public static void main(String[] args)
{
StaticPoly p1 = new StaticPoly();
p1.fun1();
p1.fun1(1);
p1.fun1(1,2);
}
}

Output:

Fun1() of Static Polymorphism.
Fun1(int x) of Static Polymorphism.
Fun1(int x, int y) of Static Polymorphism.

Q) What happens in static polymorphism at the time of compilation?

A) In static polymorphism out of multiple methods with the same name the method which has to get executed would be decided at the time of compilation itself. So we call the static polymorphism as compile time polymorphism.

Rules-based on which the Polymorphism work in Java:

1) Whenever a function call is made by passing a value has an argument then JVM searches for the method defined to accept the same data type of the value that is passed.

2) There is a method defined to accept the same data type is existing JVM would not be considered any other method whose parameter value matches to the passed argument. The first priority given to the method defined to accept the same data type of the value we pass has an argument.
3) When a function call is made by passing value has an argument & if there is no method is defined to accept the data type value passed then it may reach to the alternate method.
4) The alternate method is a method where parameter value where we passed matches the argument but the data type of the parameter and the type of the value what we pass has argument would not be same.

Example:

class Poly
{
void funA(float f)
{
System.out.println(” F = ” +f);
}
void funB(boolean b)
{
System.out.println(” B = ” +b);
}
public static void main(String[] args)
{
Poly p1 = new Poly();
p1.funA(10);
}
}

Output: F = 10.0
Explanation: In the above program the statement “p1.funA(10)” the value “10” is passed to the funA(). At calling position first the value “10” with an integer is not declared so it passed to the void funA(float f). Where float is alternate method is acceptable to the Integer value we passed.
Dynamic polymorphism (or) Run-time polymorphism: Defining functions (or) methods in the subclass with the same name and the same signature of the superclass function is called as method overloading (or) Dynamic polymorphism.
Example:
Super class program:
class A
{
int i,j;
void funA()
{
System.out.println(“FunA() of A”);
}
}
Sub class program:
class D extends A
{
int i,x;
void funA()
{
System.out.println(“FunA() of class B”);
}
public static void main(String[] args)
{
D b1 = new D();
b1.funA();
}
}

Output:

FunA() of class B.

Explanation: Whenever we are over-riding a superclass method in sub-class the signature and the prototype of the sub-class method must be the same has super-class method without which where a compilation error would occur. Whatever the rules permitted in static polymorphism is also applicable in method over-riding.
Note: In Dynamic polymorphism, multiple methods with the same name & with the same data types of the parameters has to get executed would be decided dynamically at the runtime based conditions.

Class and Object in Java with Programs and Examples

Class and objects
Why do we need a class in Java?
Java is an object-oriented programming language and represents data in the form of Objects. So in order to create an object, we required a class.
What is a class?
A class is user-defined data type in Java & is a Structure representing data and logic.
(or)
A class is a specification or blueprint or template of an object. A class defines the structure, state and behavior mean data & code that can be shared by a set of objects.
The data defined by the class are referred to as member variables or instance variables or attributes.

Syntax to declare a class:
Class
{
Type instance variable 1;
Type instance variable 2;
…..……………………………….
Type instance variable N;

Type methodname1(parameter list)
{
//body of method//
}
Type methodname2(parameter list)
{
//body of method//
}
……………………………………
Type methodnameN(parameter list)
{
//body of method//
}
}

Declaring a variable: In Java, all variables must be declared they can be used.
Variable declaration is shown below:
Type identifier [ = value], identifier [ = value], ………;
Example:
int a, b, c; // declares three integers a, b, c;
int i = 1, j = 2, k; //declares three more integers & initializing i & j;

Class Example:
Class A
{
int i,j;
Void funA()
{
System.out.println(“FunA() of class A”);
}
}
Understanding the above program:
1) Where “A” is the name of the class.
2) “i& j” are instance variables.
3) “funA()” is the name of the method (or) function.

Q) What is Next?
a) Object.

Why do we need an Object?
In order to load the members of the class(means instance variables, methods) from the byte code to the Ram in the form of executable format and make them available to the program which is under execution. Without using the concept of an object, we can’t load the members of the class from the byte code to the RAM at the runtime.
What is an object?
An object is an instance of a class. The memory space which is allocated for the members of a class, dynamically at the runtime can be called as an object.

What is the Instance?
Any dynamic memory allocation can be called as an Instance. That is memory space allocated for anything during runtime can be called as an Instance.

Syntax to declare Object:

<Class Name>   ClassObjectReference = new <Class Name>();

Ways to create Object: There are various ways to create an Object. The most commonly used and the simple and easiest way to create Object is using New keyword;
Example:

class Objectexample
{
public static void main(String[] args)
{
Objectexample e = new Objectexample();
System.out.println(“Example of Object using th new keyword”);
System.out.println(“E=”+e);
}
}

Output:
Example of Object using the new keyword
E = Objectexample@42e922

Types of Objects In Java:
In Java, we have two types of objects base on the referenced variables. They are:
1) Referenced (or) Reachable Object.
2) In-referenced (or) Un-reachable Object.

Referenced (or) Reachable Object: If an object is pointed by at least one referenced variable, it is called Referenced (or) Reachable object.
Example of Referenced Objetc creation :
ObjectExample e = new ObjectExample();
Program of Referenced (or) Reachable Object:
class Objectexample
{
public static void main(String[] args)
{
Objectexample e = new Objectexample();
System.out.println(“Example of Referenced Object”);
System.out.println(“E=”+e);
}
}

Output:
Example of Referenced Object
E = Objectexample@52e922

Un-Referenced (or) Un-Reachable Object: If an object is not pointed by at least one referenced variable, it is called Un-Referenced (or) Un-Reachable object.
Example of Un-Referenced Object creation: new Object Example();
Program of Un-Referenced (or) Un-Reachable Object:
class Objectexample1
{
public static void main(String[] args)
{
new Objectexample1();
System.out.println(“Example of Un-Referenced Object”);
System.out.println(“E=”+ new Objectexample1());
}
}

Output:
Example of Un-Referenced Object
E = Objectexample1@52e922
The Five different locations where we can define Objects in Java are:
1) Defining Object has local to a function.
2) Defining Object has an instance variable (or) Non-static member of a class.
3) Defining Object has the parameter of the function.
4) Defining Object has a return data type of the function.
5) Defining Object has a Static variable of the class.
Defining Object has local to a function:
class Demo1
{
int x,y;
void fun1()
{
x = x + 1;
A a1 = new A();
a1.i = x + 1;
}
public static void main(String[] args)
{
A a1 = new A();
Demo1 d1 = new Demo1();
d1.x = 2;
System.out.println(“a1.i = “+ a1.i);
System.out.println(“d1.x = “+ d1.x);
}
}

Output:
a1.i = 0;
a1.x = 2;

Defining Object has an instance variable (or) Non-static member of a class.

class Demo2
{
int x = 1;
A a1 = new A();
public static void main(String[] args)
{
Demo2 d1 = new Demo2();
System.out.println(d1.a1);
System.out.println(d1.a1.i);
d1.a1.funA();
}
}

Output:

A@522e34
0
funA() of A

Defining Object has a parameter of the function.
class Demo3
{
void fun1(int x)
{
int sq = x*x;
System.out.println(“sq = ” +sq);
}
public static void main(String[] args)
{
Demo3 d1 = new Demo3();
d1.fun1(5);
int x = 7;
d1.fun1(x);
}
}

Output:

sq = 25
sq = 49

Defining Object has return data type of the function:
class Demo4
{
int getSq(int x)
{
int sq = x * x;
return(sq);
}
public static void main(String[] args)
{
Demo4 d1 = new Demo4();
int x = d1.getSq(2);
System.out.println(“X = ” +x);
System.out.println(d1.getSq(4));
int y = d1.getSq(5) + 2;
System.out.println(“Y = ” +y);
}
}

Output:

x = 4
16
y = 27

Defining Object has a Static variable of the class.
Program 1:
class Demo5
{
static int x = 1;
static A a1 = new A();
}
Program 2:
class Demo6
{
public static void main(String[] args)
{
System.out.println(Demo5.x);
System.out.println(Demo5.a1);
System.out.println(Demo5.a1.i);
Demo5.a1.funA();
}
}
Output:
1
A@527e33
0
funA() of A

Java Constructor | Types of Constructor in Java with Examples.

What is Constructor in Java?
A constructor is a Functionality (or) method which is Executed automatically at the time of the creation of the Object.

Why we require Constructor in Java?
A constructor is required for creating and initializing Object in Java.

Rules to define Constructor:
1) Constructor name should be same as the Class name.
2) A constructor should not contain modifiers.
3) A constructor cannot contain return type.
4) In Constructor logic return statement with the value is not allowed.
5) The constructor must be called along with “new” keyword or else it leads to a compile-time error.

Syntax to declare Constructor:

<Class Name>()
{
}

Example:

Class A
{
A()
{
System.out.println(“Constructor Example”);
}
public static void main(String[] args)
{
A a1 = new A();
}
}

Output: Constructor Example.

Types of Constructors: There are “3” types of constructors in Java. They are:

1) Default Constructor.
2) No-argument Constructor (or) Non-parameterized Constructor.
3) Parameterized Constructor.

Default Constructor: The Zero-argument (or) No-argument Constructor generated by Compiler is called as Default Constructor.

In detail: At the time of Compilation, the compiler checks whether the class has at least one constructor or not if the compiler finds that the class doesn’t have at least one constructor then compiler automatically provides a Zero argument (or) No-argument constructor to the class is called as Default constructor.

Example of Default Constructor:
class A
{
int i,j;
void funA()
{
System.out.println(“FunA() of A”);
}
}

To see Compiler generated constructor.
1) First, write any Java program without Constructor.
2) Compile the Java program in command prompt (Example using above Class A program (type javac .java) in command prompt).
Example: javac A.java
3) To see default constructor (type javap ) in command prompt.
Example: javap A

Compiler generated output:

Class A
{
int i;
int j;
A();
Void funA();
}

In the above Compiler generated output A() is the default constructor.
Why compiler-generated Constructor is called as Default Constructor?
A) It Obtains all its default properties from its Class. They are:
1) Its name is the same as its class name.
2) It does not have parameters and logic.
3) Its accessibility modifier is the same as its class accessibility modifier.

No-argument Constructor (or) Non-parameterized Constructor: The developer generated constructor without parameters is called as No-argument Constructor (or) Non-parameterized Constructor. A Constructor is compulsory in a class but No-argument Constructor is not mandatory in a class.

Example of No-argument Constructor:

class B
{
int i,j;
B()
{
System.out.println(“FunB() of Class B”);
}
public static void main(String[] args)
{
B b1 = new B();
}
}

Output:
FunB() of Class B

Difference between the No-argument and Default Constructor?

Default Constructor:

1) It is generated by the compiler.
2) Its accessibility modifier is same as class accessibility modifier. So the only allowed accessibility modifiers are default or public.
3) It does not have logic except super() call.

No-argument:
1) It is defined by the developer.
2) It can have all four accessibility modifiers as it is defined by the developer, so the allowed accessibility modifiers are private, default, public, protected.
3) It can have logic including super() call.

Parameterized Constructor: The developer generated Constructor with parameters is called as Parameterized constructor. The parameterized constructors may contain logic also.

Example:

class C
{
int a,b;
C(int x)
{
a = x;
b = x + 1;
System.out.println(“Example of Parameterized constructor”);
System.out.println(“c(int x)”);
}
C(int x, int y)
{
a = x;
b = y;
System.out.println(“c(int x, int y)”);
}
C(boolean f)
{
System.out.println(“c(boolean f)”);
}
public static void main(String[] args)
{
C c1 = new C(3);
System.out.println(“a = ” + c1.a + ” b = ” + c1.b);
System.out.println();
C c2 = new C(3,5);
System.out.println(“a = ” + c2.a + ” b = ” + c2.b);
System.out.println();
C c3 = new C(true);
System.out.println(“a = ” + c3.a + ” b = ” + c3.b);
}
}

output:

Example of Parameterized constructor
c(int x)
a = 3 b = 4

c(int x, int y)
a = 3 b = 5

c(boolean f)
a = 0 b = 0

Constructor overloading: Defining multiple constructors within the same class by changing the data types of the parameters is called Constructors overloading. Like methods, constructors can also be overloaded but they cannot be overridden because constructors are not inherited, we cannot create a constructor in a subclass with superclass name.
The rules applicable in static polymorphism all those rules are applicable in Constructor overloading also.
Example of Constructor overloading:

class Conexample
{
Conexample()
{
System.out.println(“Example of constructor overloading”);
System.out.println(“Example of No-argument constructor overloading”);
}
Conexample(int x)
{
System.out.println(“Example of int argument”);
}
Conexample(String s1)
{
System.out.println(s1 + ” Example of String argument”);
}
public static void main(String[] args)
{
Conexample c1 = new Conexample();
Conexample c2 = new Conexample(7);
Conexample c3 = new Conexample(“Tutorials Web”);
}
}

Output:
Example of constructor overloading
Example of No-argument constructor overloading
Example of int argument
Tutorials Web Example of String argument

Calling one constructor from another Constructor: We can call a Constructor from another Constructor using “this” Keyword.
Example:
class Cdemo
{
Cdemo()
{
this(2);
System.out.println(“Cdemo()”);
}
Cdemo(int x)
{
this(x,x+2);
System.out.println(“Cdemo(int x)”);
}
Cdemo(int x,int y)
{
System.out.println(“Cdemo(int x,int y)”);
}
public static void main(String[] args)
{
Cdemo c = new Cdemo();
}
}

Rules for calling Constructor Explicitly from another Constructor:
1) The statement which explicitly calls a constructor must be the first statement in a Constructor.
2) The statement which explicitly calls a constructor should be present only inside a constructor and it cannot be called through a method.
Constructor Chaining: Calling one constructor from another constructor using super() and this() is called as Constructor Chaining. Subclass constructors are chained with superclass constructors by using super() and subclass overloaded constructors are chained by using this().

Example:
class Cdemo2
{
Cdemo2()
{
this(8);
System.out.println(“Constructor chaining Example”);
System.out.println(“No-argument constructor”);
}
Cdemo2(int i)
{
this(“Tutorials web”);
System.out.println(“Parameter constructor”);
}
Cdemo2(String s)
{
System.out.println(“String argument constructor”);
}
}

class Cdemo3 extends Cdemo2
{
Cdemo3()
{
this(8);
System.out.println(“No-argument constructor”);
}
Cdemo3(int i)
{
this(“Tutorials web”);
System.out.println(“Parameter constructor”);
}
Cdemo3(String s)
{
System.out.println(“String argument constructor”);
}
}
class Ctest
{
public static void main(String[] args)
{
new Cdemo3();
new Cdemo3(7);
new Cdemo3(“Tutorials Web”);
}
}

Output:

String argument constructor
Parameter constructor
Constructor chaining Example
No-argument constructor
String argument constructor
Parameter constructor
No-argument constructor
String argument constructor
Parameter constructor
Constructor chaining Example
No-argument constructor
String argument constructor
Parameter constructor
String argument constructor
Parameter constructor
Constructor chaining Example
No-argument constructor
String argument constructor.

Java Print with examples and programs

Print in Java: The print() method prints the required output on the same line continuously again and again on the screen. The print is a method present in PrintStream Class present in Java.io.package.

There are 8 Print methods in PrintStream Class. They are:
1) void print(Boolean b): Prints a Boolean value.
2) void print(char c): Prints a character.
3) void print(char[] s) : Prints an array of characters.
4) void print(double d): Prints a double-precision floating-point number.
5) void print(float f) : Prints a floating-point number.
6) void print(int i) : Prints an integer.
7) void print(long l): Prints a long integer.
8) void print(Object obj) : Prints an object.
9) void print(String s): Prints a string.

Example of Program:

class PrintExample{                 
public static void main(String args[]) 

System.out.print(“Int statement. “); 
System.out.print(“Double statement. “); 
System.out.print(“String statement.”);
  }
}

Output:
Int statement. Double statement. String statement.
What is the difference between System.out.println() and System.out.print() in Java?
println(): println() method places the cursor in the next line after printing the current output. So the next output will be printed in the next line.
Print(): Print() method places the cursor in the same line after printing current output. So the next output will also be printed in the same line.
Example using both System.out.println() and System.out.print() methods:

Java program to print pyramid:

import java.io.*;import java.util.*;class PyramidExa{  public static void printPyramid(int n)  {  int i, j;  for(i=0; i<n; i++)   {    for(j=0; j<=i; j++)     {      System.out.print(“* “);     }      System.out.println();   }  }public static void main(String args[]){ Scanner in = new Scanner(System.in);  System.out.println(“Enter the number”);  int n = in.nextInt(); printPyramid(n);}}

Output:

Enter a number7
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

Explaining in detail about the System.out.print() method:


System: System is the name of the class present in java.lang package.
Out: out is an object of print stream class and declared as static in System class. Present in java.lang package.
Print(): print() is a method of the PrintStream class. Present in the java.io package.

what is system.out.println in Java?

what is system.out.println in Java?

System.out.println is a Java statement that prints the argument passed into the console which is generally standard output.
In detail:
1) A system is the name of the class in java.lang package.
2) out is an object of print stream class and declared as static in System class. Present in java.lang package.
3) println() is a method of the PrintStream class. Present in the java.io package.


Explaning System.out.println using Java Programs:
Class A Program:

Class A Program:

class A{ int i,j; void funA() {  System.out.println(“FunA() of A”); }}

Class Sdemo program:

class Sdemo{ static int i = 1; static A a1 = new A();}

Class Test program:

class Test{ public static void main(String[] args) {  System.out.println(Sdemo.i);  System.out.println(Sdemo.a1);  Sdemo.a1.funA(); }}

In the above program look at the Sdemo.a1.funA();
1) Sdemo is the name of the class.
2) a1 is the object of Class A which is declared as static in Sdemo class.
3) funA() is a method of A class. Like Sdemo.a1.funA(); System.out.println() is also declared.

Java String Interview Questions and Answers

Java String Interview Questions and Answers

1) What is the difference between creating an object of string class using the new operator and using doubles quotes?
A) Using double quotes object of the string class representing a specific sequence of characters could be created only once. Whereas using new operator we can create any number of String class objects representing the same sequence of characters.

2) Explain about concatenation operator (+) in Java Strings?
A) The functionality of the concatenation operator is to create a new String class object with the data present at the left-hand side and right-hand side.

3) What is String Buffer?
A) String Buffer is like a String but can be modified in the same memory location. Every method of the String Buffer class would be changing the data within the same object and returns the address of the same object.

4) What is the String Builder?
A) String Builder is a mutable sequence of characters. String Builder class is designed for use as a drop-in replacement for StringBuffer in places where the String buffer was being used by a single thread.

5) What is the default capacity of String?
A) Strings do not have default capacity. The passed String length is its capacity.

6) What is the default capacity of String Buffer?
A) String Buffer has default capacity as 16 buffers. It increases its capacity automatically when sizes reach maximum using its capacity formula ( ( current capacity * 2 ) + 2).

7) In how many ways we can concat String in Java?
A) Using String object, we can concat new string to the current in two ways.
1) using + operator.
2) using concat() method.

8) In how many ways we can concat String Builder in Java?
A) Using String Buffer we can perform concat operation only in one way.
1) using append() method.

9) What is toString() method?
A) If you want to represent an object as a string, toString() method is used.

10) What is the advantage of the toString() method?
A) By overriding the toString() method of the object class, we can returns the values of the object.

11) What is the use of the charAt() method?
A) CharAt() method returns the character at the specified location.
Example:
String name = “TutorialsWeb”
Char ch = name.charAt(7);

12) What are the interfaces String class Implements?
A) String class implements “3” interfaces in Java. They are:
1) Serializable.
2) charsequence.
3) comparable.

13) Is String class final in Java?
A) Yes. String class is declared as final in Java.

14) What is difference between equals() and “ == ” operator?

A) The equals() method compares the characters inside a String object. The “==” operator compares two object references to see whether they refer to the same instance.

15) Is String thread-safe in Java?
A) Since String is immutable, it is threaded safe and it can be shared between multiple threads without external synchronization.

16) Why java uses the concept of String literal?
A) To make Java more memory efficient, because no new objects are created if it exists already in string constant pool.

17) What is the String Constant pool (String literal pool)?
A) String Constant pool is a separate block of memory where the string objects are held by JVM.

18) Explain the difference between the following statements?
String s = “Hello”;
String s = new String(“Hello”);
A) In first statement assignment operator is used to assign the string. In this case, JVM first checks the String pool whether the same value is already available in the String container or not, if available then it creates another reference to it, if not available then it creates the new one.
In the second case each and every time it creates a new object of string.

19) How to concat two different String?
A) We can concat two different Strings with the help of “+” assignment operator or concat() method of String class.

20) What do you mean by immutability?
A) Immutability means once an object is initialized we can’t change.

21) What is the String pool in Java?
A) String pool is a special storage area in java heap, mostly located on Bergen space, to store string literals like “ABC”. When Java program creates a new string using String literal, JVM checks for that string in the pool and, if string literal is already present in the pool then the same object is returned instead of creating a whole new object. String pool check is performed only when you create a string as literal, if you create String using the new() operator, a new String object will be created even if String with the same content is available in the pool.

22) How to make a class immutable in java?
A) 1) Make a class final or private.
2) Remove constructor.
3) Allow only the getter method in your class.

23) What is the difference between String and StringBuffer classes?
A)
String:
1) String class object is immutable hence there contain cannot be modified.
2) The method that directly manipulates data of the object in String class.
3) Append(),reverse() method not available in String class.

StringBuffer:

1) StringBuffer object is mutable so they can be modified.
2) Such methods are available in String class.
3) Append(),reverse() method available in StringBuffer class.

24) There are any other classes in java that is immutable?
A) All the wrapper classes in Java are immutable like Integer, Float, Double etc.

25) What is the String Tokenizer class?
A) String Tokenizer class is used to break the string in the form of tokens.

26) There is an alternative to string Tokenizer?
A) The String class is an alternative of string tokenizer, with the help of split() method of string.

27) What is the difference between StringBuffer and StringBuilder?
A) StringBuffer is synchronized and StringBuilder is not.

28) How to convert Integer to String?
A) With the help of toString() method of String class.

29) The string is Thread safe or not?
A) Yes, String is thread safe because string object is immutable that’s way string is thread safe.

30) What is difference between compareTo() and equals() method?
A) compareTo(): compareTo() method is provided by java.lang.String package that checks the difference string to the character by character if both the strings are same then return 0 otherwise it returns (-value) for each character.
Equals(): Equals() method is a java.object package Object class method that checks the two different object and returns true or false.

31) How to convert Integer to String?
A) There are many ways but two ways are shown below:
1) String s = 7 + “ ”;
2) String s = String.valueOf(7);

In the first case, JVM consumes a lot of space for memory. In the second case, JVM does not consume memory.

Java Exception Handling Interview Questions and Answers

Java Exception Handling Interview Questions

1) How many types of errors are there in Java?

A) There are two types of errors are there in Java:
1) Compilation error.
2) Run-time error.

2) What is a compilation Error?

A) Any error that occurs at the time of compilation could be called as Compilation Error.

3) What is Run-time Error?

A) Any Error that occurs at the time of execution of the program could be called as Run-time Error.

4) What is logical Error?

A) Any wrong logic which leads for the wrong outputs could be called as a logical Error.

5) What is Abnormal Termination?

A) Terminating any program in the middle of its execution and controlling coming out of the application (or) program without executing the last statement of the main method is known as Abnormal Termination.

6) What is Exception?

A) Exceptions are the objects representing logical Errors and Run-time Errors.

7) What is Exception handling?

A) The concept of identifying an exception and catching that exception and assigning that exception to the reference of the corresponding exception class is known as Exception Handling.

8) What is Hard coding?

A) The concept of using values directly is called Hard coding.

9) What are two types of Logical Errors?

A) There are two types of Logical Errors. They are:
1) Simple Logical Errors.
2) Serious Logical Errors.

10) Explain simple logical Errors?

A) All the Logical Errors which could be neglect by the JVM are called Simple Logical Errors.

11) Explain about Serious Logical Errors?

A) All the logical Errors (or) the run-time errors which could not be neglect by the JVM is Known as Serious Logical Errors.

12) How many types Java Exceptions are divided?

A) All the Exceptions are divided into two types. They are:
1) Checked Exceptions.
2) Un-checked Exceptions.

13) Explain about Checked Exceptions?

A) All the Exceptions which are not the sub-class of Run-time Exceptions are known as Checked Exceptions.

14) Explain about Un-Checked Exceptions?

A) All the Exceptions which are the sub-class of Run-time Exceptions are known as Un-Checked Exceptions.

15) What is the difference between “Throws” and “Throw”?

A) Using throws we can only Explicitly provide the information about the unhandled Exceptions to the Java compiler and JVM and end user. But whereas using throw we would be Explicitly raising an Exception representing the user-defined Run-time errors.

16) Explain about Try Keyword?

A) Try: Try establishes a block to write a code that causes exceptions and its related statements. Exception causing statement must be placed in a try block to be handled and catch that exception for stopping abnormal termination.

17) Explain about Catch Keyword?

A) The catch block is used to catch exceptions those are thrown from its corresponding try block. It has logic to take necessary action on that caught exception.

18) Explain about Final block?

A) Final establishes a block that definitely executes statements placed in it. Statements which are placed in this block are always executed irrespective of the way the control is coming out from the try block either by completing normally, by return statements or by throwing an exception, by catching or not catching.

19) What is Exception propagation?

A) The process of sending exception from called method to calling method is called as Exception propagation.

20) Explain the uses of Throws Keyword?

A) 1) Using throws keyword we provide the complete information about the unhandled Exceptions to the user and to the Java compiler.
2) Using throws keyword we can avoid try & catch blocks with respect to the statements proven to generate Checked Exceptions in a method.

23) Explain about Finally?

A) Finally, blocks can be executed compulsory with irrespective of Exceptions.

24) Explain the uses of the Finally block?

A) The two uses of Finally block are:
1) Using Finally block we can maintain proper separation between the statements belonging to the try, catch and the statements belonging to the function.
2) Using Finally blocks we can avoid catch blocks.

25) When it is mandatory to call a method inside try & catch blocks?
A) Whenever a method uses throws keyword and mentions the name of the checked Exception then it is mandatory to call that method inside the try-catch without which a compilation error occurs.