UNIT-1
Introduction:
Whats is java:
* Java is a widely used programming language for coding web [Link] has been a
popular choice among developers for over two decades,with millions of java application
in use [Link] is a multi platform,object oriented,and network -centric language that
can be used as a platform in itself.
* Write onces and run anywhere(WORA).
Java programming language used for:
* Game development,cloud computing,big data,artificial intelligence,internet of things.
why is java such a popular choice among modern day software developers:
* High quality learning resources,inbuilt functions and libraries,active community
support,high quality development tools,platform independent,security.
The Stage Is Set for Java:
* By the end of the 1980s and the early 1990s, object-oriented programming using C++
took hold.
* Within a few years, the World Wide Web and the Internetwould reach critical mass.
* This event would precipitate another revolution in programming.
History of java:
* Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank,
and Mike Sheridan at Sun Microsystems, Inc. in 1991.
* This language was initially called “Oak,” but was renamed “Java” in 1995.
* Initial motivation is to develop a platform independent language to create software to
be embedded in various consumers electronics devices.
* The problem is that compilers are expensive and time-consuming to create.
* Become the language of internet a portability, platform-independent
language,security.
* The emergence of the World Wide Web, Java was propelled to the fore front of
computer language design, because the Web too demanded portable programs.
* Java is simply the “Internet version of C++.”
* Java was to Internet programming what C was to system programming: a revolutionary
force that changed the world.
The Evolution of Java:
•JDK 1.02 (1995)
•JDK 1.1 (1996)
•Java 2 SDK v 1.2 ([Link] 1.2, 1998)
•Java 2 SDK v 1.3 ([Link] 1.3, 2000)
•Java 2 SDK v 1.4 ([Link] 1.4, 2002)
•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 servletsand Java
ServerPages.
•Java Micro Edition (J2ME).
–J2ME can be used to develop applications for mobile devices.
Types of Java Programs:
•Standaloneapplications (J2SE)
–AWT (Abstract Window Toolkit) and swing are used to create stand alone application.
•Web applications (JSP)
–Applet, Servlet, jsp, jsfwhich are used to create web applications.
•Enterprise applications (J2EE)
–designed for corporate sides such as banking business systems
•Mobile applications (J2ME)
–Mobile application is developed for run the mobile phones and tablets.
Java IDE Tools:
•Forte by Sun MicroSystems
•Borland JBuilder
•Microsoft Visual J++
•WebGainCafé
•IBM Visual Age for Java
•ECLIPSE
JVM :
* A JAVA Virtual Machine is a software implementation of a physical machine.
* Java was developed with the concept of WORA(Write Once Run Anywhere), which
runs on a VM.
* The compiler compiles the Java file into a [Link] file, then that .class file is input into
the JVM, which loads and executes the class file.
* The key that allows Java to solve both the security and the portability, the output of a
Java compiler is not executable code. Rather, it is byte code.
* Byte code 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).
* The original JVM was designed as an interpreter for byte code.
* Translating a Java program into byte code makes it much easier to run a program in a
wide variety of environments because only the JVM needs to be implemented for each
platform.
* The JVM will differ from platform to platform, all understand the same Java byte
code.
* The execution of byte code by the JVM is the easiest way to create truly portable
programs.
* Because byte code has been highly optimized, the use of byte code enables the JVM to
execute programs much faster.
* Java was designed as an interpreted language, there is nothing about Java that prevents
on-the-fly compilation of byte code into native code in order to boost performance.
The Java Buzzwords:
* The genesis of Java is complete without a look at the Java buzzwords. The invention of
Java are portability and security.
The Java programming language can be characterized by the following buzzwords:
* Simple
* Object-Oriented
* Distributed
* Compiled and Interpreted
* Robust
* Secure
* Architecture-Neutral
* Portable
* High Performance
* Multithreaded
* Dynamic
1. Simple:
* Java is designed to be easy for beginners and professional programmers to learn and use
effectively.
* It’s simple and easy to learn if you already know the basic concepts of Object-Oriented
Programming.
* Java has removed many complicated and rarely-used features, such as explicit pointers
and operator overloading.
2. Object-Oriented:
* Everything in Java revolves around objects and classes.
* Java allows you to model real-world entities (like a car or a bank account) as objects in
your program, making it easier to manage and build complex applications.
* Key Object-Oriented Programming (OOP) concepts include:
Object: An instance of a class.
Class: A blueprint for creating objects.
Inheritance: Allows one class to inherit the properties of another.
Polymorphism: The ability of objects to take on multiple forms.
Abstraction: Hides the complex details and shows only the essentials.
Encapsulation: Keeps the data safe by restricting access to it.
3. Distributed:
* Java is designed to create distributed applications on networks.
* Java applications can access remote objects on the Internet as easily as they can do in the
local system.
* Java enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
4. Compiled and Interpreted:
* Java combines both compiled and interpreted approaches, making it a two-stage system.
* Compiled: Java compiles programs into an intermediate representation called Java Byte
code.
* Interpreted: Byte code is then interpreted, generating machine code that can be directly
executed by the machine that provides a JVM.
5. Robust:
* Java provides many features that make programs execute reliably in a variety of
environments.
* Java is a strictly typed language that checks code at compile time and runtime.
* Java handles memory management with garbage collection and captures serious errors
through exception handling.
6. Secure:
* Java does not use pointers, which helps prevent unauthorized memory access.
* The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s
security constraints.
* Java applications run in a restricted environment (sandbox) that limits their access to
system resources and user data, enhancing security.
7. Architecture-Neutral:
* Java language and JVM help achieve the goal of “write once; run anywhere, any time,
forever.”
* Changes and upgrades in operating systems, processors, and system resources do not
force any changes in Java programs.
8. Portable:
* Java provides a way to download programs dynamically to various types of platforms
connected to the Internet.
* Java is portable because of the JVM, which provides a consistent runtime environment
across different platforms.
9. High Performance:
* Java performance is high because of the use of bytecode.
* The bytecode can be easily translated into native machine code.
10. Multithreaded:
* Multithreaded programs handle multiple tasks simultaneously, which is helpful in
creating interactive, networked programs.
* Java run-time system supports multiprocess synchronization for constructing interactive
systems.
11. Dynamic:
* Java can link in new class libraries, methods, and objects dynamically.
* Java programs carry substantial amounts of run-time type information, enabling dynamic
linking in a safe and expedient manner.
Variables:
* The variable is the basic unit of storage in a Java program.
* A variable is defined by the combination of an identifier, a type, and an optional
initializer.
* All variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable:
* In Java, all variables must be declared before they can be used.
syntax:
type identifier [ = value][, identifier [= value] ...] ;
* The typeis one of Java’s atomic types, or the name of a class or interface.
* The identifieris the name of the variable.
* Initialize the variable by specifying an equal sign and a value.
* To declare more than one variable of the specified type, use a comma separated list.
Example:
int a, b, c; // declares three int a, b, and c.
byte z = 22;// initializes z.
double pi = 3.14159; // declares an approximation of pi.
Dynamic Initialization:
* Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
For example:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}
The Scope and Lifetime of Variables
* A block defines a scope.
* A scope determines what objects are visible to other parts of your program.
* It also determines the lifetime of those objects.
* In Java, the two major scopes are,
–defined by a class
– defined by a method.
* The scope defined by a method begins with its opening curly brace.
* A variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
* Thus, when you declare a variable within a scope, you are localizing that variable and
protecting it from unauthorized access and/or modification.
* Scopes can be nested.
* Objects declared within the inner scope will not be visible outside it.
Example:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
intx; // known to all code within main
x = 10;
if(x == 10) {// start new scope
inty = 20; // known only to this block
// x and y both known here.
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}
// Demonstrate lifetime of a variable.
class LifeTime{
public static void main(String args[]) {
intx;
for(x = 0; x < 3; x++) {
inty = -1; // y is initialized each time block is entered
[Link]("y is: " + y); // this always prints -1
y = 100;
[Link]("y is now: " + y);
}
}
}
Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Arrays:
•An array is a group of like-typed variables that are referred to by a common name.
An array is a collection of similar type of elements which have a contiguous memory location.
•Arrays of any type can be created and may have one or more dimensions.
•A specific element in an array is accessed by its index.
•Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays:
* A one-dimensional array is, essentially, a list of like-typed variables.
* To create an array, you first must create an array variable of the desired type.
* The general form of a one-dimensional array declaration is:
type var-name[ ]; (or)
dataType[]arr;(or)
dataType[]arr;
* Here, type declares the base type of the array
int month_days[];
myarray= new int[10];
* you need to use it now to allocate memory for arrays.
* The general form of new as it applies to one-dimensional arrays appears
as follows:
array-var = new type[size];
Program:
// Demonstrate a one-dimensional array.
class MonthArray {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + " days.");
}
}
Output:
Multidimensional Arrays:
* A multidimensional arrays are actually arrays of arrays.
* To declare a multidimensional array variable, specify each additional index using another
set of square brackets.
* For example, the following declares a twodimensional array variable called twoD.
int twoD[][] = new int[4][5];
* This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int.
Program:
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
output:
01234
56789
10 11 12 13 14
15 16 17 18 19
* When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
A conceptual view of a 4 by 5, two-dimensional array
* The array created by this program looks like this:
* The use of uneven (or, irregular) multidimensional arrays may not be appropriate for
many applications, because it runs contrary to what people expect to find when a
multidimensional array is encountered.
Program:
// Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
[Link](threeD[i][j][k] + " ");
[Link]();
}
[Link]();
}
}
}
output:
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax:
* There is a second form used to declare an array.
Syntax:
type[ ] var-name;
* The square brackets follow the type specifier, and not the name of the array variable.
For example:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
* This alternative declaration form offers convenience when declaring several arrays at the
same time.
For example,
int[] nums, nums2, nums3; // create three arrays
* creates three array variables of type int.
It is the same as writing:
int nums[], nums2[], nums3[]; // create three arrays
* The alternative declaration form is also useful when specifying an array as a return type
for a method.
Operators:
* Java provides a rich operator environment. Most of its operators can be divided into the
following four groups:
–arithmetic
–bitwise
–relational
–logical
* Java also defines some additional operators that handle certain special situations.
Arithmetic Operators:
* The operands of the arithmetic operators must be of a numeric type.
* You cannot use them on boolean types, but you can use them on char types, since the
char type is subset of int.
The Basic Arithmetic Operators:
* The basic arithmetic operations:
addition,
subtraction,
multiplication
division
* All behave expect for all numeric types.
Program:
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
[Link]("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
[Link]("e = " + e);
// arithmetic using doubles
[Link]("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
[Link]("da = " + da);
[Link]("db = " + db);
[Link]("dc = " + dc);
[Link]("dd = " + dd);
[Link]("de = " + de);
}
}
output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
The Modulus Operator:
The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types.
Program:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
[Link]("x mod 10 = " + x % 10);
[Link]("y mod 10 = " + y % 10);
}
}
output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators:
* Java provides special operators that can be used to combine an arithmetic operation with
an assignment.
* There are compound assignment operators for all of the arithmetic, binary operators.
statement of the form:
var = var op expression;
can be rewritten as,
var op= expression;
Program:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
}
}
output:
a=6
b=8
c=3
Increment and Decrement:
* The ++ and the – – are Java’s increment and decrement operators.
* The increment operator increases its operand by one.
* The decrement operator decreases its operand by one.
For example:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
Similarly, this statement:
x = x - 1;
Program:
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
output :
a=2
b=3
c=4
d=1
The Bitwise Operators:
* Java defines several bitwise operators that can be applied to the integer types, long, int,
short,char, and byte. These operators act upon the individual bits of their operands.
The Bitwise Logical Operators:
* The bitwise logical operators are &, |, ^, and ~.
& (Bitwise AND) – returns bit-by-bit AND of input values.
| (Bitwise OR) – returns bit-by-bit OR of input values.
^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
~ (Bitwise Complement) – inverts all bits (one’s complement).
PROGRAM:
// Java Program to show the use of
// bitwise operators
import [Link].*;
class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
[Link]("d & e : " + (d & e));
[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}
Output:
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
The Left Shift:
* The left shift operator, <<, shifts all of the bits in a value to the left a specified number
of times.
Its general form:
value << num
* Here, num specifies the number of positions to left-shift the value in value.
The Right Shift:
* The right shift operator, >>, shifts all of the bits in a value to the right a specified
number of times.
Its general form :
value >> num
The Unsigned Right Shift:
* Java’s unsigned, shift-right operator, >>>,which always shifts zeros into the high-order
bit.
Example:
int a = -1;
a = a >>> 24;
Bitwise Operator Compound Assignments:
* All of the binary bitwise operators have a compound form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation.
EX:
a = a >> 4;
a >>= 4;
Relational Operators:
* The relational operators determine the relationship that one operand has to the
[Link], they determine equality and ordering.
* The relational operators are shown here:
* The outcome of these operations is a boolean [Link] stated, the result produced by a
relational operator is a boolean value.
For example,
the following code fragment is perfectly valid:
int a = 4;
int b = 1;
boolean c = a < b;
In this case, the result of a<b (which is false) is stored in c.
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.
In Java, these statements must be written like this:
if(done == 0) ... // This is Java-style.
if(done != 0) ...
Boolean Logical Operators:
* The Boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.
* The logical Boolean operators, &, |, and ^, operate on boolean values in the same way
that they operate on the bits of an integer.
* The logical ! operator inverts the Boolean state:
!true == false and !false == true.
The following table shows the effect of each logical operation:
Program:
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
[Link](" a = " + a);
[Link](" b = " + b);
[Link](" a|b = " + c);
[Link](" a&b = " + d);
[Link](" a^b = " + e);
[Link]("!a&b|a&!b = " + f);
[Link](" !a = " + g);
}
}
Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
Short-Circuit Logical Operators:
* Java provides two interesting Boolean operators, These are secondary versions of the
Boolean AND and OR operators, and are known as short-circuit logical operators.
For,Example:
if(c==1 & e++ < 100) d = 100;
The Assignment Operator:
The assignment operator is the single equal sign, =.
Its general form:
var= expression;
Example:
intx, y, z;
x = y = z = 100; // set x, y, and z to 100
* This fragment sets the variables x, y, and z to 100 using a single statement.
* This works because the = is an operator that yields the value of the right-hand
expression.
* Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned
to x.
* Using a “chain of assignment” is an easy way to set a group of variables to a common
value.
The ? Operator:
* Java includes a special ternary (three-way) operator that can replace certain types of
if-then-else statements. This operator is the ?.
Its general form:
expression1 ? expression2 : expression3
* Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the ? operation is that of the expression evaluated.
* Both expression2 and expression3 are required to return the same type, which can’t be
void.
Program:
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
[Link]("Absolute value of ");
[Link](i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
[Link]("Absolute value of ");
[Link](i + " is " + k);
}
}
Output :
Absolute value of 10 is 10
Absolute value of -10 is 10
Operator Precedence:
* The order of precedence for Java operators, from highest to lowest.
As operators:
* parentheses
* square brackets
* dot operator
* Technically, these are called separators, but they act like operators in an expression.
Using Parentheses:
* Parentheses raise the precedence of the operations that are inside them.
For example:
a >> b + 3
Type Conversion and Casting:
* If the two types are compatible, then Java will perform the conversion automatically.
* Ex: assign an int value to a long variable.
* An automatic conversion defined from double to byte.
* Conversion between incompatible types, use a cast. which performs an explicit
conversion between incompatible types.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x; //Line 5
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.
Java’s Automatic Conversions:
* A one type of data is assigned to another type of variable, an automatic type
[Link] kind of conversion is sometimes called a widening conversion or
implicit conversion.
Example:
int num=10;
double decimal=num;//I.C from int to double
Two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
Casting Incompatible Types:
* This conversion will not be performed automatically, because a byte is smaller than an
int. This kind of conversion is sometimes called a narrowing conversion or explicitly
conversion
A general form:
* (target-type) value
Example:
double decimal=10.5;
int num=(int)decimal;//E.C from double to int
A First Simple Program:
Entering the program:
* The name of the file that holds the source code to a program is arbitrary.
* The source file should be [Link].
* A source file is officially callaed a compliation unit.
* Enter the program and save as [Link]
* The name of that class should match the name of the file that holds the [Link]
should also make sure that the capitalization of the filename matches the class [Link]
reason for this is that Java is case-sensitive.
Compiling the Program:
* To compile the Example program, execute the compiler, javac, specifying the name of
the source file on the command line, as shown here:
C:\>javac [Link]
* The javac compiler creates a file called [Link] that contains the bytecode version
of the program.
* To actually run the program, you must use the Java application launcher, called [Link]
pass the class name Example as a command-line argument, as shown here:
C:\>java Example
* When the program is run, the following output is displayed:
This is a simple Java program.
A closer look at the first sample program:
java supports three styles of commend:
* commend
* multiline commend
* singleline commend
The program begins with the following lines:
commend:
/*
this is a sample java program
call this file "[Link]".
*/
multiline commend:
class Example{
single line comment:
// your program begins with a call to main().
public static void main(String args[]){
* The next line of code is shown here. Notice that it occurs inside main( ).
[Link]("This is a simple Java program.");
* This line outputs the string “This is a simple Java program.” followed by a new line on
the screen. Output is actually accomplished by the built-in println( ) method.
Constructors:
Definition:
* Automatic initialization of an object is performed through the use of a constructor.
* A constructor initializes an object immediately upon creation.
* It has the same name as the class in which it resides and is syntactically similar to a
method.
* Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
* Constructors have no return type, not even void. This is because the implicit return
type of a class constructor is the class type itself.
* The constructor’s job to initialize the internal state of an object.
Constructors are THREE types:
[Link] Constructors:
* A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with no arguments, the compiler
does not create a default constructor.
Example:
Box mybox1 = new Box();
* The default constructor automatically initializes all instance variables to zero.
2. Parameterized Constructors:
* A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with our own values, then use a parameterized constructor.
Example:
Box mybox1 = new Box(10, 20, 15);
3. Copy Constructors:
* Unlike other constructors copy constructor is passed with another object which copies the
data available from the passed object to the newly created object.
program:
// Java Program to demonstrate Constructor
import [Link].*;
// Driver Class
class Geeks {
// Constructor
Geeks()
{
super();
[Link]("Constructor Called");
}
// main function
public static void main(String[] args)
{
Geeks geek = new Geeks();
}
}
Output
Constructor Called
Methods :
* A methods to access the instance variables defined by the class.
* Classes usually consist of two things: instance variables and methods.
* Methods is a large one because Java gives them so much power and flexibility.
* A methods define the interface to most classes. The class implementor to hide the
specific layout of internal data structures behind cleaner method abstractions.
* Defining methods that provide access to data, you can also define methods that are
used internally by the class itself.
Example:
public static int methodName(int a, int b)
{
// body
}
Here,
∙ public static −modifier
∙ int – return type
∙ methodName − name of the method
∙ a, b – formal parameters
∙ int a, int b − list of parameters
Method definition consists of a method header and a method body.
Syntax
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes :
∙ modifier− It defines the access type of the method and it is optional to use.
∙ returnType− Method may return avalue.
∙ nameOfMethod− This is the method name. The method signature consists of the method name
and the parameter list.
∙ Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
∙ method body − The method body defines what the method does with the statements.
* Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:
return value;
* Here, value is the value returned.
Returning a Value:
vol = [Link]();
excutes, the value of [Link]( ) is 3,000 and this value then is stored in vol.
As shown here:
[Link]("Volume is " + [Link]());
* when println( ) is executed, [Link]( ) will be called automatically and
its value will be passed to println( ).
Adding a Method That Takes Parameters:
Example:
[Link](10, 20, 15);
is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d. Inside
setDim( ) the values of w, h, and d are then assigned to width, height, and depth,respectively.
Overloading Methods:
* To define two or more methods within the same class that share the same name, as long
as their parameter declarations are different.
* The methods are said to be overloaded, and the process is referred to as method
overloading. Method overloading is one of the ways that Java supports polymorphism.
STATIC BLOCK:
* Static block is such kind of block in java which get executed at the time of loading the
.class file into the jvm memory.
Syntax:
class a{
static
{
static block
}
}
Static Method:
* A static method in Java programming belongs to the class rather than an instance of the
class. This means it can be called directly using the class name, without needing to
create an object of the class.
* Static methods are often used for utility or helper methods that don’t require access to
instance-specific data.
Syntax Of Static Method In Java:
[access_modifier] static return_type method_name(parameters) {
// method body
}
String and StringBufferClasses: