Sie sind auf Seite 1von 101

Introduction to

Java

Session Objectives

Introduction to Java

Java Features
Java Architecture

Structure of Java Program


Programming Constructs
Features of Object Oriented Programming Model

History of Java
Java began as Programming Language Oak.
Oak - Developed by members of Green Project, which included James
Gosling and 2 more people in 1991 to create products for electronics
market.
Existing programming languages were not suited for the same.
Chief Programmer of Sun Microsystems, James Gosling, was given the
task of creating software for controlling consumer electronic devices.
The requirement of Software was to run on different kinds of computers,
should have power of networks and be based on web.
Members of the Oak team realized that Java would provide the required
cross platform independence that is independent from hardware,network
and OS.

Features of Java

Java is an Internet programming language:

Java programs can be used to access data existing


across the network irrespective of the source platform
Java is secure:

Due to the strong type-checking done by Java any


changes made to the program are tagged as errors and
the program will not execute. Java is, therefore, secure

Java is a high-performance language:


Java programs are comparable in speed to the programs written in
other compiler-based languages like C and C++. Java programs
are faster than the programs written in other interpreter-based
languages, such as BASIC

Java is simple:
The syntax of Java is similar to C++. Java does not support
pointers, multiple inheritance, goto statement, and operator
overloading

Features that slow down application development cycle have


been omitted in Java

Java Memory Management


Java prevents errors that arise due to improper memory
usage because in Java, programmers do not need to
manipulate memory

Java vs. C++:


Java is a pure object-oriented language because every
statement in Java is written inside a class. In C++, the main()
method is always written outside any class
In Java, all the data types except the primitive types are
objects. Even the primitive data types can be encapsulated
inside classes
Data types:

Java has two additional primitive data types besides the


ones available in C++

The byte data type of Java occupies one byte of memory space and
can store integral numbers
The other data type boolean can store any one of the two
boolean values, true and false
Java omits pointers and structs that are available in C++

In Java, the char data type stores characters in Unicode format


unlike the 8-bit ASCII format in C++. Unicode is a 16-bit
character format that can store Asian language alphabets
Data types in Java have a fixed size, regardless of the operating
system used

The Java Runtime Environment

The Java application environment performs as follows:

JVM Tasks

The JVM performs three main tasks:


Loads code Performed by the class loader.
Verifies code Performed by the bytecode verifier.
Executes code Performed by the runtime interpreter.

The Class Loader

Loads all classes necessary for the execution of a program.


Maintains classes of the local file system in separate
namespaces.
Avoids execution of the program whose bytecode has been
changed illegally.

The Bytecode Verifier

All class files imported across the network pass through the
bytecode verifier, which ensures that:
The code adheres to the JVM specification.
The code does not violate system integrity.
The code causes no operand stack overflows or underflows.
The parameter types for all operational code are correct.
No illegal data conversions (the conversion of integers to
pointers) have occurred.

Java Technology Runtime Environment

Structure of Java Program

Sample Application:- Welcome.java

public class Welcome


{

public static void main(String args[])


{

System.out.println(Hello);
}
}

JDK Versions

JDK 1.02 (1995)


JDK 1.1 (1996)
Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)

JDK Editions
Java Standard Edition (J2SE)

- J2SE can be used to develop client-side standalone


applications or applets.
Java Enterprise Edition (J2EE)

- J2EE can be used to develop server-side applications


such as Java servlets and Java ServerPages.
Java Micro Edition (J2ME).

- J2ME can be used to develop applications for mobile


devices such as cell phones.
This book uses J2SE to introduce Java programming.

Java IDE Tools


Forte by Sun MicroSystems
Borland JBuilder
Microsoft Visual J++
WebGain Caf
IBM Visual Age for Java

Getting Started with Java Programming

A Simple Java Application


Compiling Programs
Executing Applications

A Simple Application
Example 1.1
//This application program prints Welcome
//to Java!
package chapter1;
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

Source

Run
NOTE: To run the program,
install slide files on hard
disk.

Creating and Compiling Programs


On command line

Create/Modify Source Code

- javac file.java
Source Code

Compile Source Code


