0% found this document useful (0 votes)
5 views

Unit1 Notes

Java is a high-level, object-oriented programming language known for its platform independence and security features. It supports various applications, including desktop, web, and mobile applications, and follows the principles of Object-Oriented Programming (OOP). The document also covers Java's history, features, the Java Virtual Machine (JVM), data types, and the structure of Java programs.
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)
5 views

Unit1 Notes

Java is a high-level, object-oriented programming language known for its platform independence and security features. It supports various applications, including desktop, web, and mobile applications, and follows the principles of Object-Oriented Programming (OOP). The document also covers Java's history, features, the Java Virtual Machine (JVM), data types, and the structure of Java programs.
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
You are on page 1/ 31

UNIT I

I. INTRODUCTION TO JAVA

What is Java

Java is a high Level programming language and it is also called as a


platform. Java is a secured and robust high level object-oriented
programming language.

Platform: Any software or hardware environment in which a program runs


is known as a platform. Java has its own runtime environment (JRE) and
API so java is also called as platform.

Java fallows the concept of Write Once, Run Anywhere.

Application of java

1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc

History of Java

James Gosling, Patrick Naughton and Mike Sheridan initiated the Java
language project in 1991. Team of sun engineers designed for small,
embedded systems in electronic appliances like set-top boxes. Initially it was
called "Greentalk" later it was called Oak .

Java is an open source software produced by Sunmicro system under the


terms of the GNU General Public License (GPL) .
Features of Java:

Object Oriented Java implements basic concepts of Object oriented


programming System (OOPS) ie Object, Class, Inheritance,
Polymorphism, Abstraction, Encapsulation. In Java, everything is an
Object. Java can be easily extended since it is based on the Object
model.
Platform Independent
including C and C++, when Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code.
This byte code is distributed over the web and interpreted by the
Virtual Machine (JVM) on whichever platform it is being run on.
Simple Java fallows the basic Syntax of C,C++. If you understand
the basic concept of OOPS then it is easy to master in java.
Secure lop virus-free,
tamper-free systems. Authentication techniques are based on public-
key encryption.
Architecture-neutral -
neutral object file format, which makes the compiled code executable
on many processors, with the presence of Java runtime system.
Portable -neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler
in Java is written in ANSI C with a clean portability boundary, which
is a POSIX subset.
Robust
emphasizing mainly on compile time error checking and runtime
checking.
Multithreaded
write programs that can perform many tasks simultaneously. This
design feature allows the developers to construct interactive
applications that can run smoothly.
Interpreted
machine instructions and is not stored anywhere. The development
process is more rapid and analytical since the linking is an
incremental and light-weight process.
High Performance -In-Time compilers, Java
enables high performance.
Distributed
internet.
Dynamic
since it is designed to adapt to an evolving environment. Java
programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.

Object Oriented Programming System(OOPS)

Object means a real word entity such as pen, chair, table etc. Object-
Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies the software development and
maintenance by providing some concepts:

Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

If any language fallows the OOPS concepts that language we call it as object
oriented language

Procedure to write simple java Program

To write a java program First we have install the JDK.

To create a simple java program, you need to create a class that contains
main method. Let's understand the requirement first.

install the JDK and install it.


set path of the jdk
create the java program
compile and run the java program

Setting Up the Path for Windows

Assuming you have installed Java in c:\Program Files\java\jdk

Right-click on 'My Computer' and select 'Properties'.


Click the 'Environment variables' button under the 'Advanced' tab.
Now, alter the 'Path' variable so that it also contains the path to the
Java executable. Example, if the path is currently set to
'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java


binaries have been installed. Refer to your shell documentation, if you have
trouble doing this. For Example if you use bash as your shell, then you
would add the following line to the end of your '.bashrc: export PATH =
/path/to/java:$PATH'

Popular Java Editors

Notepad
like Notepad (Recommended for this tutorial), TextPad.
Netbeans -source and free which can be
downloaded from Eclipse open-
source community and can be downloaded from

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified.


But implementation provider is independent to choose the algorithm.
Its implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

Loads code
Verifies code
Executes code
Provides runtime environment

JVM provides definitions for the:

Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.

JAVA VIRTUAL MACHINE

code. Rather, it is bytecode. Bytecode is a highly optimized set of


instructions designed to be executed by the Java run-time system, which is
called the Java Virtual Machine (JVM).

