0% found this document useful (0 votes)
4 views156 pages

Core Java 1

This document provides a comprehensive overview of Core Java, covering its fundamentals, features, and various applications. It explains key concepts such as JDK, JVM, and JRE, along with data types, operators, control statements, and object-oriented programming principles. Additionally, it includes practical examples and syntax for Java programming constructs like loops, conditionals, and methods.

Uploaded by

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

Core Java 1

This document provides a comprehensive overview of Core Java, covering its fundamentals, features, and various applications. It explains key concepts such as JDK, JVM, and JRE, along with data types, operators, control statements, and object-oriented programming principles. Additionally, it includes practical examples and syntax for Java programming constructs like loops, conditionals, and methods.

Uploaded by

Deepak Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basics of Core Java

S A G AR S A R K A R

T E C H N I C A L F A C U L T Y - T A L E N T D E V E L O P ME N T - P UN E

B S @ IIT M A DRA S

S T R E AM S - C# , P YT H O N , J A VA , M A CH I N E L E A R N I N G , BI G D A T A , A Z U R E - I O T
Contents
Introduction.
JDK,JVM and JRE.
Variables
Data Types
Operator
Control Statements
OOPS Concept
Static and this Keyword
Package
Access Modifiers and Encapsulation
Method Overloading
Memory Allocation
Array
Introduction
Java is a programming language. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java.
Java was originally designed for interactive television, but it was too advanced technology for
the digital cable television industry at the time. However, it was suited for internet
programming.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".
Currently, Java is used in internet programming, mobile devices, games, e-business solutions,
etc.
Types of Java Applications
1) Standalone Application
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate5 etc. technologies are used for creating web applications in Java.
3) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android is used for
creating mobile applications.
4) Embedded System
5) Smart Card
6) Robotics
Features of Java
Simple
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.
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.
Java code can be run on multiple platforms, for example, 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
Java is best known for its security. Java is secured because:
No explicit pointer that prohibits anyone to make any reference based modifications on data
Java Programs run inside a virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
It uses strong memory management and garbage collection system.
There are exception handling and the type checking mechanism in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI(Remote Method Injection) and EJB(Enterprise Java Beans) are used for creating distributed
applications.
This feature of Java makes us able to 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.
Threads are important for multi-media, Web applications, etc.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Object-oriented
Java is an object-oriented programming language.
Everything in Java is an object. Object-oriented means we organize our software as a
combination of different types of objects that incorporates both data and behavior.
JDK,JRE and JVM
Java Development Kit (JDK) is a software development environment used for developing Java
applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader
(Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other
tools needed in Java development.
JRE (Java Runtime Environment) is an installation package that provides an environment to only
run(not develop) the java program(or application)onto your machine. JRE is only used by those
who only want to run Java programs that are end-users of your system.
JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained
or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line by line, hence it is also known as an interpreter.
How does Java Program gets executed-[Link]
java-program/
Creating Hello World Example

class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}
Parameters used in First Java Program
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create an object to invoke
the main method.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument.
[Link]() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Variable is name of reserved area allocated in memory. In other words, it is a name of memory
location. It is a combination of "vary + able" that means its value can be changed.
int data=50;//Here data is variable
Data Type Default Value Default size
boolean False 1 bit
char 0 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used for simple
flags that track true/false conditions.
Example: Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It saves
space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Short Data Type
Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller
than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example: int a = 100000, int b = -200000
Long Data Type
Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -
1)(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0L. The long data type is used when you need a range of values
more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. Its default value is 0.0F.
Example: float f1 = 234.5f
Double Data Type
Its value range is unlimited. The double data type is generally used for decimal values just like
float. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between ' (or 0) to (or
65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
Types of Operators
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


If statement
The Java if statement tests the condition. It executes the if block if condition is true.
if(condition){
//code to be executed
}
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Using Ternary Operator
We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand way to check the condition. If the
condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.
if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
...
else{
//code to be executed if all the conditions are false
}
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
For statement
The Java for loop is used to iterate a part of the program several times. If the number of iteration
is fixed, it is recommended to use for loop
There are three types of for loops:

Simple For Loop


For-each or Enhanced For Loop
Labeled For Loop
Java Simple For Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
Initialization: It is the initial condition which is executed once when the loop starts. Here, we can
initialize the variable, or we can use an already initialized variable. It is an optional condition.
Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either true
or false. It is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Java Nested For Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop
executes completely whenever outer loop executes.
Java for-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for
loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful
if we have nested for loop so that we can break/continue specific for loop.
Usually, break and continue keywords breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.
The switch statement works with byte, short, int, long, String.
It basically tests the equality of a variable against multiple values.
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only. The case value must be literal or constant. It doesn't
allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
Each case statement can have a break statement which is optional. When control reaches to the break statement,
it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
The case value can have a default label which is optional.
The Java switch statement is fall-through. It means it executes all statements after the first match if a break
statement is not present.
Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.

Syntax:

while(true){

//code to be executed

Example:

public class WhileExample2 {

public static void main(String[]args) {

while(true){

[Link]("infinitive while loop");

}
Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body
Syntax-
do{
//code to be executed
}while(condition);
Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:
do{
//code to be executed
}while(true);
Java Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.
Syntax:
jump-statement;
break;
Java Continue Statement
The continue statement is used in loop control structure when you need to jump to the next
iteration of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.
Syntax:
jump-statement;
continue;
Comments
The Java comments are the statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code.
There are three types of comments in Kava.
Single Line Comment
Multi Line Comment
Documentation Comment
Java Documentation Comment
The documentation comment is used to create documentation API.
Syntax:
1./**
[Link]
[Link]
[Link]
[Link]
6.*/
Example:
1./** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
[Link] class Calculator {
3./** The add() method returns addition of given numbers.*/
[Link] static int add(int a, int b){return a+b;}
5./** The sub() method returns subtraction of given numbers.*/
[Link] static int sub(int a, int b){return a-b;}
7.}
Now, there will be HTML files created for your Calculator class in the current directory.
OOPs Concepts
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
The main aim of object-oriented programming is to implement real-world entities
Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology to design a program using classes and objects.
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
[Link] provides code [Link] is used to achieve runtime polymorphism
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to draw
something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
We use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Coupling
Coupling refers to the dependency of another class. It arises when classes are aware of each
other. If a class has the details information of another class, there is strong coupling. In Java, we
use private, protected, and public modifiers to display the visibility level of a class, method, and
field. You can use interfaces for the weaker coupling because there is no concrete
implementation.
Advantage of OOPs over Procedure-oriented
programming language

1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented


programming language, it is not easy to manage code
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global
data can be accessed from anywhere.
3)OOPs provides the ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.
Procedural Oriented Programming Object-Oriented Programming
Java Naming conventions
Java naming convention is a rule to follow as you decide what to name your identifiers such as
class, package, variable, constant, method, etc.
But, it is not forced to follow. So, it is known as convention not rule
By using standard Java naming conventions, you make your code easier to read for yourself and
other programmers. Readability of Java program is very important.
The following are the key rules that must be followed by every identifier:
The name must not contain any white spaces.
The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).
Class and Interface
It should start with the uppercase letter.
Use appropriate words, instead of acronyms.
Example: -
public class Employee
{
//code snippet
}
Method
It should start with lowercase letter.
If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as
actionPerformed().
Example:-
class Employee
{
//method
void draw()
{
//code snippet
}
}
Variable
It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore).
If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter
such as firstName, lastName.
Example :-
class Employee
{
//variable
int id;
//code snippet
}
Package
It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as [Link],
[Link].
Example :-
package [Link]; //package
class Employee
{
//code snippet
}
What is an object in Java
An entity that has state and behavior is known as an object e.g., chair, bike etc. It can be
tangible or intangible(Banking system).
An object has three characteristics:
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. An object is a real-world entity.
What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
class <class_name>{
field;
method;
}
Object and Class Example: main within the
class
In this example, we have created a Student class which has two data members id and name. We are creating the object
of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: [Link]
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;
//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
[Link]([Link]);//accessing member through reference variable
[Link]([Link]);
}
}
Output:
0
null
Object and Class Example: main outside the
class
In real time development, we create classes and use it from another class. It is a better approach than previous
one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java
source file, it is a good idea to save the file name with the class name which has main() method.
File: [Link]
//Java Program to demonstrate having the main method in
//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
[Link]([Link]);
[Link]([Link]);
}
}
Test it Now
Output:

