0% found this document useful (0 votes)
116 views33 pages

JAVA - UNIT - 1 Customised

This document provides an introduction to the Java programming language including: 1. A brief history of Java's origins at Sun Microsystems in 1991 and its initial motivation as a platform-independent language. 2. An overview of Java's key features such as being object-oriented, platform independent, secure, portable, robust, and multi-threaded. 3. A comparison of how Java differs from C and C++ in its use of objects, platform independence, and other features. 4. An explanation of the structure of a basic Java program and the roles of the JVM, JDK, and JRE in executing Java code.

Uploaded by

Simran fatima
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)
116 views33 pages

JAVA - UNIT - 1 Customised

This document provides an introduction to the Java programming language including: 1. A brief history of Java's origins at Sun Microsystems in 1991 and its initial motivation as a platform-independent language. 2. An overview of Java's key features such as being object-oriented, platform independent, secure, portable, robust, and multi-threaded. 3. A comparison of how Java differs from C and C++ in its use of objects, platform independence, and other features. 4. An explanation of the structure of a basic Java program and the roles of the JVM, JDK, and JRE in executing Java code.

Uploaded by

Simran fatima
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/ 33

UNIT-1

1. Introduction to JAVA
 JAVA History

James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan conceived Java at Sun
Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language
was initially called “Oak” but was renamed “Java” in 1995. The original motivation for java was not
the Internet! Instead, the primary motivation was the need for a platform-independent
(Architectural Neutral).
S.N Year Name of the Place &Developers Drawbacks
o programming
language
1. 1960 ALGOL 60 International Too general and too abstract
Committee
2. 1963 CPL Cambridge University Hard to learn and implement
3. 1967 BCPL Martin Richards at Could only deal with specific
Cambridge University problems.
4. 1970 B Ken Thompson at Dealt with only specific problems
AT&T BELL Laboratory
5. 1972 C Dennis Ritchie at AT&T Added features of B and BCPL and
BELL Laboratory lost generality and abstractions
6. 1979 C++ Bjarne Stroustrup Derived from C and added features
of object-oriented programming
7. 1991 JAVA James Goslling, Patrick Completely object based and
Naughtson, Chris Architectural Neutral.
Warth, Ed Frank and
Mike Sheridan at Sun
Micro Systems

 JAVA

JAVA is high-level programming language that follows OOP principle. The main motto of JAVA
programming language is “write once and run everywhere”. The syntax and semantics of JAVA
are very much similar to C & C++ programming languages.
JAVA is considered a programming language and a platform independent. As a programming
language, it is a general-purpose, object-oriented, high-level programming language that has its
own syntax and style. As a platform, it provides an environment in which java applications run.
 Applications of JAVA
 Mobile Applications
 Desktop GUI Applications
 Web-based Applications
 Enterprise Applications
 Scientific Applications
 Gaming Applications
 Big Data technologies
 Business Applications
 Distributed Applications
 Cloud-based Applications

 Features of JAVA
 There are eleven features of JAVA programming Language. They are:
 i.) Simple:
 It is easy to understand and learn.
 Java is a simple programming language and its syntax is based on C++, easy for
C++ learners.
 It removed some difficult and rarely used like pointers, operator overloading etc.
 No need to remove unwanted data because there is an automatic garbage
collector.

ii.) Object-oriented:

 Java is an object oriented programming language where everything in there is an


object.
 Class – Variables and functions together.
 Object – Combining together
 Inheritance – Acquiring features of parent class to child class
 Encapsulation – Combining together

iii.) Platform Independent:

 It is independent because other languages like C and C++ can’t move from one
system to other, which is possible in JAVA. The compiler converts the written
program in byte code, which is done internally in the system.

iv.) Secured:

 Java provides best security than other languages.

v.) Portable:

 It is portable because it is easy to you to carry JAVA bytecode to any platform.

vi.) Robust:

 JAVA is strong. As it is used for strong memory management.


 There is automatic garbage collection, rechecking mechanism etc.
 All the above, makes JAVA robust