Java complier translates the java source code into byte code or intermediate
code ,not the executable file .JVM take the byte code and convert into
executable code corresponding to Operating system

Because of the above feature java is portable

II.CLASS, OBJECT AND METHODS

Java program is a collection of objects that communicate via invoking each


other's methods. We now briefly look into class, object, methods, and
instance variables.
Class
behavior/state that the object of its type supports.

A class is declared by use of the class keyword. A simplified general form of


a class definition is shown here:

class classname

type instance-variable1; type instance-variable2;

// ... type instance-variableN;

type methodname1(parameter-list)

{ // body of method }

type methodname2(parameter-list)

{ // body of method }

// ... type methodnameN(parameter-list)

{ // body of method } }

The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and
variables defined within a class are called members of the class. In most
classes, the instance variables are acted upon and accessed by the methods
defined for that class

Simple Class

Class Sample

int len, float ht

void get()

{ // body
} }

Here a class Sample contains two variable len and ht

Object in Java

Object is the physical as well as logical entity whereas class is the logical
entity only.

An object has three characteristics:

state: represents data (value) of an object.


behavior: represents the behavior (functionality) of an object such as
deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. But, it is used
internally by the JVM to identify each object uniquely.

Object is an instance of a class. Class is a template or blueprint from


which objects are created. So object is the instance(result) of a class.

Object Definitions:

Object is a real world entity. Object is a run time entity.


Object is an entity which has state and behavior.
Object is an instance of a class.

Sample s=new Sample() here s is an object for the class Sample

new operator is used to create an object

Methods
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.

Let's create the Simple java program:

1. class Sample{
2. public static void main(String args[]){
3. System.out.println("How are you ");
4. }
5. }

save this file as Sample.java


To compile: javac Sample.java

To execute: java Sample

Java Identifiers

All Java components require names. Names used for classes, variables, and
methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as

All identifiers should begin with a letter (A to Z or a to z), currency


character ($) or an underscore (_).
After the first character, identifiers can have any combination of
characters.
A key word cannot be used as an identifier.
Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.

Java Modifiers:

Access Modifiers
Non-access Modifiers

III DATA TYPES

Primitive Data Types


Non Primitive Types
Primitive Data Types

There are eight primitive data types supported by Java. Primitive data types
are predefined by the language and named by a keyword. Let us now look
into the eight primitive data types in detail.

byte

Byte data type is an 8-bit signed two's complement integer


Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50

short

Short data type is a 16-bit signed two's complement integer


Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int

Int data type is a 32-bit signed two's complement integer.


Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values
unless there is a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000

long

Long data type is a 64-bit signed two's complement integer


Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L

float

Float data type is a single-precision 32-bit IEEE 754 floating point


Float is mainly used to save memory in large arrays of floating point
numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f

double

double data type is a double-precision 64-bit IEEE 754 floating point


This data type is generally used as the default data type for decimal
values, generally the default choice
Double data type should never be used for precise values such as
currency
Default value is 0.0d
Example: double d1 = 123.4

boolean

boolean data type represents one bit of information


There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true

char

char data type is a single 16-bit Unicode character


Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'

Java Literals

A literal is a source code representation of a fixed value. Literals can be


assigned to any primitive type variable.

byte a = 68; char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10),


hexadecimal(base 16) or octal(base 8) number systems as well.

Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when

int decimal = 100; int octal = 0144; int hexa = 0x64;

String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes.

Example
"Hello World" "two\nlines" "\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For
char a = '\u0001'; String a = "\u0001";

Java language supports few special escape sequences for String and char

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t Tab

\" Double quote


\' Single quote

\\ Backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Java Variable Example: Add Two Numbers

1. class Sample{
2. public static void main(String[] args){
3. int i=50;
4. int j=60;
5. int k=a+b;
6. System.out.println(k);
7. } }

Java Variable Example: Widening

1. class Sample{
2. public static void main(String[] args){
3. int j=10;
4. float k=a;
5. System.out.println(i);
6. System.out.println(j);
7. }}

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

Before Unicode, there were many language standards:

ASCII (American Standard Code for Information Interchange) for the


United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
Java Tokens

Java Tokens are the smallest individual building block or smallest unit of a
Java program, it is used by the Java compiler for constructing expressions
and statements. Java program is collection different types of tokens,
comments, and white spaces.
Java Supports Five Types of Tokens:

Reserved Keywords Identifiers Literals


Operators Separators

Java Keywords can not be used as a variable name.

Abstract Assert boolean break


Byte Case catch char
Class Const continue default
Do Double else enum
extends Final finally float
For Goto if implements
Import Instanceof int interface
Long Native new package
private Protected public return
Short Static strictfp super
Switch synchronized this throw
throws Transient try void
volatile While true false
Null

Variable

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.

There are three types of variables in java:

local variable
instance variable
static variable
1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is
called instance variable . It is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be


local.

We will have detailed learning of these variables in next chapters.

IV OPERATORS & IF, Switch, loop Statements

Operators in java

Operator in java is a symbol that is used to perform operations. For


example: +, -, *, / etc.

There are many types of operators in java which are given below:

Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java If-else Statement

The Java if statement is used to test the condition. It checks boolean


condition: true or false. There are various types of if statement in java.

if statement if-else statement


if-else-if ladder nested if statement

Java IF Statement

The Java if statement tests the condition. It executes the if block if condition
is true. The following is the syntax

1. if(condition){
2. //code to be executed
3. }

1. public class Example {


2. public static void main(String[] args) {
3. int k=35;
4. if(k>18){ System.out.print("Hello");
5. } } }

IF-else Statement

The if-else statement in java tests the condition. It executes the if block if
condition is true otherwise else block is executed.

Syntax:

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

public class Sample {


public static void main(String[] args) {
int n=23;
if(number%2==0){
System.out.println("even ");
}else{
System.out.println("odd ");
} }
}
IF-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple


statements.

Syntax:

1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }

1. public class Simple {


2. public static void main(String[] args) {
3. int marks=70;
4.
5. if(marks<40){
6. System.out.println("FAIL");
7. }
8. else if(marks>=40 && marks<50){
9. System.out.println("D grade");
10. }
11. else if(marks>=50 && marks<60){
12. System.out.println("C grade");
13. }
14. else if(marks>=60 && marks<70){
15. System.out.println("B grade");
16. }
17. else if(marks>=70 && marks<80){
18. System.out.println("A grade");
19. }else if(marks>=80 && marks<100){
20. System.out.println("A+ grade");
21. }else{
22. System.out.println("Invalid!");
23. }
24. }
25. }
Switch Statement

The switch statement in java executes one statement from multiple


conditions. It is like if-else-if ladder statement.

Syntax:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Example:

1. public class Sample {


2. public static void main(String[] args) {
3. int k=20;
4. switch(k){
5. case 10: System.out.println("10");break;
6. case 20: System.out.println("20");break;
7. case 30: System.out.println("30");break;
8. default:System.out.println("Not in 10, 20 or 30");
9. } }
10. }

Java For Loop

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 loop in java.

Simple For Loop


For-each or Enhanced For Loop
Labeled For Loop
Java Simple For Loop

The simple for loop is same as C/C++. We can initialize variable, check
condition and increment/decrement value.

Syntax:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }

Example:

1. public class Sample {


2. public static void main(String[] args) {
3. for(int i=1;i<=20;i++){
4. System.out.println(i);
5. }
6. }
7. }

Java 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:

1. while(condition){
2. //code to be executed
3. }

1. public class Sample {


2. public static void main(String[] args) {
3. int j=1;
4. while(j<=10){
5. System.out.println(j);
6. j++;
7. }
8. } }

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

public class Example {

public static void main(String[] args) {

int j=1;

do{ System.out.println(j);

j++;

}while(j<=10);

} }

Java Break Statement

The Java break 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.

Example:

1. public class Simple {


2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. System.out.println(i);
8. }
9. }
10. }

Java Continue Statement

The Java continue statement is used to continue loop. It continues the


current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.

Example:

1. public class Sample {


2. public static void main(String[] args) {
3. for(int k=1;k<=10;k++){
4. if(k==5){
5. continue;
6. }
7. System.out.println(k);
8. }
9. }
10. }

V ARRAYS & COMMENTS in JAVA

Array in java

Array is group of elements of similar types occupying contiguous memory


locations

Advantage of Java Array

Code Optimization Random access

Disadvantage of Java Array is it has fixed size it cannot grow

There are two types of array in java .

Single Dimensional Array


Multidimensional Array

