Core Java
Core Java
Core Java
3. BLOCKS 14-16
4. CONSTRUCTORS 17-19
7. INHERITANCE 25-30
8. PACKAGES 31-33
18. THREADS
BASICS/VARIABLES/METHODS
C JAVA
6.Define
a) KEYWORDS:
Keywords are set of reserved words or Predefined words for which already some meaning is
defined by the java developers.
In java there are 52 keywords.
Every keyword must be represented in lower case.
Ex: class, public, void etc……………
b) IDENTIFIERS:
Identifiers are used to identify the elements of java (class & method).
In other words, the names that we give to a class or a method in order to identify them
uniquely are known as identifiers.
Page |2
c) VARIABLES:
Variables are identifiers in which we store some value.
The type of value and the length of value to be stored under a variable will be decided by
datatype.
Datatypes will be used along the variable during variable declaration process.
d) DATATYPES:
In Java every datatype is the keyword.
In boolean variable we can store true/false not 1/0.
In Java String is not a datatype rather it is a Predefined class which is available in inbuilt
library folder.
Datatypes
Class type
Numeric Datatype Non-numeric Datatype Interface type
Char – 2 bytes
Boolean – 1 bit
No.
Advantages of methods:
a) Code reusability
b) We can achieve Modularity (Structure way of Programming)
Page |3
Type 2: Passing some value to a method and returning nothing from the method.
Type 3: Passing nothing to a method and returning some value from the method.
(i). whenever a method wants to something back to caller it will make use of return keyword.
(ii). If a method returning some value when the return type of the method will change based on that type of
value the method is returning.
Type 4: Passing values to a method and returns some value from the method.
Operators: 6 types
1. Arithmetic Operator : + , - , *, / , %
2. Relational Operator : > ,< , >= ,<= , == , !=
3. Logical Operator : && , ||
4. Bitwise Operator : %,|
5. Unary Operator : ++ (increment) ,--(decrement)
6. Shift Operator : >> (right shift) , << (left shift)
Page |4
Control Statements:
Control Statements are used to Control the flow of execution of the program.
Control Statements
Branching Looping
If for
If – else while
Else – if Ladder do while
Nested if
switch
Branching: syntax
if (condition)
{
----------
}
else if ( cond ) * out of all blocks any one will execute depending
{ upon the condition.
----------
} * if all the condition fails then else block will be
else if (cond) execution.
{
----------
}
else
{
----------
}
Page |5
if (condition)
{
if (condition)
{
------- (it will execute when both outer if and inner if the condition is true)
}
else
{
-------(it will execute outer if condition is true but inner if the
condition is false)
}
}
else
{
----------(it will execute outer if condition is false)
}
Looping:
If we want to perform the similar task repeatedly then we can make use of any one of the looping
statements.
2.Here the first condition will be check and 2.Here the first do while loop block will be
then the while loop block will be executed. executed and then condition will be checked.
3.If the condition is false the loop block will 3.The loop bloc will be executed at least one
not get executed even one’s. time even if the initial condition is false.
Basics of String:
In java String is a pre-defined class which available in the inbuilt library folder.
Within the inbuilt library folder, the string class in present in java. lang package.
The String class contains lots of predefined methods which are used to perform operations on string
value.
4.What is a Class?
A class is the java definition block or a java blue print which will contains different states and behaviour.
States refers to data members EX:
Behaviour refers to member function.
Class A
{
Static int x = 10, y = 20;
Public static void m1()
{
class Demo
Syntax:
{
Int x =100;
class CN Static double y=10.12;
{ public static void m1 ()
variable / data members {
Int a = 10;
static non-static --------
--------
}
public void m1 ()
methods/ member function
{
Int b = 20;
static non-static --------
} --------
}
P a g e | 10
5.What is an object?
An object is the real-world entity which will have its own states & behaviour.
States refers to Characteristics and Behaviour refers to functionality.
Ex: object Student
X=10
State / characteristics: height, weight, id, name ……
Behaviour/functionality: write, read, jump, run…. Y=20
M1()
M2()
Object w.r.to java:
An object is the real-world entity which will have its own states & behaviour.
States refers to variable or data members.
Behaviour refers to methods or member function.
Object Initialisation:
The process of initializing the non-static variables present inside an object is known as object
initialization.
According to the IT Standard the object initialization should not take place in the main method, if we
want to initialize the non-static variables, we will make use of
I. Non-static block
II. Constructor
6.What is byte code file? How many byte code files will be generated after compiling source file?
The File generated after successful compilation of a java source file called as byte code file or class file
or executable file.
A java source file can have any no. of classes in it. The no. of executable file or byte code file or class
file to be generated after successful compilation will be equal to the no.of classes present in the
source file and these byte code files will have some name as that of the class name out of all the
executable file we can pass one at a time to the JVM for the execution.
class A Output 1
A.CLASS
{
--------
} B.CLASS processor Output 2
class B JAVA C
{
C.CLASS Output 3
--------
}
Java support 3 types of variables they are local, static and non-static
12.How to access static & non static members explain with an example.
(i). Access static members:
To access static properties of one class into another class we make use of the below syntax.
During the class loading process that means when we pass a class file to the JVM for execution all the
static properties will be loading into the class memory or class area. which will have the same name as
that of the class name. This is the reason we access static properties of one class into class by using
class name.
To access non-static properties of one class into another class the below steps must be follow.
We need to create an object or instance of the class whose non-static properties should be accessed
by using the below syntax.
Create a reference variable in order to refers to the object present inside the heap memory or heap
area.
classname ref_varname;
Object creation
P a g e | 13
The individual properties are the details that differ from person to person will be declared as non-
static.
Ex: id
Name
Marks
Salary etc
Example:
class Faculty
{
int id;
String name; output:
double sal;
static String cname;
} Id Name salary com_name
class MainOfFaculty 111 veerendra 500.0 JSP
{ 112 sai 890.0 JSP
public static void main (String [] args)
{
Faculty.cname="JSP";
Faculty veeru=new Faculty ();
veeru.id=111;
veeru.name="veerendra";
veeru.sal=500.00;
System.out.println("Id\t\tName\t\tsalary\t\tcom_name");
System.out.println("-------------------------------------------------------------");
System.out.println(veeru.id+"\t\t"+veeru.name+"\t"+veeru.sal+"\t\t"+Faculty.cna
me);
System.out.println(sai.id+"\t\t"+sai.name+"\t\t"+sai.sal+"\t\t"+Faculty.cname);
}
}
P a g e | 14
BLOCKS
1. What is block and how many types of blocks available?
Blocks are set of instructions written by the programmer in order to perform some special tasks.
Static
Non-static
METHODS BLOCKS
1. It will have some name. 1. It will not have any name.
2. It will have modifier and return type. 2. It will allow modifier but it will not return type.
3. It will neither except nor return values.
3. It will have except and return values. 4.Ther are used for Special purpose.
4. It is used for writing logics by the
Programmer. 5. It will automatically execute
5. It will execute only when it is called explicitly
by the user.
The blocks which one declared using static keyword are known as static block.
The static block will be executed automatically during class loading time that means when we pass
the class file to the JVM for execution it will first check if the class contains any static block. If present
it will execute and then it will execute the main method.
A java class can have multiple static blocks in it, they will be executed in the same order in which they
are defined during class loading time.
Ex:
class NonStaticBlock
{
{
System.out.println("non-static block 1 executed"); // 2 Output:
}
public static void main (String [] args)
{ HELLO MAIN
System.out.println("HELLO MAIN"); // 1 non-static block 1 executed
new NonStaticBlock (); // object creation non-static block 2 executed
System.out.println("BYE MAIN"); // 5 non-static block 3 executed
} BYE MAIN
{
System.out.println("static block 2 executed"); // 3
}
{
System.out.println("static block 3 executed"); // 4
}
}
5.How many times static block will execute and non-static block will execute?
A java class can have both static block and non-static block together.
The static block will be executed only once during class loading time.
Non-static block will be executed every time when we create an object of a class.
Ex:
class Demo
{
static Output:
{
System.out.println("static block executed");
static block executed
}
HELLO MAIN
{
non-static block executed
System.out.println("non-static block executed");
non-static block executed
}
non-static block executed
public static void main (String [] args)
BYE MAIN
{
System.out.println("HELLO MAIN");
new Demo (); //object created
new Demo (); //object created
new Demo (); //object created
System.out.println("BYE MAIN");
}
}
P a g e | 16
CONSTR`UCTORS
1.What is a constructor? & Why is it used for?
Constructors are special method are member function which will have the same name as that of class
name.
Constructors are used to achieve object initialisation that means they are used to initialise the non-
static variable.
Constructors will not have any Return type.
Constructors will not have any Modifier.
Constructors are used instead of non-static blocks to achieve object initialisation.
Constructors will be executed automatically when we create an object
If we want to initialize some non-static variables in a class, we will go for argumented constructor.
Ex: class A
{
public A ()
{
System.out.println("no arg");
}
public A (int x)
{
System.out.println(x);
} Output:
public A (char ch, int a)
{
System.out.println(ch); 100
System.out.println(a); no arg
} x
public A (int x,char ch) 100
{ 100
System.out.println(x); A
System.out.println(ch);
}
}
class MainOfA
{
public static void main (String [] args)
{
new A (100);
new A ();
new A('x',100);
new A (100,'A');
}
}
P a g e | 19
8.What is the access modifiers allowed for constructor? (Public, private, protected, default)
All public, protected, private and default access modifiers are allowed for constructor.
Step 1: An empty object will be created in the heap memory or heap area.
Step 2: All the non-static properties will be loaded into the object.
Step 3: non-static block will be executed (if present)
Step 4: Constructor will be executed
Step 5: Create a reference variable in order to access the non-static properties present inside the object.
P a g e | 20
METHOD OVERLOADING
Overloading ‘main’ method means we have multiple method with the name “main” which differ in
their arguments with in a class which will be treated like any other user defined static method. The
JVM is concerned about the main method which is in the following format.
If the JVM does not find the main method in the above format then it will throw run time error.
Ex:
class Sample
{
public static void main ()
{ Output:
System.out.println("Hi no arg");
}
public static void main (double a, float b)
{ Hi no arg
System.out.println("hi double and float arg "+a+" "+b); Hi double and float arg 12.12 10.12
} Hi boolean and char arg true, T
public static void main (boolean x, char y)
{
System.out.println("Hi boolean and char arg"+x+" "+y);
}
}
class MainOfSample
{
public static void main (String [] args)
{
Sample.main();
Sample.main(12.12, 10.12f);
Sample.main(true,'T');
}
}
P a g e | 21
Java program1
“10” “20” “30” “40”
class Demo
{
public void xyz ()
{ Output:
System.out.println("In no arg of xyz");
}
public void xyz (int x)
{
In no arg of xyz
System.out.println("In int arg of xyz"+x);
In int arg of xyz 100
}
In float and String arg of xyz 12.12, Hello World
public void xyz (char a, boolean b)
In char and boolean arg of xyz ‘A’, false
{
System.out.println("In char and boolean arg of xyz"+a+" "+b);
}
public void xyz (float f, String s)
{
System.out.println("In float and String arg of xyz"+f+" "+s);
}
}
class MainOfDemo1
{
public static void main (String [] args)
{
Demo1 d1=new Demo1();
d1.xyz ();
d1.xyz (100);
d1.xyz (12.12f,"Hello World");
d1.xyz ('A’, false);
}
}
Method Overriding
2.Multiple methods with same name different 2.changing superclass method implementation is
signature is known as overloading. subclass is known as overloading.
Override concept is applicable only for object level methods that means in java static methods cannot
be overridden with respect to static method the same concept is known as method hiding.
while overriding the superclass method in the subclass we can either retained the same visibility of
the method or we can increase it.
But we cannot decrease the visibility while over hiding.
P a g e | 23
while overriding the super class in the subclass we cannot change the return type of the method (with
respect to primitive type).
class A
{
public void m1()
{
---
---
}
class B extends A
{
public int m1() // CTE, can’t change return type
{ while overriding.
--
--
}
}
Yes.
No.
An object showing different states in its different stages of life is known as polymorphism.
Polymorphism is classified into 2 types.
1.Static polymorphism:
Constructor Method
Overloading Overloading
2.Dynamic Polymorphism:
No, because the superclass constructor will not be inherited in its subclass.
14. While overriding, why co-variant type changes allowed & why not contra
variant?
P a g e | 25
INHERITANCE
1.What is inheritance & what are its advantages
The process of deriving one class property to another class is known as Inheritance
The class from which we derived the properties is known as present Parent class or Super class or
Base class.
The class two which we derive the properties is known as child class or sub class or derived class.
In java inheritance is also known as IS-A Relationship.
In order to inherit the properties are class into another class into another class we will make use of
“extends “keyword.
Syntax:
Class A class B extends A
{ { sub class Parent class
-------- child class Super class
-------- derived class Base class
} }
Advantages:
a. Code Reusability
b. To achieve dynamic polymorphism.
Multi-level inheritance:
The inheritance in which a super class will have a sub class and that sub class will further have another
sub class and so on is known as multi-level inheritance.
Hierarchical inheritance:
The inheritance in which one super class will have multiple sub classes is known as Hierarchical
inheritance.
It is the most widely used inheritance in the industry.
Multiple inheritance:
A sub class having more than one super class is known as multiple inheritance.
In java multiple inheritance not allowed.
Hybrid inheritance:
Combination of two or more type of inheritance is known as hybrid inheritance.
P a g e | 26
Object
A B
A A A
B C
B B C
C
EX: class A
{
int x; Output:
int y;
public A (int a,int b) 10
{ 20
System.out.println(a); 0
System.out.println(b); 0
System.out.println(x); 100
System.out.println(y); 200
} 0
} 0
class BOfMain
{
public static void main (String [] args)
{
A a1=new A (10,20);
A a2=new A (100,200);
}
}
P a g e | 27
Ex:
class A
{
int x=100;
int y=200;
} Output:
class B extends A
{
int a=10; 1
int b=20; 2
100
public B () 200
{ 100
int x=1; 200
int y=2;
System.out.println(x);
System.out.println(y);
System.out.println(this.x);
System.out.println(this. y);
System.out.println(super.x);
System.out.println(super. y);
}
}
class COfMain
{
public static void main (String [] args)
{
new B ();
}
}
It will call its super class constructor. If is called constructor chaining process.
class A
Ex: {
public A ()
{
System.out.println("no arg");
Output:
}
public A (int x)
{
this (); no arg
System.out.println(x); 100
}
public A (char ch, String s) x
{
this (100); HELLO
System.out.println(ch);
System.out.println(s);
}
}
class BofMain
{
public static void main (String [] args)
{
new A('x',"HELLO");
}
}
Ex:
final class A
{
------
}
class B extends A
{
-------- Output:
}
class main Compile time error can’t inherit final class
{
public static void main (String [ ] args)
{
----------
}
}
P a g e | 29
class A
Ex: {
public A ()
{
System.out.println("YO A");
}
}
class B extends A
{
public B (int x)
{
super (); Output:
System.out.println("YO B"+x);
}
} Main Starts
class C extends B YO A
{ YO B100
public C (boolean a) YO Cfalse
{ Main Ends
super (100);
System.out.println("YO C"+a);
}
}
class MainOfD
{
public static void main (String [] args)
{
System.out.println("Main Starts");
new C(false);
System.out.println("Main Ends");
}
}
2.It is used to refer the 2.It is used perform 2. It is used to access 2. It is used perform
current object. (Use constructor calling. super class properties in constructor chaining.
differentiate between the sub class.
local variable and non-
static variable)
3.It can be used inside a 3. It can be used only 3.It can be used inside a 3. It can be used only
constructor and non- inside a constructor. constructor and non- inside a constructor.
static block. static block.
4.It can be used 4.It must always be the 4.It can be used 4.. It must always be the
anywhere within first statement of anywhere within first statement of
constructor or non-static constructor body. constructor or non-static constructor body.
methods body. methods body.
Void: m1()
B C
m1() m1()
------
m1() m1()
----- ----
P a g e | 31
PACKAGES
No, because in one source file can only once package can be created.
package Gmail.login
package Gmail.login
import class B extends A;
import Gmail.logout.B;
{
{ public int p=100;
public class A }
public int x=10;
public int y=20; // only x and y are
int z=30; accessible from B class
private int m=40;
}
A.java B.java
YES
6. In which order package & import keyword should exist in a source file?
2.Default: It is also known as package level access modifier default members are accessible within the
package from any class.
3.Protected: It is same as default + we can also access protected members outside the provided the class
were trying to access should inherit from the class which that member belongs to
4.Public: They can be accessible with the class with in the package and also outside the package.
Hiding the data members of a class from outside the class is known as data hiding. We can the data
through private data members. To access the hidden data member, we use public methods.
a. setx (100);
System.out.println (a. getx ()); // 100
9. What is encapsulation?
Binding the data member of class with the methods together in a single entity is known as
Encapsulation.
A class is encapsulation of data members and methods.
A package is encapsulation of classes and interfaces.
A jar file is encapsulation of byte code file.
P a g e | 33
10. What is jar file? Where is rt.jar present? & What it contains?
12. Can I access public members outside the package if the class is default?
Outer classname - $
Inner classname - .class
14.Can I declare a class as private? What access modifiers can I provide for a Class.
3. Where we provide definition for the abstract methods & what if we failed to provide?
For all the abstract methods we will provide implementation in the subclass.
If we fail to provide then we will declare subclass also as abstract.
If a class contains at least one abstract method then it is mandatory to declare class as abstract.
If class contains only concrete methods.
Then it is optional to declare such class as abstract.
These two keywords not allowed in same line. Only one keyword only allowed
While providing implementation in the subclass either we should retain the visibility or increase.
[But cannot decreased].
P a g e | 35
Even though abstract class cannot be created constructors are allowed inside abstract class.
Abstract class constructor will be executed when we instantiate the subclass through constructor
chaining process.
Constructor inside the abstract class is used to initialise the data member of abstract class.
No, because the private method will not be inherited in its sub class.
P a g e | 36
12. Does abstract class allows static members? If yes, how to access them?
Write an example.
YES,
package org.jsp.abstracts;
public class A
{
public int x=10;
public static int y=100;
public static void print ()
{
System.out.println(“static concrete method”);
}
package org.jsp. abstracts;
public class MainClass
{
public static void main (String [] args)
System.out.println(“x=+”A.x);
System.out.println(“x=+”A.x);
}
}
INTERFACE
Interface is a java definition block which is used to define data member and methods.
Data members are by default static and final and methods are by default public and abstract.
interface A
{ interface A
{
same int x=10;
static final int x=10;
void m1();
public abstract void m1(); }
Note:
IS-A
Class Interface
| |
| |
| |
| |
| |
Class Class
Yes.
interface Itr1
{
}
interface Itr2 extends Itr1
{
}
P a g e | 38
An Interface can extend for another interface but not from class.
A class interface inherits from more than one interface that is multiple inheritance is allowed w.r.to
interface but not respect to interface.
Itr1 Itr2
k:int k:int
print (): void print (): void
Itr1
object
x:int
print (): void
Implem extends
class I class extends object implementation Itr2
I class
{
both }
sub class & implem class
An interface having only one Single Abstract Method (SAM) is known as functional interface.
interface Itr
{
public static void main (String [] args]
{ Compile:
System.out.println(“HELLO WORLD”);
} javac Itr.java
} java Itr
8. Advantages of interfaces.
To achieve abstraction
By creating a single interface type reference variable, we can accept any implementation class object.
And we can achieve tight coupling.
10. Can one interface have multiple implementation classes? Write an example
Yes,
Example : (abstraction)
Typecasting
Converting from one type of information to another type is known as Type Casting.
Type Casting is classified into 2 types:
Type Casting
short (2 byte)
Byte
double y=10;
float f=3.14; // CTE
implicitly widening double e = 8.14 f; // implicitly widening
float f = (float )3.14;
int x=(int) 10.11; Explicitly Narrowing System.out.println (e); // 3.14
System.out.println (x); // 10 System.out.println (f); // 8.14
System.out.println (y); // 10.0
Converting from one class type of information to another class is known as non-primitive type casting.
A a = new A (); A
class A B b= new B (); X: int
{ Print (): void
int x=10; A a=new B ();
public void print ()
Type mismatching
{ B b=new A (); Statements
-----
} B
class B extends A
{ System.out.println (a.x); y: double
double y =10.11; a.print (); disp (): void
public void disp ()
{ B b= (B) new A (); // explicit down casting
-----
}
}
Up Casting: When subclass object is referred by super class reference is known as Up casting.
Down Casting: When super class object is referred by subclass reference is known as Down casting.
The class we are trying to convert should contains the properties of the class to which we are trying to
convert.
If the 1st condition is failed, we will get CTE and 2nd condition is failed we will get ClassCastException
(CCE).
P a g e | 44
When we don’t use typecasting, we will end up writing multiple overloaded specialized methods.
A method which accepts specific type of object is known as “Specialized method “.
A Program written by using specialised is known as ‘Specialisation’.
A
X: int
Print (): void
B C D
y: double Z: char m: long
class Display
{
public void print (B b)
{
System.out.println (b.x+” “+b.y);
}
public void print (C c)
{
System.out.println (c.z);
}
public void print (D d)
{
System.out.println (d.m);
}
class MainOfDisplay
{
public static void main (String [] args)
{
Display d=new Display ()
d.print (new b ());
d.print (new c ());
d.print (new d ());
}
}
P a g e | 45
When we use Typecasting, we will able to right one generalized method which can accepts returns
any type of object.
A program returns by using such generalized methods is known as ‘Generalisation’.
class Display
Ex:
{
public void print (object obj)
{
if (obj instance of A)
{
A a = (A) obj;
System.out.println (a.x);
if (obj instance of B)
{
B b = (B) a;
System.out.println (b.y);
}
if (obj instance of C)
{
C c = (c) a;
System.out.println (c.z);
}
if (obj instance of D)
{
D d = (D) a;
System.out.println (D.m);
}
}
}
}
class MainOfDisplay
{
public static void main (String [] args)
{
Display d=new Display ()
d.print (new B ()); // object obj = new B ()
d.print (new C ()); // object obj = new B ()
d.print (new D ()); // object obj = new B ()
}
}
P a g e | 46
“instanceof “is a keyword used to check whether the given object contains the properties of any
particular class or not.
It returns Boolean value.
class A
{
int x=10;
public void main ()
{
-------
}
class B extends A
{
double y=10.11;
public void disp ()
{
----
}
}
class MainOfA
{
public static void main (String [] args)
{
A a=new B ();
System.out.println(a.x);
System.out.println(a.print ());
B.b=(B) new A ();
if (a instanceof B)
{
B b=(B) a; Up casted
System.out.println(b.y);
b.disp ();
}
}
A a = new A ();
If (a instanceof B)
{
B b = (B) a; // CCE
}
Not up casted
P a g e | 47
Writing public class with private data member, public constructor, getters and setters is known as
Java Bean Class.
Java Bean Class is an example for both data hiding and encapsulation.
We write java bean class in order to achieve DAO (Data Access Object) or DTO (Data Transfer Object)
layers of project development.
public class A
{
private int x;
public A (int x);
{
this.x = x;
}
// getter
public int get x ();
{
return x;
}
// setter
Getters: Getters are used to get the values. The values of a private data member from one class to another.
Setters: Setters used to set the values of a private data member from one class to another.
Syntax: // getter
public int get x ()
{
return x;
}
// setter
public void set x (int x)
{
this.x=x;
}
P a g e | 48
A class whose object can be created only throughout the live of the project.
This can be achieved by using private constructor, helper method and private data member.
This is called Single-Ton-class.