vii.) Architectural Neutral:

 It means it is fixed. There are no implementation dependent features.


 Ex – In C, Datatypes occupy
2bytes of memory for 32 bits
4bytes of memory for 64 bits
But in JAVA, it occupies
4bytes of memory for both 32 and 64 bits

viii.) High Performance:

 It is a faster programming language. JAVA bytecode is close to naïve code but its
slower than C++.
 JAVA is an interpreted language, that is why it is slower.

ix.) Distributed:

 The distributed feature of JAVA makes us to access the files by calling methods.

x.) Multi-threaded:

 It means “more than one”. We can perform 2 (or) more tasks at a time.

xi.) Dynamic:

This means class libraries are linked with some other libraries.

 Ex – stdio.h (in C language)

 How does JAVA differ from C and C++?


 C is a procedure oriented programming language, C++ is an object-oriented
programming language, whereas JAVA is a purely object-oriented programming
language.
 C and C++ both the languages only use compiler bur Java uses a complier and an
interpreter.
 C and C++ languages are platform dependent but Java is platform independent.
 Java doesn’t support any header files like C and C++ languages.
C and C++ uses pointers but java doesn’t.
 Storage classes like auto, extern are not supported by Java where C and C++
languages supports storage classes.
 We can create our own packages in Java but not in C and C++ languages.
 Internal programming like frames, applets are used in Java where C and C++
doesn’t use them.
STRUCTURE OF JAVA PROGRAM
class <name of class>
{
public static void main(String args[])
{
//body
}
}
Class:Class Keyword is used to declare class in java
Public:It is an access specifier.
Public means this function is visible to all.
Static:Static is keyword used to make function static.
To execute a static function you do not have to create an object of the class,
The main() method is called by JVM without creating an obj for class.
Void: It is the return type ,meaning this function will not return anything.
Main():Main () method is most important method in java program.
This is the method which is executed, hence all the logic must be inside the main() method.
 If java class is not having main() method it causes compilation error
 String[]args:This represent an array whose type is string and name is args
 System.out.println:This is used to Print any thing on the console like Printf in c lang.
Introduction to JDK and JRE
JVM:

 It stands for Java Virtual Machine(JVM)


 It is an interpreter that executes bytecode.
 JVM architecture includes 6 components. They are:
a) Class loader
b) Bytecode Verifier/ Security Manager
c) JAVA interpreter
d) Just-in-time compiler
e) Garbage collector / Memory Management
f) JAVA Runtime Environment(JRE)

JDK:
The Java Development Kit (JDK) is one of three core technology
packages used in Java programming, along with the JVM (Java Virtual
Machine) and the JRE (Java Runtime Environment). It's important to
differentiate between these three technologies and understand how
they're connected:

 The JVM is the runtime that hosts running programs.

 The JRE is the on-disk part of Java that creates the JVM and loads
programs into them.

 The JDK provides the tools necessary to write Java programs that can
be executed and run by the JVM and JRE.
Developers new to Java often confuse the Java Development Kit and
the Java Runtime Environment. The distinction is that the JDK is a
package of tools for developing Java-based software, whereas the
JRE is a package of tools for running Java code.

The JRE can be used as a standalone component to simply run Java


programs, but it's also part of the JDK. The JDK requires a JRE
because running Java programs is part of developing them.

Basic Operators

Operators are the symbols used to perform operations such as +, -, *, / etc.

 Types of operators in JAVA:


 Unary Operator:
 This operator requires only one operand.
 Used to perform:
 increment / decrement
 negating an expression
 inverting value of Boolean.
 Arithmetic Operator:
 It performs calculations such as addition, subtraction, multiplication,
division.
 Shift Operator:
 Here, it again has Right Shift and Left shift.
 Right shift operator is used to shift all the bits to its left in a value to
right of a specified number of times.
 Left shift operator is used to shift all the bits to its right in a value to