0
null
3 Ways to initialize object
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor
Object and Class Example: Initialization
through reference

Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.
File: [Link]
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
[Link]=101;
[Link]="Sonoo";
[Link]([Link]+" "+[Link]);//printing members with a white space
}
}
Output:

101 Sonoo
Object and Class Example: Initialization
through method
In this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
Object and Class Example: Initialization
through a constructor

Eclipse-TestEmployee
TestAccount
Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

int a=10, b=20;


Initialization of refernce variables:

Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects


Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
We can use access modifiers while declaring a constructor. It controls the object creation. In
other words, we can have private, protected, public or default constructor in Java.
It calls a default constructor if there is no constructor available in the class.
In such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized 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.
Rules for creating Java constructor
There are two rules defined for the constructor.

Constructor name must be the same as its class name


A Constructor must have no explicit return type
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
If there is no constructor in a class, compiler automatically creates a default constructor
Example of default constructor
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){[Link]("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
If there is no constructor in a class, compiler automatically creates a default constructor.
Example of default constructor that displays
the default values
//Let us see another example of default constructor
//which displays the default values
class Student3{
int id; //0
String name;//null
//method to display the value of id and name
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3(); Output-0 null
//displaying values of the object 0 null
[Link]();
[Link]();
}
}
Java Parameterized Constructor
//Java Program to demonstrate the use of the parameterized constructor.

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

//method to display the values

void display(){[Link](id+" "+name);}


public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists.
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types.
Student5
Difference between constructor and method
in Java
Java Constructor Java Method
A constructor is used to initialize the state of A method is used to expose the behavior of an
an object. object.
A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the compiler in
constructor if you don't have any constructor any case.
in a class.

The constructor name must be same as the The method name may or may not be same as
class name. the class name.
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than
an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Java static variable
The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
The static variable gets memory only once in the class area at the time of class loading.
It makes your program memory efficient (i.e., it saves memory).

Static variable1
Understanding the problem without static
variable

class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
Java static property is shared to all objects.
Another example of a static method that
performs a normal calculation
//Java Program to get the cube of a given number using the static method

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

public static void main(String args[]){


int result=[Link](5);
[Link](result);
}
}
Restrictions for the static method