Single Dimensional Array in java


Syntax to Declare an Array in java

1. datatype[] arrayname (or)


2. datatype []arrayname; (or)
3. datatype arrayname[];

Array initialization in java

1. arrayname=new datatype[size];

Example

Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
1. class Testarray{
2. public static void main(String args[]){
3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10; a[1]=20; a[2]=70; a[3]=40; a[4]=50;
5. for(int i=0;i<a.length;i++)//length is the property of array
6. System.out.println(a[i]);
7. }}

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10. }}

Multidimensional array in java

In such case, data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Multidimensional Array in java

1. dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or)


2. dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional java array

Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

1. class Ex{
2. public static void main(String args[]){
3.
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
10. System.out.print(arr[i][j]+" ");
11. }
12. System.out.println();
13. }
14. } }

Java Comments

The java comments are 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 for specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

1. //This is single line comment


Example:

1. public class Sample{


2. public static void main(String[] args) {
3. int j=10;//Here, i is a variable
4. System.out.println(j);
5. }
6. }

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:

1. /*
2. This
3. is
4. multi line
5. comment
6. */

Example:

1. public class CommentExample2 {


2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int j=10;
6. System.out.println(j);
7. }
8. }

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create


documentation API, you need to use javadoc tool.

Syntax:

1. /**
2. This
3. is
4. documentation
5. comment
6. */

VI CONSTRUCTORS

Constructor is special member function ,it has the same name as class
name. It is called when an instance of object is created and memory is
allocated for the object.

It is a special type of method which is used to initialize the object

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

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


parameter.

class Sample{
Sample()
{
System.out.println("Sample is created");
}
public static void main(String args[])
{
Sample b=new Sample();
} }

A constructor which has a specific number of parameters is called


parameterized constructor.
1. class Student4{
2. int id;
3. String name;
4. Student4(int i,String n){
5. id = i;
6. name = n;
7. }
8. void display(){System.out.println(id+" "+name);}
9.
10. public static void main(String args[]){
11. Student4 s1 = new Student4(111,"Karan");
12. Student4 s2 = new Student4(222,"Aryan");
13. s1.display();
14. s2.display();
15. }
16. }

Difference between constructor and method in java

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

Java Constructor Java Method


Constructor is used to initialize the state of Method is used to expose
an object. behaviour of an object.
Method must have return
Constructor must not have return type.
type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default
Method is not provided by
constructor if you don't have any
compiler in any case.
constructor.
Constructor name must be same as the Method name may or may not
class name. be same as class name.

Java static keyword

The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class.
The static keyword belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable

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

The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
The static variable gets memory only once in class area at the time of
class loading.

Advantage of static variable: It makes your program memory


efficient (i.e it saves memory).
class Stud{
int rollno;
String name;
static String college ="ITS";
Stud(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Stud s1 = new Stud(11,"Krishna");
Stud s2 = new Stud(22,"Rama");
s1.display();
s2.display();
} }

2) Java static method

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

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


A static method can be invoked without the need for creating an
instance of a class.
static method can access static data member and can change the
value of it.

Example of static method


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

2.
3. class Stud{
4. int rollno;
5. String name;
6. static String college = "BEC";
7.
8. static void change(){
9. college = "JBIEIT";
10. }
11. Stud(int r, String n){
12. rollno = r;
13. name = n;
14. }
15.
16. void display (){System.out.println(rollno+" "+name+" "+college
);}
17. public static void main(String args[]){
18. Stud.change();
19. Stud s1 = new Stud (11,"Kiran");
20. Stud s2 = new Stud (22,"Arjun");
21. Stud s3 = new Stud (33,"srinu");
22. s1.display();
23. s2.display();
24. s3.display();
25. }
26. }

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

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) 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.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display(); }}
2) 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

1. class B{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. B b=new B();
12. b.n();
13. }}

3) 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:

1. class B{
2. B(){System.out.println("hello ");}
3. B(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class Sample{
9. public static void main(String args[]){
10. B a=new B(10);
11. }}

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "
+fee);}
15. }
16. class SamplTest{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is


mainly used in the event handling. Let's see the example:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have
to use one object in multiple classes. Let's see the example:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case,
return type of the method must be the class type (non-primitive). Let's see
the example:

Syntax of this that can be returned as a statement

1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement
from the method

1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }

You might also like