left of a specified number of times.
 Relational Operator:
 It is used for comparing two or more values.
 Logical Operators:
 It is used to check whether the given expression is True / False.
 Bitwise Operators:
 It is used for manipulating individual bits of a number.
 Ternary Operators:
 It is used as one-line replacement for if-then-else which is the only
operator that uses 3 operands.
 Assignment Operator:
 It is used to assign values on right to the operands on left.
 It is the most common operator used.

 Conditional and Logical Statements


 Conditional operators check the condition and decides the desired result on the basis of
both conditions.
 There are three types of the conditional operator in Java:
1) Conditional AND
2) Conditional OR
3) Ternary Operator
1) Conditional AND:

The operator is applied between two Boolean expressions. It is denoted by the two AND
operators (&&). It returns true if and only if both expressions are true, else returns false.

X Y X && Y

True False False

False True False

False False False

True True True

2) Conditional OR:

The operator is applied between two Boolean expressions. It is denoted by the two OR
operator (||). It returns true if any of the expression is true, else returns false.
X Y X || Y

True True True

True False True

False True True

False False False

3)Ternary Operators:

The meaning of ternary is composed of three parts. The ternary operator (? :) consists of
three operands. It is used to evaluate Boolean expressions. The operator decides which
value will be assigned to the variable. It is the only conditional operator that accepts
three operands. It can be used instead of the if-else statement. It makes the code much
more easy, readable, and shorter.

CONDITIONAL STATEMENTS:

Conditional statements in a computer program supports decision based on certain condition of


true or false.

IF STATEMENT:
If basically analysis and chooses in which direction a program flows based on certain
parameters and conditions.

SYNTAX:

If(condition)

//Block of statements

PROGRAM:

Public class Ifstatement

public static void main (Strings [] args)

Int age=18;

If(age>=18);

System.out.println(“you can drive”);

IF ELSE STATEMENT:

In if else program if the condition is true then the statement present in if statement will be
executed if the condition is false the else statement will be executed.

SYNTAX:

If(condition)

//block of statement
}

else

//block of statements

PROGRAM:

Public class Ifelsestmt

public static void main(Strings[] args)

int age=18;

If(age>=18)

System.out.println(“you can drive”)

else

System.out.println(“you are not old enough to drive”);

SWITCH STATEMENT:

The switch statement is a multi-way branching statement. In simple words, the java switch
statement executes one statement from multiple conditions.

SYNTAX:
Switch(condition)

Case 1:

//block of statements

Break;

Case 2:

//block of statement

Break;

Default:

//block of statement

PROGRAM:

public class Switchstatement

public static void main(Strings[] args)

int i=5;

switch( roman number 1)

Case 1:

System.out.println(“I is 1”);

Break;

Case 2:

System.out.println(“I is 2”);

Break;
Case 3:

System.out.println(“I is 3”);

Break;

Case 4:

System.out.println(“I is 4”);

Break;

Case 5:

System.out.println(“I is 5”);

Break;

Default:

System.out.println(“INVALID VALUE”);

Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be


declared before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:Backward Skip 10sPlay VideoForward Skip 10s
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

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:

1. Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. 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:

1. byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. 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:

1. short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer. 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:

1. int a = 100000, int b = -200000

Long Data Type

The long data type is a 64-bit two's complement integer. 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 0. The long data type is used when you
need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.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. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range
is unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between '\
u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example:

1. char letterA = 'A'

Loops in java:
Loops in java : Loop is used in programming to repeat a specific block of code when some
conditions become true. There are three types of loops in java.
(1) for loop
(2) while loop
(3) do-while loop >
The for Loop : The 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 in java.
✓ Simple For Loop
✓For-each or Enhanced For Loop
✓Labeled For Loop
Simple For Loop : We can initialize variable, check condition The simple for loop is same as
C/C++. and increment/decrement value.
Syntax :
for(initialization; condition; incr/decr)
{ //code to be executed }
Program to show usage to of for loop:
Public class Forexample
{
public static void main(String[]args)
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
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
}
program to show usage of for each loop:
public class ForEachExample:
{
public static void main(String[] args)
{
int arr[]= (10,12,25,30,56);
for(int i : arr)
{
System.out.println(i);
}
}
}
Output :
10
12
25
30
56
LOOPS
While Loop : The Java while loop is used to iterate a part of the program several times. If number
of iteration is not fixed, it is recommended to use while loop.
Syntax :
while(condition)
{
//code to be executed
}
Program to show usage of while loop
public class Whilexample
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
System.out.println(i);
i++;
}
}
}
Output :
1
2
3
4
5
do-while Loop :
The java dowhile loop is used to iterate a part of 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);
Program to show usage of do-while loop:

public class Dowhileexample


{
public static void main(String[] args)
{
int i;
do
{
System.out.println(i);
i++;
}
while(i<=5);
}
Output :
1
2
3
4
5

2. DEFINING CLASSES

Class:

Class is a blueprint from which objects are created.

Class is the collection of instance variables and methods which are nothing but variables and
functions in C language and Data variables and member functions in C++ language.

A class is a group of objects which have common properties.

 Syntax of Class:
Class < classname>
{
-----------
------------
------------
------------
}
No need to put “;” at the end of the class in Java as in C++.

class Student //class name should start with capital letter


{
string name;
int rollno;
void set( )
{
name=”xyz”
rollno=521;
}
void display() //method
{

System.out.println(“Name=”+name);

System.out.println(“Rollno=”+rollno);
}
}

We use + symbol(Concat) to add. If we want to add any argument to first argument, we use +.

Method:

 In Java, a method is like a function which is used to expose the behavior of


an object.
 Code reusability and code optimization are the advantages of methods in
Java.
 Method are defined inside the class in Java.
 Methods are defined outside the class in C++.

 Method Syntax:
returntype methodname(argument, argument)
{
-----------
--------- //body
----------
}
voidset( ) is the method from above class example.

 Object:
 The instance of class is called object.
 Syntax:
Classname objectname = new Classname( );
Student s = new Student( );
 Here, new keyword allocates memory dynamically.

 How do we access methods of class:


 object_name.instance variable;
(or)
objectname.methodname(argument);
 Operator is used to access the members of the class.

class Add
{
int a, b, t; //instance variables create separate copies for a,b,c and t when objcre
void sum()
{
a=13
b=7
t=a+b;
system.out.println(“Sum of the two numbers =” +t)
}
}
class Madd
{
public static void main(string args[]);
{
Add obj = new add();
obj.sum();
}
}

 Execution starts from main class which is ‘public static void main(string args[]); in the
above program.

 We have to save program with main class name only (i.e.) Madd.java

 Adding instance fields and methods

 Instance Methods are the group of codes that performs a particular task. Sometimes
the program grows in size, and we want to separate the logic of the main method from
other methods.
 Instance methods can access instance variables and instance methods directly and
undeviatingly.
 Instance methods can access static variables and static methods directly.
 Syntax:
modifier return_type method_name( )
{
method body;
}
 Exmaple:
public void disp( )
{
int a= 10;
System.out.println(a);
}
 Calling Instance Method:
 You cannot call an instance method in the static method directly, so the instance
method can be invoked using an object of the class. As we know java program
starts from the main method is static. So first we have to call class object then we
can call the instance method in the main method.

 Instance Method with Parameter:


 Instance method with parameter takes the argument when it is called in the main
method.
Syntax:
modifier return_typemethod_name( parameter list)
{
method body;
}

 Example:
// Java program to see how can we call
// an instance method with parameter
importjava.io.*;
class Luck {
// static method
Public static void main (String[] args) {
// creating object
LUCK obj = new Luck();
// calling instance method by passing value
obj.add(2,3);
System.out.println("LUCK!");
}
// Instance method with parameter
Void add(int a, int b)
{
// local variables
Int x= a;
Int y= b;
Int z= x + y;
System.out.println("Sum : "+ z);
}
}
output:
Sum : 5
LUCK !

