Java Basics
Java Basics
Module-I
1
Introduction to Java: The Java Language
• Java Programming is a general-purpose object-oriented
programming language, designed for the development of
software for consumer electronic devices such as TVs, VCRs,
toasters, etc.
• Java is a class-based, object-oriented programming language
and is designed to have as few implementation dependencies
as possible.
• Java is a platform neutral language, which means it is not tied
to any particular hardware or operating system. It guarantees
users to ‘write once, run anywhere’.
2
• Java language is supported by almost every operating
system such as Sun Solaris, RedHat, Windows etc.
4
• 1993-The World Wide Web came to the internet and
transformed the text-based Internet into the graphical rich
environment. The Green Project team came up with an idea
of developing Web applets (tiny programs) that could run on
all types of computers connected to the internet.
• 1994-The team developed a web browser called “HotJava” to
locate and run applet programs on the internet. This made it
immensely popular amongst the internet users.
• 1995-Oak was renamed as “Java”, due to some legal snags.
Java is a name, no acronym.
• 1996-Java programming was established as the leader for
internet programming and also as a general-purpose object-
oriented programming language. Sun releases Java
Development Kit 1.0.
5
• 1997-Sun releases Java Development Kit 1.1 (JDK 1.1)
• 1998-Sun releases the Java 2 with version 1.2 of the Software
Development Kit (SD K 1.2)
• 1999-Sun releases Java 2 platform, Standard Edition (J2SE) and
Enterprise Edition (J2EE)
• 2000-Release ofJ2SE with SDK 1.3.
• 2002-The release of J2SE with SDK 1.4.
• 2004-The release of J2SE with JDK 5.0 (instead of JDK 1.5),
known as J2SE 5.0.
• 2006- The release of Java SE 6.
• 2011- The release of Java SE 7.
• 2014- The release of Java SE 8.
• 2017- The release of Java SE 9.etc
6
• 2023 – Java SE 20
Java programming language is named JAVA. Why?
9
C vs Java
• The major difference between C vs Java Programming language is
that Java is an Object Oriented language and has a mechanism to
define classes and objects.
12
Types of Java Applications
13
VERSIONS
Major release versions of Java, along with their release
dates:
• JDK 1.0 (January 21, 1996)
• JDK 1.1 (February 19, 1997)
• J2SE 1.2 (December 8, 1998)
• J2SE 1.3 (May 8, 2000)
• J2SE 1.4 (February 6, 2002)
• J2SE 5.0 (September 30, 2004)
• Java SE 6 (December 11, 2006)
• Java SE 7 (July 28, 2011)
• Java SE 8 (March 18, 2014)
14
Latest version
15
Java Development Kit (JDK)
• The Java Development Kit (JDK) is a software development
environment that offers a collection of tools and libraries
necessary for developing Java applications.
• You need the JDK to convert your source code into a format
that the Java Runtime Environment (JRE) expects.
• The JDK includes the Java Runtime Environment (JRE), an
interpreter (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc), and some other
development tools.
• The Java Runtime Environment itself consists of the Java
Virtual Machine (JVM), supporting files, and core classes.
• Typically, if you are only interested in running Java programs
on your machine or browser, you only need to install JRE.
However, if you would like to develop an application and do16
• JDK is an implementation of any one of the below given Java
Platforms released by Oracle corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform
• 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.
17
Figure shows how the JDK fits into the
Java application development lifecycle.
18
Java Buzzwords
• Java is the most popular object-oriented programming
language. Java has many advanced features, a list of key
features is known as Java Buzz Words.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted
• High performance
• Distributed
19
•
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have
been removed. One of the most useful features is the garbage collector it makes java
more simple.
Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run
on any computer or operating system. For example, an applet developed using java
runs on a wide variety of CPUs, operating systems, and browsers connected to the
Internet.
20
Object-oriented
Java is said to be a pure object-oriented programming language. In java,
everything is an object. It supports all the features of the object-oriented
programming paradigm.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism
(garbage collector), java is a strictly typed language, it has a strong set of
exception handling mechanism, and many more.
21
Multi-threaded
Java supports multi-threading programming, which allows us to write
programs that do multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. The byte code is
interpreted to any machine code so that it runs on the native machine.
High Performance
Java performance is high because of the use of bytecode.
The bytecode was used so that it was easily translated into native
machine code.
Distributed
Java programming language supports TCP/IP protocols which enable the
java to support the distributed environment of the Internet. Java also
supports Remote Method Invocation (RMI), this feature enables a program
to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically
updated on a running system and it has a dynamic memory allocation and
deallocation (objects and garbage collector). 22
Byte Code
• Java bytecode is the instruction set for the Java Virtual
Machine. It acts similar to an assembler which is an alias
representation of a C++ code.
23
Working Principle
• When we write a program in Java, firstly, the compiler compiles
that program and a bytecode is generated for that piece of code.
• When we wish to run this .class file on any other platform, we
can do so.
• After the first compilation, the bytecode generated is now run by
the Java Virtual Machine and not the processor in consideration.
• This essentially means that we only need to have basic java
installation on any platforms that we want to run our code on.
• Resources required to run the bytecode are made available by
theJava Virtual Machine, which calls the processor to allocate
the required resources.
• JVM's are stack-based so they stack implementation to read the
codes.
24
25
Advantage of Java Bytecode
• Platform independence is one of the soul reasons for which
James Gosling started the formation of java and it is this
implementation of bytecode which helps us to achieve this.
• The set of instructions for the JVM may differ from system to
system but all can interpret the bytecode.
28
29
Difference between Byte Code and Machine Code
Byte Code Machine Code
Byte code is considered as the intermediate-level code. Machine Code is considered as the low-level code.
Byte code is a non-runnable code generated after compilation of Machine code is a set of instructions in machine language or in
source code and it relies on an interpreter to get executed. binary format and it is directly executed by CPU.
Byte code is executed by the virtual machine then the Central Machine code is not executed by a virtual machine it is directly
Processing Unit. executed by CPU.
Byte code is less specific towards machine than the machine Machine code is more specific towards machine than the byte
code. code.
It is platform-independent as it is dependent on the virtual It is not platform independent because the object code of one
machine and the system having a virtual machine can be platform can not be run on the same Operating System. Object
executed irrespective of the platform. varies depending upon system architecture and native
instructions associated with the machine. 30
JVM
• JVM, i.e., Java Virtual Machine.
• JVM is the engine that drives the Java code.
• Mostly in other Programming Languages, compiler produce code
for a particular system but Java compiler produce Bytecode for a
Java Virtual Machine.
• When we compile a Java program, then bytecode is generated.
Bytecode is the source code that can be used to run on any
platform.
• Bytecode is an intermediary language between Java source and
the host system.
• It is the medium which compiles Java code to bytecode which gets
interpreted on a different machine and hence it makes it
Platform/Operating system independent.
31
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM
should have in OS because JVM is platform dependent.
32
Platform Independent
• Java is called platform independent because of Java Virtual
Machine. As different computers with the different
operating system have their JVM, when we submit
a .class file to any operating system, JVM interprets the
bytecode into machine level language.
• JVM is the main component of Java architecture, and it is
the part of the JRE (Java Runtime Environment).
• A program of JVM is written in C Programming Language,
and JVM is Operating System dependent.
• JVM is responsible for allocating the necessary memory
needed by the Java program.
• JVM is responsible for deallocating memory space.
33
JRE and Java environment
• The JRE is one of three interrelated components for developing
and running Java programs. The other two components are as
follows:
• The Java Development Kit, or JDK, is a set of tools for developing
Java applications. Developers choose JDKs by Java version and by
package or edition—Java Enterprise Edition (Java EE), Java
Standard Edition (Java SE), or Java Mobile Edition (Java ME). Every
JDK always includes a compatible JRE, because running a Java
program is part of the process of developing a Java program.
• The Java Virtual Machine, or JVM, executes live Java applications.
Every JRE includes a default JRE, but developers are free to choose
another that meets the specific resource needs of their
applications.
34
• As the runtime environment for Java, the JRE contains the
Java class libraries, the Java class loader, and the Java
Virtual Machine. In this system:
• The class loader is responsible for correctly loading classes
and connecting them with the core Java class libraries.
• The JVM is responsible for ensuring Java applications have
the resources they need to run and perform well in your
device or cloud environment.
• The JRE is mainly a container for those other components,
and is responsible for orchestrating their activities.
35
How the JRE works with the JVM
38
Example
class Student {
int id;
String name;
}
39
Object in Java
• In real–world, we see many objects round us like automobiles, dogs,
cats and so on. these kinds of objects have a state and a behavior.
• An object is an instance of a class.
• If you compare the software object with a real-world object in java ,
they have very similar characteristics.
• A class provides the blueprints for objects. So basically an object is
created from a class. In Java the new keyword is used to create new
object in java.
• It’s miles a basic unit of object orientated Programming and
represents the real existence entities.
• An average Java program creates many objects, which as you already
know, have interaction by way of invoking strategies.
40
An object includes :
• state : it’s represented by attributes of an object.
It additionally reflects the properties of an object.
• behavior : it’s represented by means of methods of
an object in java. It also reflects the reaction of
an object with other objects.
• identity : It gives a completely unique name to
an object and allows one object to have
interaction with different items.
41
class Student {
int id;
String name;
public static void main(String args[])
{
Student s1 = new Student();
}}
42
Simple Class Program
class Student {
System.out.println(s1.name);
} 43
Java Data Type
45
Example of Primitive DataType:
public class Primitive_Java {
// DataType Declaration
byte b = 100;
short s = 123;
int i = 123543;
long long_Val = 1234567891;
float float_Val = 12.25f;
double double_Val = 12345.234d;
boolean boolean_True = true;
boolean boolean_false = false;
char char_Val = 'Y';
46
// Print Variable Values
}
47
Non-primitive data types
48
STRING
• It is class in java provided with several methods used to
store group of characters.
• Example: abcd, india123 etc. String is not a primitive data
type because it has methods and only class can have
methods.
• Primitive data types cannot have methods. So, String is a
class which is non-primitive type.
• ‘String’ is used to represent string class.
Example:
String s="World";
49
Array
• Array is non-primitive data type because it
refers to the memory location.
• An array is a collection of like-typed
variables which are referred
to by a common name.
• Syntax
dataType[] arrayRefVar;
50
• type var-name[]; OR type[] var-name;
Eg: int intArray[]; or int[] intArray;
Instantiating an Array in Java
• var-name = new type [size];
Eg:int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to
array OR
int[] intArray = new int[20]; // combining both
statements in one
51
Java Variables
• Variable is a name of memory location where the
value is stored to use within class, Method etc…
• Each variable in Java has a specific Datatype to
store Value.
• Which decides the size and layout of the java
variables memory.
• Values can be put away inside that memory, and
the arrangement of activities that can be
connected to the variable.
52
•There are three different kinds of variable in Java
1.Local variables
2.Instance variables
3.Class / Static variables
class Variable_Java {
void method() {
53
• 1) Local variables
• Local java variables can be declared within
methods, constructors, or blocks.
• Local variables are created when the method,
constructor or block is entered and the variable
will be destroyed once it exits the method,
constructor or block.
• Access modifiers cannot be used for local
variables Because Local Variables defined within
method.
• Local variable can be declared within the
method, constructor or block.
54
2) Instance variables
• Instance java variables are declared in a class, but
outside a method, constructor etc.
• When a space is allocated for an object in the heap, a
memory slot for each instance variable value is
created.
• Instance variables are created when an object is
created and destroyed when the object is destroyed.
• Instance variables hold values that must be
referenced by more than one method, constructor or
block.
• Access modifiers can be given for instance variables.
55
• Class / static variables
• class java variables is also referred to as static
variable and declared with the static key-word
in a category, but it is outside a method,
constructor or a block.
• only one replica of every class variable is
created, regardless of how many objects are
created.
• Static variables are stored in static memory.
• Static variables are created while the program
begins and destroyed while this system stops.
56
Java Operators
• An operator is used to perform an operation
over one or more operands.
• An operator is a character that represents an
action, for example + is an arithmetic operator
that represents addition.
• Java operators use in within class.
57
Types of Operator in Java
• Basic Arithmetic Operators
• Assignment Operators
• Auto-increment and Auto-decrement
Operators
• Logical Java Operators
• Comparison (relational) operators
• Bitwise Operators
58
Java Decision making statements
1) if Statement
2) if…else Statement
3) if…else…if…else Statement
4) Nested if statement
5) switch statement
59
if Statement
int x = 10;
if (x == 10) {
System.out.print("This is if statement");
}
}
}
60
if… else Statement
int x = 30;
if (x == 20) {
System.out.print("This is if statement");
} else {
System.out.print("This is else statement");
}
}
}
61
if… else…if… else Statement
int x = 30;
if (x == 10) {
System.out.print("Value of X is 10");
} else if (x == 20) {
System.out.print("Value of X is 20");
} else if (x == 30) {
System.out.print("Value of X is 30");
} else {
System.out.print("This is else statement");
}
}
}
62
switch statement
case 'A':
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
64
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
}
}
65
Java Loop
• In some situation you need to execute a block of code several
number of times in such a case loops are used.
• A java loop statement permits us to execute
a statement or group of statements multiple times and following
is the general form of a loop statement in most of the
programming languages.
• Looping in programming languages is
a characteristic which helps the execution of a
set of instructions/functions again and again while a
few situation evaluates to true.
• Java provides three methods for executing the loops.
• while all the approaches offer similar simple capability,
they range of their syntax and condition checking time.
66
• while Loop
• do…while Loop
• for Loop
• for each loop
• Java Continue Statement
• Java Break Statement
67
The while Loop:
• A while loop is a control shape that allows you to
repeat a assignment for sure number of times.
• while executing, if the condition is actual, then
the actions inside the loop might be done.
• This could retain as long as the condition is true.
• While loop begins with the checking of situation. If it
evaluated to actual, then the java
loop body statements are executed in any other
case first statement following the loop is achieved.
• For that reason it is also referred to
as access control loop
68
Syntax:
while (condition)
{
//Statements
}
Example:
Example:
public class Do_While_Java {
public static void main(String args[]) {
int x = 10;
do {
System.out.print("value of x : " + x);
x++;
System.out.print("\n");
} while (x < 13);
}
}
71
The for Loop
72
• Syntax:
for(initialization;condition;increment/decrement)
{
//
}
• Example:
jump-statement;
continue;
77
Example
public class Continue_Java {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}
}
}
78
Java Break Statement
79
Example
public class Break_Java {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
80
Arrays
• The array is a collection of elements of the same type that are
nearby memory spaces.
• We can store only a certain set of elements in a java array.
• The array index is based, the first element of the array is stored in
the 0 index.
Types of Array:
• One Dimensional Array
• Two Dimensional Array
Java program contains steps in array:
• Announce the name of the array.
• Create an array.
• Start array values.
81
One dimensional array
Syntax:
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];
• An array declaration has two components: array type and array name.
• The type of an array is written as type [], where type elements are the
type of data; Brackets are special symbols which indicate that this
variable holds an array.
• The size of the array is not part of its type.
• With other types of variables, the announcement does not actually
make a Java array; It only tells the compiler that in this variable there
will be an array of the specified type.
82
//
Java Program to illustrate how to declare, instantiate
, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//
length is the property of array
System.out.println(a[i]);
}} 83
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
84
• Another way of creating and initializing same
one dimensional array is as shown below.
int a[]={10,20,70,40,50};
85
Two Dimensional Array
• dataType []arrayRefVar[];
87
public class Two_Array_Java {
str[0][0] = "user_1";
str[1][0] = "user_2";
str[2][0] = "user_3";
str[0][1] = "pwd_1";
str[1][1] = "pwd_2";
str[2][1] = "pwd_3";
System.out.println(str[i][j]);
} }
88
}
Command Line Arguments
89
class Main
{
public static void main(String[] args)
{ System.out.println("Command-Line arguments are");
// loop through all arguments
for(String str: args)
{
System.out.println(str);
}
}
}
90
1. To compile the code
javac Main.java
2. To run the code
java Main
• Now suppose we want to pass some arguments while running
the program, we can pass the arguments after the class name.
• For example,
java Main apple ball cat
• Here apple, ball, and cat are arguments passed to the
program through the command line.
• Now, we will get the following output.
Command-Line arguments are Apple Ball Cat
• In the above program, the main() method includes an array of
strings named args as its parameter.
• Note: Arguments are always stored as strings and always
separated by white-space. 91
Passing Numeric Command-Line Arguments
92
Example: Numeric Command-Line Arguments
class Main
{
public static void main(String[] args)
{
for(String str: args)
{ // convert into integer type
int argument = Integer.parseInt(str);
System.out.println("Argument in integer form: " + argument);
}
}
}
93
// compile the code
javac Main.java
// run the code
java Main 11 23
Here 11 and 23 are command-line arguments.
Now, we will get the following output.
Arguments in integer form 11 23
94
• In the above example, notice the line
int argument = Integer.parseInt(str);
• Here, the parseInt() method of the Integer class converts the
string argument into an integer.
• Similarly, we can use
the parseDouble() and parseFloat() method to convert the
string into double and float respectively.
• Note: If the arguments cannot be converted into the specified
numeric value then an exception
named NumberFormatException occurs.
95
Java Methods
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also
known as functions.
• Why use methods? To reuse code: define the code once, and use
it many times.
• A method must be declared within a class.
• It is defined with the name of the method, followed by
parentheses ().
• In Java, there are two types of methods:
• User-defined Methods: We can create our own method based on
our requirements.
• Standard Library Methods: These are built-in methods in Java that
are available to use.
• Java provides some pre-defined methods, such 96
• We can also create your own methods to perform certain
actions:
97
• myMethod() is the name of the method
• static means that the method belongs to the Main class and
not an object of the Main class.
• void means that this method does not have a return value.
98
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the
action), when it is called:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
} 99
With Parameters
public class Main
{
static void myMethod(String fname, int age)
{
System.out.println(fname + " is " + age);
}
public static void main(String[] args)
{
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
} 100
Return Values
• The void keyword, used in the examples above, indicates that the
method should not return a value.
• If you want the method to return a value, you can use a primitive
data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method .
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{ System.out.println(myMethod(3));
}
}
101
Method Overloading
• With method overloading, multiple methods can have the
same name with different parameters.
Example
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
102
static int plusMethodInt(int x, int y)
{
return x + y;
}
static double plusMethodDouble(double x, double y)
{ return x + y;
}
public static void main(String[] args)
{
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
103
Example-2
class MethodOverloading
{
private static void display(int a)
{
System.out.println("Arguments: " + a);
}
private static void display(int a, int b)
{
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args)
{
display(1);
display(1, 4);
} 104
Important Points
• Two or more methods can have the same
name inside the same class if they accept
different arguments. This feature is known as
method overloading.
• Method overloading is achieved by either:
– changing the number of arguments.
– or changing the data type of arguments.
• It is not method overloading if we only change
the return type of methods. There must be
differences in the number of parameters.
105
Constructor
• A Java constructor is special method that is called when an
object is instantiated.
• In other words, when you use the new keyword.
• The purpose of a Java constructor is to initializes the newly
created object before it
class Test
{
Test()
{
// constructor body
}
}
• Here, Test() is a constructor. It has the same name as that of
the class and doesn't have a return type. 106
Example
class Main
{
private String name;
// constructor
Main()
{
System.out.println("Constructor Called:");
name = “XXXXX";
}
public static void main(String[] args)
{ // constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}} 107
Types of Constructor
108
1. Java No-Arg Constructors
}} 110
2. Java Parameterized Constructor
111
class Main
{ String languages;
// constructor accepting single value
Main(String lang)
{
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args)
{ // call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}}
112
3. Java Default Constructor
• If we do not create any constructor, the Java compiler
automatically create a no-arg constructor during the execution
of the program. This constructor is called default constructor.
class Main
{ int a;
boolean b;
public static void main(String[] args)
{
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}} 113
The default constructor initializes any uninitialized instance variables with
default values.
114
Important Notes on Java Constructors
• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
The name of the constructor should be the same as the class.
A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0
• Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but can not be overridden.
115
Constructors Overloading in Java
• Similar to Java method overloading, we can also create two or
more constructors with different parameters. This is called
constructors overloading.
116
class Main
{ String language;
// constructor with no parameter
Main()
{ this.language = "Java";
}
// constructor with a single parameter
Main(String language)
{
this.language = language;
}
public void getName()
{ System.out.println("Programming Langauage: " + this.language);
} public static void main(String[] args)
{ // call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}}
117
Implicit this
• In Java, this keyword is used to refer to the current object inside a
method or a constructor. For example,
class Main
{
int instVar;
Main(int instVar)
{
this.instVar = instVar;
System.out.println("this reference = " + this);
}
public static void main(String[] args)
{ Main obj = new Main(8);
System.out.println("object reference = " + obj);
System.out.println("object reference = " + obj.instVar);
}} 118
Output
this reference = Main@23fc625e
object reference = Main@23fc625e
121
Static Methods/Class Methods
Method Description
nextBoolean() Reads a boolean value from the
user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
129
• import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();