There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static

public static void main(String args[]){


[Link](a);
}
}
Test it Now
Output:Compile Time Error
Why is the Java main method static?
Ans) It is because the object is not required to call a static method.
If it were a non-static method, JVM creates an object first then call main() method that will lead
the problem of extra memory allocation.
Java static block

•Is used to initialize the static data member.


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

Example of static block


class A2{
static{[Link]("static block is invoked");}
public static void main(String args[]){
[Link]("Hello main");
}
}
Test it Now
Output:static block is invoked Hello main
Can we execute a program without main()
method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is
not possible to execute a Java class without the main method.
class A3{
static{
[Link]("static block is invoked");
[Link](0);
}
}
this keyword in java
There can be a lot of usage of java this keyword.
In java, this is a reference variable that refers to the current object
Usage of java this keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Example testStatic1
this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example
class A{
void m(){[Link](“Hello m");}
void n(){
[Link]("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output
Hello n
Hello m
this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor-teststatic5
Calling parameterized constructor from default constructor-teststatic6
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining.

Rule: Call to this() must be the first statement in constructor.

Testthis7
this: to pass as an argument in the method

Example s2
this: to pass as argument in the constructor
call

Exampel A4
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this,
output of both variables are same.

class A5{
void m(){
[Link](this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
[Link](obj);//prints the reference ID
obj.m();
}
}
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as
1) [Link]: Contains language support classes(e.g classes which defines primitive data types, math
operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.
3) [Link]: Contains utility classes which implement data structures like Linked List, Dictionary and
support .
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
How to access package from another
package?

There are three ways to access the package from outside the package.
import package.*;
import [Link];
fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Using [Link]
If you import [Link] then only declared class of this package will be accessible.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
//save by [Link]

package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Access Modifiers
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
There are four types of Java access modifiers:

Access Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private
class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the instance of that class from
outside the class
A class cannot be private or protected
Default
//save by [Link]

package pack;

class A{

void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error

[Link]();//Compile Time Error

}
It provides more accessibility than private.
But, it is more restrictive than protected and public.
Public
/save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
} //save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Protected
//save by [Link]

package pack;

public class A{

protected void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

[Link]();

}
Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
class A{
protected void msg(){[Link]("Hello java");}
}
public class Simple extends A{
void msg(){[Link]("Hello java");}//[Link]
public static void main(String args[]){
Simple obj=new Simple();
[Link]();
}
}
Encapsulation
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
The Java Bean class is the example of a fully encapsulated class.
Advantage of Encapsulation in Java
By providing only a setter or getter method, you can make the class read-only or write-only. In
other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should
be greater than 100 only, you can write the logic inside the setter method. You can write the
logic not to store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and
fast to create an encapsulated class in Java.
Simple Example of Encapsulation in Java
Let's see the simple example of encapsulation that has only one field with its setter and getter
methods.
File: [Link]
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package [Link];
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
[Link]=name
}
}
File: [Link]
//A Java class to test the encapsulated class.
package [Link];
class Test{
public static void main(String[] args){
//creating instance of the encapsulated class
Student s=new Student();
//setting value in the name member
[Link]("vijay");
//getting value of the name member
[Link]([Link]());
}
}
Output:
vijay
Read-Only class
//A Java class which has only getter methods.
public class Student{
//private data member
private String college="AKG";
//getter method for college
public String getCollege(){
return college;
}
}
Now, you can't change the value of the college data member which is "AKG".

[Link]("KITE");//will render compile time error


Write-Only class
//A Java class which has only setter methods.
public class Student{
//private data member
private String college;
//getter method for college
public void setCollege(String college){
[Link]=college;
}
}
Now, you can't get the value of the college, you can only change the value of college data member.

[Link]([Link]());//Compile Time Error, because there is no such method


[Link]([Link]);//Compile Time Error, because the college data member is private.
//So, it can't be accessed from outside the class
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
Method Overloading is not possible by changing the return type of the method only.
Method Overloading: changing no. of
arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of
arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}
Output:
22
24.9
Why Method Overloading is not possible by
changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because
of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
[Link]([Link](11,11));//ambiguity
}}
Output-Compile Time Error-method add(int,int) is already defined in the Adder Class
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[] args){[Link]("main with String[]");}
public static void main(String args){[Link]("main with String");}
public static void main(){[Link]("main without args");}
}
Output-main with String[]
Method Overloading and Type Promotion
Example of Method Overloading with
TypePromotion
class OverloadingCalculation1{
void sum(int a,long b){[Link](a+b);}
void sum(int a,int b,int c){[Link](a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
[Link](20,20);//now second int literal will be promoted to long
[Link](20,20,20);
}
}
Output:40
60
Example of Method Overloading with Type
Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b){[Link]("int arg method invoked");}
void sum(long a,long b){[Link]("long arg method invoked");}