 There are two types of Instance methods in Java:


1. Accessor Method (Getters)
2. Mutator Method (Setters)

 The accessor method is used to make the code more secure and increase its protection
level, accessor is also known as a getter. Getter returns the value that returns the value
of data type int, string, double, float, etc. For the convenience of the program, getter
starts with the word “get” followed by the variable name.
 The mutator method is also known as the setter. It sets the value for any variable which is
used in the programs of a class and starts with the word “set” followed by the variable
name.
 Getter and Setter make the programmer convenient in setting and getting the value for a
particular data type. In both getter and setter, the first letter of the variable should be
capital.
 Accessor and mutator are mainly used to access or set the value for the private member
of the class in the main method.
Constructors:

 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.

 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: Default constructor, and parameterized
constructor.

Rules for creating Java constructor

 There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.


Syntax of default constructor:
class Class_name()
{
--------
---------
}
Example:

//Java Program to create and call a default constructor


class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:

Bike is created

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

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

 Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
//Java Program to demonstrate the use of the parameterized constructor.
class Student
{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student s1 = new Student4(111,"Karan");
Student s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Output:

111 Karan

222 Aryan

Constructor Overloading in Java

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.

PROGRAM :

Class Add

{
Int x,y,total;

Add( ) // 0 order constructor

x=10;

y=20;

}
Add (int x)

x=a;

y=a;

Add(int a, int b )

x=a;

y=b;

Void sum()

Total=x+y;

System.out.println(“sum=”+total);

}
}
class Madd

public static void main(String[]

args);

Add 01=new Add();


Add 02= new Add(30);

Add 03 = new Add(40,30);

01.sum();

02.sum();

03.sum();

METHOD OVERLOADING:

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

Example program:

class mo

Void add (int a , int b )

{
System.out.println(“sum=”+(a+b))’;

Void add(int x, int y, int z);

System.out.println(“sum”+(a+b+c));

}
void add (float x, float y)

{
system.out.println(“sum”+(x+y));

}//class closed

Class Mmo

{
Public static void main(string []args);

mo obj =new mo();

obj .add(10,20);

obj.add(10.20,10.40);

obj.add (10,20,30);

}
}

Difference between constructor and method in Java

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

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of 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 constructor The method is not provided by the compiler in any
if you don't have any constructor in a class. case.

The constructor name must be same as the class The method name may or may not be same as the
name. class name.

Java Copy Constructor

There is no copy constructor in Java. However, we can copy the values from 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:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
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.

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();
}
}

Output:

111 Karan

111 Karan

Access specifiers

The access specifiers in Java specifies the accessibility / scope of a field, method, constructor or
class.

We can change the access levels of the fields, constructors and class by applying access
specifiers / modifiers on it.

They are of 4 types:


1. Private: The access level of the private modifier is only within the class. It can’t be accessed
from outside the class. This is called Data Hiding(so our data is protected).Default vibility is
private.
2. Default: The access level of a default modifier is only within the package. It can’t be
accessed from outside the package. If you don’t specify any access level it will be default.
3. Protected: Protected members are accessed with that class members and immediately
derived class members. It is possible in inheritance.
4. Public: The access level of public modifier is everywhere. It ca be accessed within the class,
outside the class, within the package, outside the package.

Variables:
A variable is the name of a reserved area allocated in the memory.
It is the combo of Varry and Able (Varry + Able) which means the value can be changed.
It is of 3 types. They are
1) Local Variable: A variable which is declares inside the body of the method / method
parameter is called as local variable.
Example:
Void add ()
{
Int x; // local variable
}
(OR)
Void add(int x) // int x is the local variable

2) Instance Variable: A variable which is declared inside the class but outside the method.
Example:

Class Book
{
Int a, b; // Instance Variable
Public static void main(string args[])
}
{
------------
----------
}

3) Static Variable: A variable which is declared with the help of static keyword is called as
static variable.
Example:
Static int a;
// We can use this anywhere in the program