i.e. javac Welcome.java
If compilation errors

Bytecode

Run Byteode
i.e. java Welcome

Result

If runtime errors or incorrect result

How it works!
Compile-time Environment

Compile-time Environment
Class
Loader
Bytecode
Verifier

Java
Source
(.java)

Java
Compiler

Java
Bytecodes
move locally
or through
network

Java
Interpreter

Just in
Time
Compiler

Runtime System

Java
Bytecode
(.class )

Operating System

Hardware

Java
Class
Libraries

Java
Virtual
machine

How it works!

Java is independent only for one reason:

- Only depends on the Java Virtual Machine (JVM),


- code is compiled to bytecode, which is interpreted by
the resident JVM,
- JIT (just in time) compilers attempt to increase speed.

Executing Applications
On command line

- java classname

Bytecode

Java
Interpreter
on Windows

Java
Interpreter
on Linux

...

Java
Interpreter
on Sun Solaris

Example
javac Welcome.java

java Welcome
output:...

In Java, the main() method and the class in which it is


defined should be declared public because the Java
runtime environment has to access the main() method to
execute a program
The main() method should be declared static because it
has to exist before any object of the class is created
The command line parameter is a String type variable
main(String args[]). The number of arguments is
determined by the String class object

The String Object:


In Java, a String is a real object and not an array of nullterminated characters as in C++
In Java, the String objects are consistent. The way in
which strings are obtained and the string elements are
accessed is consistent across all systems. They have welldefined programming interfaces
In Java, the String objects are reliable. They do not give
rise to memory leaks in a program

Java uses all the system resources such as the display device
and the keyboard with the help of the System class. This class
contains all the methods that are required to work with the
system resources
The out object encapsulated inside the System class
represents the standard output device. This object contains the
println() method
The println() method displays data on the screen

Executing a Java Program:

Java programs are executed by a program called the Java


Virtual Machine (JVM). The JVM contains the runtime
environment and the class loader
You must save a Java source file with the .java extension.
The name of the file should be the same as the public class
name
When you compile a .java file, a .class file is created

To compile a file, you use the javac utility.

To execute a .class file, you use the java utility


For example, to compile and execute a class Welcome:
Save the file as Welcome.java
At the command prompt, type
javac Welcome.java <Enter>

At the command prompt, type


java Welcome <Enter>

Data Types In Java


Java has eight primitive types of data:
byte, short, int, long, char, float, double,
and boolean.These can be put in four groups:
1.Integers includes byte, short, int, and long
2.Floating-point numbers includes float and
double
3.Characters includes char, like letters and
numbers.
4.Boolean includes boolean representing
true/false values

Data Types

Data Types

int
It is a 32-bit signed two's complement integer data type. It ranges from 2,147,483,648 to 2,147,483,647. This data type is used for integer values.
However for wider range of values use long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from 128 to127 (inclusive). We can save memory in large arrays using byte. We can
also use byte instead of int to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from 32,768 to 32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type
with larger range of values.

Data Types
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges
from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or
negative). Use a float (instead of double) to save memory in large arrays. We do
not use this data type for the exact values such as currency. For that we have to
use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or
negative). This data type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use
this data type for conditional statements. true and false are not the same as True
and False. They are defined constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0
to 65,535. They are not same as ints, shorts etc.

Size for Java's Primitive Types

Type
int

Explanation
A 32-bit (4-byte) integer value

short

A 16-bit (2-byte) integer value

long

A 64-bit (8-byte) integer value

byte

An 8-bit (1-byte) integer value

float

A 32-bit (4-byte) floating-point value

double
char

A 64-bit (8-byte) floating-point value


A 16-bit character using the Unicode encoding scheme

Identifiers

Identifiers are used for class names,method names and variable names.
Identifier may be any descriptive sequence of upper case and lower case
characters, numbers, or the underscore and dollar sign characters.
They must not begin with number.
Java is case-sensitive, so VALUE is different identifier than Value.

Java Reserve Keywords

abstract

continue

goto

package

synchronized

assert

default

if

private

this

boolean

do

implements

protected

throw

break

double

import

public

throws

byte

else

instanceof

return

transient

case

extends

int

short

try

catch

final

interface

static

void

char

finally

long

strictfp

volatile

class

float

native

super

while

const

for

new

switch

Variables
The variable is an identifier that denotes a storage location used to store a data
value.
A variable name can be choosen by the programmer in a meaningful way so as to
reflect what it represents in the program. Variable names may consist of alphabets,
digits, the underscore(_) and dollar character, subject to the following conditions:

They must not begin with a digit


Uppercase and lowercase are distinct.
It should not be a keyword
white space is not allowed
variable names can be of any length

Declaration of Variables
The general form of variable declaration is:

type variable1, variable2, ........, variableN;


Example:
int count;
byte b;
char c2;

Variables and Scope

Variables defined inside a method are called local variables,


also referred to as automatic, temporary, or stack variables.
Local variables must be initialized before the first use.
Variables defined outside a method are created when the
object is constructed using the new xxx() call. They are of two
types:
Static variables: They are created when the class is loaded
and continue to exist for as long as the class is loaded.
Instance variables: They are declared without using the
static keyword. They continue to exist for as long as the
object exists.

Primitive Types and Variables

boolean, char, byte, short, int, long, float, double etc.


These basic (or primitive) types are the only types that are not objects (due to
performance issues).
This means that you dont use the new operator to create a primitive variable.
Declaring primitive variables:

float initVal;
int retVal, index = 2;
double gamma = 1.2, brightness
boolean valueOk = false;

Initialisation

If no value is assigned prior to use, then the compiler will give an error
Java sets primitive variables to zero or false in the case of a boolean variable
All object references are initially set to null
An array of anything is an object

- Set to null on declaration


- Elements to zero false or null on creation

Declarations

int index = 1.2;


// compiler error
boolean retOk = 1;
// compiler error
double fiveFourths = 5 / 4; // no error!
float ratio = 5.8f;
// correct
double fiveFourths = 5.0 / 4.0; // correct
1.2f is a float value accurate to 7 decimal places.
1.2 is a double value accurate to 15 decimal places.

Assignment

All Java assignments are right associative

int a = 1, b = 2, c = 5
a=b=c
System.out.print(
a= + a + b= + b + c= + c)
What is the value of a, b & c
Done right to left: a = (b = c);

Basic Mathematical Operators

* / % + - are the mathematical operators


* / % have a higher precedence than + or double myVal = a + b % d c * d / b;

Is the same as:


double myVal = (a + (b % d))
((c * d) / b);

Statements & Blocks

A simple statement is a command terminated by a semi-colon:


name = Fred;
A block is a compound statement enclosed in curly brackets:
{
name1 = Fred; name2 = Bill;
}
Blocks may contain other blocks

Flow of Control

Java executes one statement after the other in the order they are written
Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping:
for, while, do while
Escapes:
break, continue, return

If The Conditional Statement

The if statement evaluates an expression and if that evaluation is true then the specified
action is taken

if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10
It could have been written:

if ( x < 10 )
x = 10;
Or, alternatively:

if ( x < 10 ) { x = 10; }

Relational Operators

==
!=
>=
<=
>
<

Equal (careful)
Not equal
Greater than or equal
Less than or equal
Greater than
Less than

If else

The if else statement evaluates an expression and performs one action if that evaluation
is true or a different action if it is false.
if (x != oldx) {

System.out.print(x was changed);


}
else {
System.out.print(x is unchanged);
}

Nested if else

if ( myVal > 100 ) {


if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(myVal is in range);
}

else if

Useful for choosing between alternatives:

if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute
code block #3
}

A Warning

WRONG!
if( i == j )

if ( j == k )
System.out.print(
i equals k);
else
System.out.print(
i is not equal
to j);

CORRECT!
if( i == j ) {
if ( j == k )
System.out.print(
i equals k);
}
else
System.out.print(i is
not equal to j); //
Correct!

The switch Statement


switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
//execute code block #4
break;
}

The for loop

Loop n times

for ( i = 0; i < n; n++ ) {


// this code body will execute n times
// ifrom 0 to n-1
}
Nested for:

for ( j = 0; j < 10; j++ ) {


for ( i = 0; i < 20; i++ ){
// this code body will execute 200 times
}
}

while loops

while(response == 1) {
System.out.print( ID = + userID[n]);
n++;
response = readInt( Enter );
}
What is the minimum number of times the loop
is executed?
What is the maximum number of times?

TYPE CASTING
In some situations we need to store a value of one type into a variable
of another type. In such situations, we must cast the value to be
stored by proceeding ot with the type name in paranthesis.
syntax:
type variable2 = (type) variable2;

do { } while loops

do {
System.out.print( ID = + userID[n] );
n++;
response = readInt( Enter );
}while (response == 1);

What is the minimum number of times the loop


is executed?
What is the maximum number of times?

Break

A break statement causes an exit from the innermost containing while, do, for
or switch statement.

for ( int i = 0; i < maxID, i++ ) {


if ( userID[i] == targetID ) {
index = i;
break;
}
}// program jumps here after break

Continue

Can only be used with while, do or for.


The continue statement causes the innermost loop to start the next iteration immediately

for ( int i = 0; i < maxID; i++ ) {


if ( userID[i] != -1 ) continue;
System.out.print( UserID + i + : +
}

userID);

Arrays

Am array is a list of similar things


An array has a fixed:

- name
- type
- length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution of the code

TYPE CASTING
The process of converting one data type to another is called casting. Casting is often
necessary when a method return a type different than the one we require.
Four integer types can be cast to any other type except boolean. Casting into a smaller
type except boolean. Similarly, the float and double can be cast to any other type
except boolean. But casting to smaller type can result in a loss of data. Casting a
floating point value to an integer will result in a loss of the fractional part.

Example:
int m = 50;
byte n = (byte)m;
long count = (long)m;

TYPE CASTING
The following table , guarantees to result in no loss of information or data.

FROM

TO

byte

short, char, int, long, float, double

short

int, long, float, double

char

int, long, float, double

int

long, float, double

long

float, double

float

double

Casting

Casting means assigning a value of one type to a variable of


another type.
If information might be lost in an assignment, the programmer
must confirm the assignment with a cast.
The assignment between long and int requires an explicit
cast.
Examples of casting are:
long bigValue = 99L;
int squashed = bigValue; // Wrong, needs a cast
int squashed = (int) bigValue; // OK
int squashed = 99L; // Wrong, needs a cast

Promotion and Casting of Expressions

Variables are promoted automatically to a longer form (such


as int to long).
Expression is assignment-compatible if the variable type is at
least as large (the same number of bits) as the expression
type.
For Example:
long bigval = 6; // 6 is an int type, OK
int smallval = 99L; // 99L is a long, illegal
double z = 12.414F; // 12.414F is float, OK
float z1 = 12.414; // 12.414 is double, illegal

Example:
Creation and Casting of variables
class TypeWrap{
public static void main(String args[]) {
System.out.println("Variable Created");
char c= 'x';
byte b=50;
short s=1996;
int i=12345; int j= 123;
long l=12345654321L;
float f1=3.142F; float f2=1.2e-5F;
double d2=0.000000987;
short s1 = (short)b; short s2 = (short)i; // produces incorrect result
float f = (float)i;
int n = (int)f1; // Fractional part is lost
byte b1 = (byte)i; // produces incorrect result
byte b2=(byte)j;
System.out.println(" s1 = " + s1);
System.out.println(" s2 = " + s2);
System.out.println(" f = " + f);
System.out.println(" n = " + n);
System.out.println(" b1 = " + b1);
System.out.println(" b2 = " + b2);
}

Operators

An Operator is a symbol that takes one or more


arguments and operates on them to produce a
result.
Operators are as follows:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Conditional Operators
Special Operators (instance and dot operator)

Operators

Arithmetic Operators

+,-,*,/,%

Increment & Decrement Operators

++,--

Relational Operators

= =,!=,>,<,>=,<=

Logical Operators :->

And,Or,Not

Assignment Operator :->

Ternary Operator

Operators Precedence

()

[]

Highest

++

--

>

>=

==

!=

<

<=

&
&&
||
?:
=

Lowest

Introduction
Classes And Objects

Object Oriented Concepts in Java

Object-oriented concepts form the base of all modern programming


languages. Understanding the basic concepts of object-orientation helps a
developer to use various modern day programming languages, more
effectively.
Object orientation is a software development methodology that is based
on modeling a real-world system.
An object oriented program consists of classes and objects.
Let us understand the termsclass and objects

Classes ARE Object Definitions

OOP - object oriented programming


code built from objects
Java these are called classes
Each class definition is coded in a separate .java file
Name of the object must match the class/object name

The three principles of OOP

Encapsulation

- Objects hide their functions


(methods) and data (instance
variables)
Inheritance

- Each subclass inherits all


variables of its superclass

car

Super class

Polymorphism

- Interface same despite different


data types

manual

draw()

automatic

Subclasses

draw()

Simple Class and Method

Class Fruit{
int grams;
int cals_per_gram;
int total_calories() {
return(grams*cals_per_gram);
}
}

Methods

A method is a named sequence of code that can be invoked by other Java code.
A method takes some parameters, performs some computations and then optionally returns
a value (or object).
Methods can be used as part of an expression statement.
public float convertCelsius(float tempC) {
return( ((tempC * 9.0f) / 5.0f) + 32.0f );
}

Method Signatures

A method signature specifies:

- The name of the method.


- The type and name of each parameter.
- The type of the value (or object) returned by the method.
- The checked exceptions thrown by the method.
- Various method modifiers.
- modifiers type name ( parameter list ) [throws exceptions ]
public float convertCelsius (float tCelsius ) {}
public boolean setUserInfo ( int i, int j, String name ) throws
IndexOutOfBoundsException {}

Public/private

Methods/data may be declared public or private meaning they may or


may not be accessed by code in other classes
Good practice:

- keep data private


- keep most methods private
well-defined interface between classes - helps to eliminate errors

Using objects

Here, code in one class creates an instance of another class and does something
with it

Fruit plum=new Fruit();


int cals;
cals = plum.total_calories();
Dot operator allows you to access (public) data/methods inside Fruit class

Constructors

The line

plum = new Fruit();


invokes a constructor method with which you can set the initial data of an object
You may choose several different type of constructor with different argument lists

eg Fruit(), Fruit(a) ...

Overloading

Can have several versions of a method in class with different


types/numbers of arguments

Fruit() {grams=50;}
Fruit(a,b) { grams=a; cals_per_gram=b;}
By looking at arguments Java decides which version to use

Java Development Kit

javac - The Java Compiler


java - The Java Interpreter
jdb - The Java Debugger
appletviewer -Tool to run the applets

javap - to print the Java bytecodes


javaprof - Java profiler
javadoc - documentation generator
javah - creates C header files

What is a class?

Early languages had only arrays

- all elements had to be of the same type


Then languages introduced structures (called records, or structs)

- allowed different data types to be grouped


Then Abstract Data Types (ADTs) became popular

- grouped operations along with the data

So, what is a class?

A class consists of

- a collection of fields, or variables, very much like


the named fields of a struct
- all the operations (called methods) that can be
performed on those fields
- can be instantiated
A class describes objects and operations defined on those objects

Name conventions

Java is case-sensitive; maxval, maxVal, and MaxVal are three different


names
Class names begin with a capital letter
All other names begin with a lowercase letter
Subsequent words are capitalized: theBigOne
Underscores are not used in names
These are very strong conventions!

The class hierarchy

Classes are arranged in a hierarchy


The root, or topmost, class is Object
Every class but Object has at least one superclass
A class may have subclasses
Each class inherits all the fields and methods of its (possibly
numerous) superclasses

An example of a class

class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name + ' is
now ' + age);
}
}

Creating and using an object

Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );

The Foundation of Object Orientation


An object means a material thing that is capable of being
presented to the senses.
An object has the following characteristics:
It has a state
It may display behavior
It has a unique identity

Objects interact with other objects through messages.


Let us understand these concepts.

Characteristics of the Object-Oriented Approach


Realistic modeling
Reusability
Resilience to change
Existence as different forms

Features of Object Oriented Concepts

1. Data Abstraction