public static void main(String args[]){


OverloadingCalculation2 obj=new OverloadingCalculation2();
[Link](20,20);//now int arg sum() method gets invoked
}
}
Output:int arg method invoked
Example of Method Overloading with Type
Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be
ambiguity.

class OverloadingCalculation3{
void sum(int a,long b){[Link]("a method invoked");}
void sum(long a,int b){[Link]("b method invoked");}

public static void main(String args[]){


OverloadingCalculation3 obj=new OverloadingCalculation3();
[Link](20,20);//now ambiguity
}
}
Output:Compile Time Error
Memory Allocation in Java
What is Stack Memory?
Stack in java is a section of memory which contains methods, local variables, and reference
variables. Stack memory is always referenced in Last-In-First-Out order. Local variables are
created in the stack.

What is Heap Memory?


Heap is a section of memory which contains Objects and may also contain reference variables.
Instance variables are created in the heap
The JVM divided the memory into following sections.
Heap
Stack
Code
Static

This division of memory is required for its effective management.

The code section contains your bytecode.


The Stack section of memory contains methods, local variables, and reference variables.
The Heap section contains Objects (may also contain reference variables).
The Static section contains Static data/methods.
Let's take an example to understand this better.
Consider that your main method calling method m1
public void m1{
int x=20
}
In the stack java, a frame will be created from method m1.
The variable X in m1 will also be created in the frame for m1 in the stack.
Method m1 is calling method m2. In the stack java, a new frame is created for m2 on top of the
frame m1.
Variable b and c will also be created in a frame m2 in a stack.

public void m2(int b){


boolean c;
}
Same method m2 is calling method m3. Again a frame m3 is created on the top of the stack.
Now let say our method m3 is creating an object for class "Account," which has two instances variable int p and int q.
Account {
Int p;
Int q;
}
Here is the code for method m3
public void m3(){
Account ref = new Account();
// more code
}
The statement new Account() will create an object of account in heap.
The reference variable "ref" will be created in a stack java.
The assignment "=" operator will make a reference variable to point to the object in the Heap.
Once the method has completed its execution. The flow of control will go back to the calling
method. Which in this case is method m2.
The stack from method m3 will be flushed out.
Since the reference variable will no longer be pointing to the object in the heap, it would be
eligible for garbage collection.
Once method m2 has completed its execution. It will be popped out of the stack, and all its variable will be
flushed and no longer be available for use.
Likewise for method m1.
Eventually, the flow of control will return to the start point of the program. Which usually, is the "main" method.
What if Object has a reference as its instance variable?
public static void main(String args[]) {
A parent = new A(); //more code }
class A{ B child = new B();
int e; //more code }
class B
{ int c; int d; //more code }
In this case , the reference variable "child" will be created in heap ,which in turn will be pointing
to its object,
Java Arrays
Normally, an array is a collection of similar type of elements which have a contiguous memory
location.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Copying a Java Array
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
src − This is the source array.
srcPos − This is the starting position in the source array.
dest − This is the destination array.
destPos − This is the starting position in the destination data.
length − This is the number of array elements to be copied.
Thanks and All the Best

You might also like