0% found this document useful (0 votes)
71 views23 pages

Java Intrvw Cncpts Details Extra

The document discusses variables and data types in Java. There are three types of variables: local, instance, and static. Java has two types of data types - primitive (boolean, char, byte, short, int, long, float, double) and non-primitive. The sizes and default values of the primitive data types are also listed.

Uploaded by

Ashish Gulshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views23 pages

Java Intrvw Cncpts Details Extra

The document discusses variables and data types in Java. There are three types of variables: local, instance, and static. Java has two types of data types - primitive (boolean, char, byte, short, int, long, float, double) and non-primitive. The sizes and default values of the primitive data types are also listed.

Uploaded by

Ashish Gulshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

next prev

Variable and Datatype in Java


1. Variable
2. Types of Variable
3. Data Types in Java
In this page, we will learn about the variable and java data types. Variable is a name of
memory location. There are three types of variables: local, instance and static. There are
two types of datatypes in java, primitive and non-primitive.

Variable
Variable is name of reserved area allocated in memory.

1.

int data=50;//Here data is variable

Types of Variable
There are three types of variables in java
local variable

instance variable

static variable

Local Variable
A variable that is declared inside the method is called local variable.

Instance Variable
A variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.

Static variable
A variable that is declared as static is called static variable. It cannot be local.
We will have detailed learning of these variables in next chapters.

Example to understand the types of variables


1.
2.
3.
4.
5.
6.
7.

class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class

Data Types in Java

In java, there are two types of data types


primitive data types

non-primitive data types

Data Type

Default Value

Default size

boolean

false

1 bit

char

'\u0000'

2 byte

byte

1 byte

short

2 byte

int

4 byte

long

0L

8 byte

float

0.0f

4 byte

double

0.0d

8 byte

Why char uses 2 byte in java and what is \u0000 ?


because java uses unicode system rather than ASCII code system. \u0000 is the lowest
range of unicode system.To get detail about Unicode see below.

JVM (Java Virtual Machine)


1. Java Virtual Machine
2. Internal Architecture of JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform
dependent).

What is JVM?
It is:
1. A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its implementation
has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, and instance of JVM is created.

What it does?
The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

1) Classloader:
Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area:
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.

3) Heap:
It is the runtime data area in which objects are allocated.

4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Register:


PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack:


It contains all the native methods used in the application.

7) Execution Engine:
It contains:
1) A virtual processor
2) Interpreter:Read bytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation.Here the term ?compiler? refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction set
of a specific CPU.

Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.

Why java uses Unicode System?

Before Unicode, there were many language standards:

ASCII (American Standard Code for Information Interchange) for the United
States.

ISO 8859-1 for Western European Language.

KOI-8 for Russian.

GB18030 and BIG-5 for chinese, and so on.

This caused two problems:


1. A particular code value corresponds to different letters in the various language
standards.
2. The encodings for languages with large character sets have variable length.Some
common characters are encoded as single bytes, other require two or more byte.
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


1.

<class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
1.
2.
3.
4.
5.
6.

class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Test it Now
Output:
Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc. depending
on the type.

Example of default constructor that displays the


default values
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.

class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}

Test it Now
Output:
111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
by taking into account the number of parameters in the list and their type.

Example of Constructor Overloading


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

class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}

Test it Now
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor
Constructor is used to initialize the state of an object.

Java Method

Method is used to expose


object.

Constructor must not have return type.

Method must have return

Constructor is invoked implicitly.

Method is invoked explicit

The java compiler provides a default constructor if you don't have any

Method is not provided by

constructor.

case.

Constructor name must be same as the class name.

Method name may or may


class name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:

By constructor

By assigning the values of one object into another

By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Test it Now

Output:
111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan

Q) Does constructor return any value?


Ans:yes, that is current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any
operation in the constructor as you perform in the method.

Java static keyword

he 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.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class

1) Java static variable


If you declare any variable as static, it is known static variable.

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.

The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


1.
2.

class Student{
int rollno;

3.
4.
5.

String name;
String college="ITS";
}
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.

Example of static variable


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

//Program of static variable


class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output:111 Karan ITS
222 Aryan ITS

Program of counter without static variable


In this example, we have created an instance variable named count which is incremented in
the constructor. Since instance variable gets the memory at the time of object creation,
each object will have the copy of the instance variable, if it is incremented, it won't reflect to
other objects. So each objects will have the value 1 in the count variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();

14.
15.
16.

}
}
Test it Now
Output:1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Test it Now
Output:1
2
3

2) Java static method


If you apply static keyword with any method, it is known as static method.
o

A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a class.

static method can access static data member and can change the value of it.

Example of static method


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

//Program of changing the common property of all objects(static field).


class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal


calculation
1.
2.
3.
4.
5.
6.
7.

//Program to get cube of a given number by static method


class Calculate{
static int cube(int x){
return x*x*x;
}

8.
9.
10.
11.
12.

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Test it Now
Output:125

Restrictions for static method


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.
2. this and super cannot be used in static context.
1.
2.
3.
4.
5.
6.
7.

class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Test it Now
Output:Compile Time Error

Q) why java main method is static?


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.

3) Java static block


o

Is used to initialize the static data member.

It is executed before main method at the time of classloading.

Example of static block


1.
2.

class A2{
static{System.out.println("static block is invoked");}

3.
4.
5.
6.

public static void main(String args[]){


System.out.println("Hello main");
}

}
Test it Now

Output:static block is invoked


Hello main

Q) Can we execute a program without main() method?


Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1.
2.
3.
4.
5.
6.

class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Test it Now
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method
as:
public static void main(String[] args)

Difference between ArrayList and Vector


ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.

ArrayList
1) ArrayList is not synchronized.

Vector
Vector is synchronized.

2) ArrayList increments 50% of current

Vector increments 100% means doubles the array si

array size if number of element exceeds

of element exceeds than its capacity.

from its capacity.


3) ArrayList is not a legacy class, it is

Vector is a legacy class.

introduced in JDK 1.2.


4) ArrayList is fast because it is non-

Vector is slow because it is synchronized i.e. in multith

synchronized.

environment, it will hold the other threads in runnable


state until current thread releases the lock of object.

5) ArrayList uses Iterator interface to

Vector uses Enumeration interface to traverse the ele

traverse the elements.

use Iterator also.

Example of Java ArrayList


Let's see a simple example where we are using ArrayList to store and traverse the elements.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creating arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Test it Now
Output:
Sonoo
Michael
James
Andy

Example of Java Vector


Let's see a simple example of java Vector class that uses Enumeration interface.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.

import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Test it Now
Output:
umesh
irfan
kumar

You might also like