2. Encapsulation
3. Inheritance

4. Polymorphism

Classes
A Class is blueprint that defines the variables and methods common to all
objects of a certain kind. Class is a user-defined data type with a template that
serves to define its properties. Once the class type has been defined, we can
create "variables" of primitive data types similar to the basic type declarations
and also methods, which are also called as functions. In Java, these variables
and methods are termed as instances of classes.
Defining of Class
Syntax:

class <class name>


{

[variable declaration;]

[method declaration;]

Objects
An Object is a representation (instance )of a class, which
inherits all the properties from his class.
Declaration of Objects: ClassName objectName;
Example:
Circle myCircle;

Classes and Objects

A Circle object
Data Field
radius = 5

Method
findArea

Creating Objects
Syntax:ClassName objectName = new ClassName();
Example:
Circle myCircle = new Circle(); // Dynamic Memory Allocation using
new operator

Constructors
We know that all objects that are created must be given initial values.
It would be simpler and more concise to initialize an object when it is first

created.
Java supports a special type of method, called a constructor that initializes it
when it is created.
In the Java(TM) programming language, constructors are instance methods with
the same name as their class.
Constructors are invoked using the new keyword. A constructor method is a
special type of method that determines how an object is initialized when created.
They have as same name as the class and do not have any return type.
When a keyword new is used to create an instance of a class. Java allocates
memory for the object, initializes the instance variables and calls the constructor
methods.
Every class has a default constructor that does not take any argument and the
body of it does of it not have any statements.

Constructors Example
class Circle
{
int radius ;
Circle(int a)
//Constructor
{
radius=a;
}
void findArea()
{
System.out.println("Area of c1 = " + (3.14f*radius*radius));
}
public static void main(String args[])
{
Circle c1;
//object declaration
c1=new Circle(10);
//object creation
c1. findArea() ;
c1=new Circle(50);
c1. findArea() ;
}
}

Visibility Modifiers and


Accessor Methods

Access controls is the process of controlling visibility of a variable or method.

public Access:
Any variable or method is visible to the entire class in which it is defined.
What if we to make it visible to all the classes outside this class? This is possible
by simply declaring the variable as public. A variable or method declares as
public has the widest possible visibility and accessible everywhere, and any
class can use it.
private Access:
It is narrowly visible and the highest level of protection that can possibly be
obtained. private methods and variables cannot be seen by any class other than
the one which they are defined. They are extremely restrictive but are most
commonly used. They are accessible only within their own class. They cannot
be inherited by subclasses and therefore not accessible in subclasses.
protected Access:
This protected specifier is the relationship between a class and its present
and future subclasses. The subclasses are closer to the parent class than any
other class. This level gives more protection and narrow visibility.
package Access:
package is indicated by the lack of any access modifier in a declaration. It
has an increased protection and narrowed visibility and is the default protection
when none has been specified.

Scope of Variables

The scope of instance and class variables is the entire class.


They can be declared anywhere inside a class.
The scope of a local variable starts from its declaration and continues to the
end of the block that contains the variable.
A local variable must be declared before it can be used.

this keyword

The keyword this is useful when you need to refer to instance of the class from
its method.
The keyword helps us to avoid name conflicts.
As we can see in the program that we have declare the name of instance
variable and local variables same.
Now to avoid the confliction between them we use this keyword.

Here, this section provides you an example with the complete code of the
program for the illustration of how to what is this keyword and how to use it.

Constructor Overloading
& this Keyword
class Student {
int rollno;
String name;
Student(int rollno) {
this.rollno=rollno;
}
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public static void main(String args[])
{
Student scott=new Student(101,);
Student peter=new Student(102,Peter);
}
}

Method Overloading
class Student {
int rollno;
String name;
void setDetails(int rollno) {
this.rollno=rollno;
}
void setDetails(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public static void main(String args[]) {
Student scott=new Student();
scott.setDetails(101);
Student peter=new Student();
peter.setDetails(102,peter);
}
}

Summary

In this Session

Over view of Java


Java Architecture

Structure of Java Program


Data types in Java
Overview of Object oriented Concepts in Java

Das könnte Ihnen auch gefallen