Java Questions
Java Questions
Simple
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
There are two types of platforms software-based and hardware-based. Java provides
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
1. Runtime Environment
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is
a platform-independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).
Secured
o No explicit pointer
o Java Programs run inside virtual machine sandbox
o Classloader: adds security by separating the package for the classes of the local
file system from those that are imported from network sources.
o Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: determines what resources a class can access such as
reading and writing to the local disk.
These security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.
Architecture-neutral
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for
both 32 and 64 bit architectures.
Portable
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine
on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications etc.
Q2)Write a short note on jvm?
ava Literals are syntactic representations of boolean, character, numeric, or string data. Literals
provide a means of expressing specific values in your program. For example, in the following
statement, an integer variable named count is declared and assigned an integer value. The
literal 0 represents, naturally enough, the value zero.
Code section 3.61: Numeric literal.
1 int count = 0;
The code section 3.62 contains two number literals followed by two boolean literals at line 1, one
string literal followed by one number literal at line 2, and one string literal followed by one real
number literal at line 3:
There are no other boolean literals, because there are no other boolean values!
Numeric Literals[edit]
Integer Literals[edit]
1. As decimal numbers such as 1995, 51966. Negative decimal numbers such as -42 are
actually expressions consisting of the integer literal with the unary negation operation -.
2. As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits
between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for
example 037777777770 is actually the decimal value -8.
3. As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal
digits (digits from 0 to 9, a to f or A to F). For example, 0xCAFEBABEL is the long integer
3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.
4. Starting in J2SE 7.0, as binary numbers, using the form 0b (or 0B) followed by one or more
binary digits (0 or 1). For example, 0b101010 is the integer 42. Like octal and hex numbers,
binary literals may represent negative numbers.
By default, the integer literal primitive type is int. If you want a long, add a letter el suffix
(either the character l or the character L) to the integer literal. This suffix denotes a long
integer rather than a standard integer. For example, 3405691582L is a long integer literal.
Long integers are 8 bytes in length as opposed to the standard 4 bytes for int. It is best
practice to use the suffix L instead of l to avoid confusion with the digit 1 (one) which looks
like l in many fonts: 200l ≠ 2001. If you want a short integer literal, you have to cast it.
Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are
ignored but may help readability by allowing the programmer to group digits.
1. an optional leading + or - sign, indicating a positive or negative value; if omitted, the value is
positive,
2. one of the following number formats
o integer digits (must be followed by either an exponent or a suffix or both, to
distinguish it from an integer literal)
o integer digits .
o integer digits . integer digits
o . integer digits
3. an optional exponent of the form
o the exponent indicator e or E
o an optional exponent sign + or - (the default being a positive exponent)
o integer digits representing the integer exponent value
4. an optional floating point suffix:
o either f or F indicating a single precision (4 bytes) floating point number, or
o d or D indicating the number is a double precision floating point number (by default,
thus the double precision (8 bytes) is default).
Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are
ignored but may help readability by allowing the programmer to group digits.
Character Literals[edit]
Character literals are constant valued character expressions embedded in a Java program.
Java characters are sixteen bit Unicode characters, ranging from 0 to 65535. Character literals
are expressed in Java as a single quote, the character, and a closing single quote ('a', '7',
'$', 'π'). Character literals have the type char, an unsigned integer primitive type.
Character literals may be safely promoted to larger integer types such as int and long.
Character literals used where a short or byte is called for must be cast to short or byte
since truncation may occur.
String Literals[edit]
String literals consist of the double quote character (") (ASCII 34, hex 0x22), zero or more
characters (including Unicode characters), followed by a terminating double quote character
("), such as: "Ceci est une string."
<STRING :
"\""
( (~["\"","\\","\n","\r"])
|("\\"
( ["n","t","b","r","f","\\","'","\""]
|["0"-"7"](["0"-"7"])?
|["0"-"3"]["0"-"7"]["0"-"7"]
)
)
)*
"\"">
Within string and character literals, the backslash character can be used to escape special
characters, such as unicode escape sequences, or the following special characters:
String literals may not contain unescaped newline or linefeed characters. However, the Java
compiler will evaluate compile time expressions, so the following String expression results in
a string with three lines of text:
null[edit]
null is a special Java literal which represents a null value: a value which does not refer to
any object. It is an error to attempt to dereference the null value — Java will throw a
NullPointerException. null is often used to represent uninitialized state.
CALL BY VALUE:
class Hello
{
void disp(int i,int j)
{
i*=2;
j/=2;
}
}
class T7
{
public static void main(String as[])
{
int a=99;
int b=77;
System.out.println("before call");
System.out.println("a="+a);
System.out.println("b="+b);
}
}
OUTPUT:
before call
a=99
b=77
AFTER call
a=99
b=77
When you pass a simple type to a method, it is passed by value. Thus what occurs to the
parameter that receives the argument has no effect outside the method. Here the
operation occur inside disp() have no effect on the values of a and b used in the call.
Their values didn't change to 198 and 38.
CALL BY REFERENCE:
class Hello
{
int a,b;
Hello(int i,int j)
{
a=i;
b=j;
}
void disp(Hello o) //pass an object
{
o.a*=2;
o.b/=2;
}
}
class T6
{
public static void main(String as[])
{
Hello h=new Hello(15,20);
System.out.println("before call");
System.out.println("a="+h.a);
System.out.println("b="+h.b);
h.disp(h);
System.out.println("AFTER call");
System.out.println("a="+h.a);
System.out.println("b="+h.b);
}
}
OUTPUT:
before call
a=15
b=20
AFTER call
a=30
b=10
When you pass an object to a method the situation change dramatically. Because objects
are passed by Reference. When you creating a variable of a class type , you are only
creating a reference to an object. change to the object inside the method do effect the
object used as an argument. When object reference is passed to a method, the reference
itself is passed by use of call-by-value.
The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the class than instance of the class.
3. block
4. nested class
o The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of
students etc.
o The static variable gets memory only once in class area at the time of class
loading.
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is created.All student have its unique rollno and name so
instance data member is good.Here, college refers to the common property of all
objects.If we make it static,this field will get memory only once.
Java static property is shared to all objects.
o A static method can be invoked without the need for creating an instance of a
class.
o static method can access static data member and can change the value of it.
o //Program to get cube of a given number by static method
o
o class Calculate{
o static int cube(int x){
o return x*x*x;
o }
o
o public static void main(String args[]){
o int result=Calculate.cube(5);
o System.out.println(result);
o }
o }
Output:125
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
Ans) because object is not required to call static method if it were non-static method,
jvm create object first then call main() method that will lead the problem of extra
memory allocation.
Hello main
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }
Test it Now
Output:Error: Main method not found in class A3, please define the main method as:
To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.
1) By nulling a reference:
3) By annonymous object:
1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
1. public static void gc(){}
There are many differences between method overloading and method overriding in java.
A list of differences between method overloading and method overriding are given below:
5) In java, method overloading can't be performed by changing return Return type must be s
type of the method only. Return type can be same or different in method overriding.
method overloading. But you must have to change the parameter.
A class declared inside a class is known as nested class. We use nested classes to logically
group classes in one place so that it can be more readable and maintainable code.
Moreover, it can access all the members of outer class including private members.
class OuterClass {
...
class NestedClass {
...
}
difference between nested class and inner class?
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static
are simply called static nested classes. Non-static nested classes are called inner classes. Inner class is a
part of nested class. Non-static nested classes are known as inner classes.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are declared private. Static nested classes do not have
access to other members of the enclosing class. As a member of the OuterClass, a nested class can be
declared private, public, protected, or package private. (Recall that outer classes can only be declared
public or package private.)
1. It is a way of logically grouping classes that are only used in one place.
2. It increases encapsulation.
3. Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed
it in that class and keep the two together. Nesting such “helper classes” makes their package more
streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to
members of A that would otherwise be declared private. By hiding class B within class A, A’s
members can be declared private and B can access them. In addition, B itself can be hidden from the
outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code
closer to where it is used.
Types of Nested class:
There are two types of nested classes non-static and static nested classes.The non-static nested classes are
also known as inner classes.
1. non-static nested class(inner class)
a)Member inner class
b)Annomynous inner class
c)Local inner class
2. static nested class
Static Nested Classes
As with class methods and variables, a static nested class is associated with its outer class. And like static
class methods, a static nested class cannot refer directly to instance variables or methods defined in its
enclosing class — it can use them only through an object reference.
Note: A static nested class interacts with the instance members of its outer class (and other classes) just
like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been
nested in another top-level class for packaging convenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class
and has direct access to that object’s methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the
following classes:
class OuterClass {
...
class InnerClass {
...
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance. The next figure illustrates this idea.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within
the outer object with this syntax:
Additionally, there are two special kinds of inner classes: local classes and anonymous classes.
Q9)Define?
1) Byte code?
Java bytecode is the result of the compilation of a Java program, an
intermediate representation of that program which is machine independent.
The Java bytecode gets processed by the Java virtual machine (JVM) instead
of the processor. It is the job of the JVM to make the necessary resource calls
to the processor in order to run the bytecode.
Java bytecode is the result of the compilation of a Java program, an
intermediate representation of that program which is machine independent.
The Java bytecode gets processed by the Java virtual machine (JVM) instead
of the processor. It is the job of the JVM to make the necessary resource calls
to the processor in order to run the bytecode.
2) class?
o fields
o methods
o constructors
o blocks
o nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
3) Object?
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen,
table, car etc. It can be physical or logical (tangible and intangible). The example of
intangible object is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
Object Definitions:
4) Constructor?
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called parent or super class and
the new class is called child or subclass.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
Single Inheritance Example
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error now.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now