Use of Static and Final Keyword:

Static Keyword:

 A class consists of variables and methods.


 An object is created from a class, this object can be used to call variables and methods.
 When a class member is declared as static, it doesn’t require to create an object to call
methods and variables. Instead, the class name can be used to call it. In other words, static
is a keyword that belongs to class rather than to object.
 The static variable gives memory only once in the class area at the time of class loading.
 The main advantage of this variable is that it helps to save memory. It makes a program
memory efficient.

 The static keyword in Java is used for memory management mainly.

Final Keyword:

 It is a keyword to restrict the user.


 It can be used in variables, methods and a class.
 A value of final variable can’t be changed.
 Any variable declared by using final keyword is called final variable
 They can be declared by static keyword in Java and treated as constant.
Objects as Parameters

A method can take an objects as a parameter. For example, in the following program, the
method setData( ) takes three parameters. The first parameter is a Data object. If you pass an
object as an argument to a method, the mechanism that applies is called pass-by-reference,
because a copy of the reference contained in the variable is transferred to the method, not a
copy of the object itself.
class Data {
int data1;
int data2;
}
class setData{
void setData(Data da,int d1,int d2)
{
da.data1 = d1;
da.data2 = d2;
}
void getData(Data da)
{
System.out.println(“data1 : “+da.data1);
System.out.println(“data2 : “+da.data2);
}
}
public class Javaapp{
public static void main(String[] args){
Data da = new Data();
SetData sd = new setData();
sd.setData(da,50,100);
sd.getData(da);
}
}
Output:
data1 : 50
data2 : 100

Difference between the instance variable vs local variable:

Instance Variable Local Variable

They are defined in class but outside the They are defined as a type of variable declared
body of methods. within programming blocks.

These variables are created when an These variables are created when a block, method
object is instantiated and are accessible or constructor is started and the variable will be
to all constructors, methods, or blocks in destroyed once it exits the block, method, or
class. constructor.

These variables are destroyed when the These variables are destroyed when the
object is destroyed. constructor or method is exited.

It can be accessed throughout the class. Its access is limited to the method in which it is
declared.

They are used to reserving memory for They are used to decreasing dependencies
data that the class needs and that too for between components I.e., the complexity of code
the lifetime of the object. is decreased.

These variables are given a default value These variables do not always have some value,
if it is not assigned by code. so there must be a value assigned by code.

It is not compulsory to initialize instance It is important to initialize local variables before


variables before use. use.

It includes access modifiers such as It does not include any access modifiers such as
private, public, protected, etc. private, public, protected, etc.

INTRODUCTION TO OBJECT CLASS

Object class is present in java.lang package. Object Class in Java is the topmost class
among all the classes in Java. We can also say that the Object class in Java is the parent class for
all the classes. It means that all the classes in Java are derived classes and their base class is the
Object class.All the classes directly or indirectly inherit from the Object class in Java.

Consider the example-

Class Vehicle{
//body of class Vehicle
}

Here we can see that the class Vehicle is not inheriting any class, but it inherits the Object class.
It is an example of the direct inheritance of object class.

Now, look at this example-

Class Vehicle{
//body of class Vehicle
}
Class Car extends Vehicle{
//body of class Car
}

Here we can see that the Car class directly inherits the Vehicle class. The extends keyword is
used to establish inheritance between two classes. But we have seen in the above example that if
we define a class without inheriting it from some other class, it directly inherits the Object class.
Since Car inherits the Vehicle and the Vehicle inherits the Object class, the Car indirectly
inherits the Object class.
User Input from Keyboard
Accepting keyboard input in Java is done using a Scanner object.

Scanner console = newScanner(System.in)

This statement declares a reference variable named console. The Scanner


object is associated with standard input device (System.in).
To get input from keyboard, you can call methods of Scanner class. For
example in following statmentnextInt() method of Scanner takes an integer
and returns to variable x :

int x = console.nextInt();

You might also like