You are on page 1of 47

A First Simple Program

/*
Call this file "Example.java".
*/
class Example
{
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
A First Simple Program
Compiling the Program:
C:\>javac Example.java

Executing the program:


C:\>java Example

Output:
This is a simple Java program.
A First Simple Program

/*
This is a simple Java program.
Call this file "Example.java".
*/
This is a comment

class Example {
This line uses the keyword class to declare that a new class is being
defined.

public static void main(String args[]) {


A First Simple Program

public static void main(String args[]) {

The public keyword allows the member to be accessed by code


outside the class in which it is declared. In this case, main( ) must be
declared as public, since it must be called by code outside of its class
when the program is started.
The keyword static allows main( ) to be called without having to
instantiate a particular instance of the class. This is necessary since
main( ) is called by the Java interpreter before any objects are made.
The keyword void simply tells the compiler that main( ) does not
return a value.
Data Types, Variables, and Arrays


Java is a strongly typed language

The Simple Types

Integer- This group includes byte, short, int, and long, which are
for whole valued signed numbers.

Floating-point number- This group includes float and double,
which represent numbers with fractional precision.

Character- This group includes char, which represents symbols
in a character set, like letters and numbers.

Boolean- This group includes boolean, which is a special type
for representing true/false values.
Data Types, Variables, and Arrays


Integers


Name Width Range

long 64 –9,223,372,036,854,775,808 to

9,223,372,036,854,775,807

int 32 –2,147,483,648 to
2,147,483,647

short 16 –32,768 to 32,767

byte 8 –128 to 127
Data Types, Variables, and Arrays


Floating-Point Types


Name Width Range


double 64 4.9e–324 to 1.8e+308

float 32 1.4e−045 to 3.4e+038
Data Types, Variables, and Arrays

Characters


In C/C++, char is an integer type that is 8 bits wide. Instead, Java
uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters
found in all human languages. It is a unification of dozens of
character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew,
Katakana, Hangul, and many more. For this purpose, Java char is
a 16-bit type. The range of a char is 0 to 65,536. There are no
negative chars. The standard set of characters known as ASCII
still ranges from 0 to 127 as always, and the extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
Data Types, Variables, and Arrays

Even though chars are not integers, in many cases you can
operate on them as if they were integers.

class CharDemo {

public static void main(String args[]) {

char ch1;

ch1 = 'X';

System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1

System.out.println("ch1 is now " + ch1);

}

}

The output generated by this program is shown here:

ch1 contains X

ch1 is now Y
Data Types, Variables, and Arrays
Booleans-Java has a simple type, called boolean, for logical values. It can have only one of
two possible values, true or false.
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b); Output:
// a boolean value can control the if statement b is false
if(b) System.out.println("This is executed."); b is true
b = false; This is executed.
if(b) System.out.println("This is not executed."); 10 > 9 is true
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
Data Conversions
Java’s Automatic Types, Variables, and Arrays
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two conditions are
met:

■ The two types are compatible.


int x; short y;
■ The destination type is larger than the source type. X =y;

When these two conditions are met, a widening conversion takes place.
For example, the int type is always large enough to hold all valid byte
values, so no explicit cast statement is required.
For widening conversions, the numeric types, including integer and floating-
point types, are compatible with each other. However, the numeric types
are not compatible with char or boolean. Also, char and boolean are not
compatible with each other.
Data Types, Variables, and Arrays
Casting Incompatible Types

When we want to convert an bigger size value( say, int) to smaller size(say,
byte), this kind of conversion is sometimes called a narrowing conversion,
since we are explicitly making the value narrower so that it will fit into the
target type.
To create a conversion between two incompatible types, we must use a
cast. A cast is simply an explicit type conversion. It has this general form:

(target-type)
value
int a;
byte b;
b = (byte) a;
Data Types, Variables, and Arrays
Automatic Type Promotion in Expressions

In addition to assignments, certain type conversions may occur in expressions. In an


expression, the precision required of an intermediate value will sometimes exceed the range
of either operand.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte or short
operand to int when evaluating an expression.
byte b = 50; byte c;
b = b * 2; // Error! Cannot assign an int to a byte!
But the correct code is:
byte b = 50;
b = (byte)(b * 2);
Data Types, Variables, and Arrays

Java defines several type promotion rules that apply to expressions.


They are as follows:

First, all byte and short values are promoted to int.


Then, if one operand is a long, the whole expression is promoted to long.
If one operand is a float, the entire expression is promoted to float.
If any of the operands is double, the result is double.
Data Types, Variables, and Arrays
class Promote {
public static void main(String args[]){
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Data Types, Variables, and Arrays
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[ ];

For example, the following declares an array named month_days with the
type “array of int”: int month_days[];

The general form of new as it applies to one-dimensional arrays appears


as follows: array-var = new type[size];

e.g. month_days = new int[12]; After this statement executes,


month_days will refer to an array of 12 integers. Further, all elements in the
array will be initialized to zero.
Data Types, Variables, and Arrays
// Demonstrate a one-dimensional array.
class Array {
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;
System.out.println("April has " + month_days[3] + " days.");
}
}
Data Types, Variables, and Arrays
In Java, multidimensional arrays are actually arrays of arrays.
For example, the following declares a two-dimensional 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
implementedas an array of arrays of int. Conceptually, this array will look like the
one shown below.
Three-dimensional array will be
decfined as follows:
int threeD[ ][ ][ ] = new int[3][4][5];
Data Types, Variables, and Arrays
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 separately.

int twoD[][] = new int[4][ ]; //allocates memory for the first dimension

//It allocates the second dimension manually.


twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[5];
Class

A class is the template or blueprint from which objects are made.


An object is an instance of a class.

A simple class:
class Box
{
double width;
double height;
double depth;
}

Box mybox = new Box(); // create a Box object called mybox.


to assign the width variable of mybox the value 100,
mybox.width = 100;
class Box {
Class
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Class Member Function

class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}

//Function calling in main()


mybox.volume();
Constructor Function
/* Here, Box uses a constructor to initialize the dimensions of a box.*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
Constructor Function

class BoxDemo{
public static void main(String args[ ]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized Constructor Function
class Box {
double width; //Objects to be created in main()
double height; Box mybox1 = new Box(10,
double depth; 20,15);
// This is the constructor for Box. Box mybox2 = new Box();
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
The this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object.

//A simple use to resolve namespace conflict

Box(double width, double height, double depth) {


this.width = width;
this.height = height;
this.depth = depth;
}

Box mybox = new Box(2,3,4);


Garbage Collection

In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator. Java takes a different approach; it handles deallocation for you
automatically. The technique that accomplishes this is called garbage collection.

When no references to an object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed.

Garbage collection only occurs sporadically during the execution of your program.
Garbage Collection

The finalize( ) Method:Sometimes an object will need to perform some action when it is
destroyed. For example, if an object is holding some non-Java resource such as a file
handle or window character font, then you might want to make sure these resources are
freed before an object is destroyed. To handle such situations, Java provides a mechanism
called finalization. By using finalization, you can define specific actions that will occur when
an object is just about to be reclaimed by the garbage collector.

protected void finalize( )


{
// finalization code here
}

protected prevents access to finalize( ) by code defined outside its class.


Garbage Collection

A serial garbage collector is a type of garbage collector used in programming languages that
implement automatic memory management, such as Java or Python.

In a program that uses dynamic memory allocation, objects are created and destroyed
dynamically during runtime. When an object is no longer needed, the memory it occupies is
released so that it can be reused.

Garbage collection is the process of automatically identifying and freeing memory that is no
longer needed by the program. A serial garbage collector works by pausing the entire
program, identifying all the memory that is no longer needed, and then freeing it all at
once before resuming the program's execution.
Garbage Collection

One disadvantage of a serial garbage collector is that it can result in long pauses in the
program's execution, particularly in programs that use large amounts of memory. This is
because the program must stop executing while the garbage collector runs.

However, in programs that use relatively small amounts of memory, a serial garbage
collector can be a simple and effective approach to managing memory.
Function Overloading

In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as method overloading.

class Point
{
private int x = 0, y = 0;
private float a = 0.0f, b = 0.0f;
void move(int dx, int dy) { x += dx; y += dy; }
void move(float da, float db) { a += da; b += db; }
}
Function Overloading

class PointDemo
{
public static void main(String args[ ])
{
Point p1 = new Point();
p1.move(3, 2);
p1.move(4.5, 5.5);
}
}
Constructor Overloading
In addition to overloading normal methods, you can also overload constructor methods.
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() { //-1 is used to indicate an uninitialized box
width = -1;
height = -1;
depth = -1;
}
Constructor Overloading
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

class OverloadCons {
public static void main(String args[])
{ // create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
Constructor Overloading

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
Output:
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
// get volume of cube
Volume of mycube is 343.0
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Using Objects as Parameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// return true if ‘o’ is equal to the invoking object
boolean equals(Test o) //passing object o as argument. o = ob3
{
if(o.a == a && o.b == b) return true;
else return false;
}
}
Using Objects as Parameters

class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));


System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}

Output:
ob1 == ob2: true
ob1 == ob3: false
Returning Objects

A method can return any type of data, including class types that you create.
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp; //returning object of class Test
}
}
Returning Objects
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " + ob2.a);
}
}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Recursion
Java supports recursion. Recursion is the process of defining something in terms of
Itself.
// A simple example of recursion. class Recursion
class Factorial { {
// this is a recursive function public static void main(String args[])
int fact(int n) { {
long int result; Factorial f = new Factorial();
if(n==1) return 1; System.out.println("Factorial of
result = fact(n-1)
3 is "* +
n; f.fact(3));
return result; System.out.println("Factorial of
} 4 is " + f.fact(4));
} System.out.println("Factorial of
Output: 5 is " + f.fact(5));
Factorial of 3 is 6 }
Factorial of 4 is 24 }
Factorial of 5 is 120
Static Keyword


There will be times when you will want to define a class member that will be used
independently of any object of that class. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any object.


Instance variables declared as static are, essentially, global variables. When objects of its
class are declared, no copy of a static variable is made. Instead, all instances of the class
share the same static variable.


Methods declared as static have several restrictions:


They can only call other static methods.

They must only access static data.

They cannot refer to this or super in any way. (The keyword super relates to
inheritance).
Static Keyword
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void method(int x){ Output:
System.out.println("x = " + x); Static block initialized.
System.out.println("a = " + a); x = 42
System.out.println("b = " + b); a=3
} b = 12
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
method(42);
}
}
Static Keyword
If calling a static method from outside its class is needed, the following general form of
function calling is used: classname.method( );

class StaticDemo {
static int a = 42;
static int b = 99;
static void check() { System.out.println("a = " + a); }
}

class StaticByName {
public static void main(String args[])
{
StaticDemo.check();
System.out.println("b = " + StaticDemo.b);
}
}
final Keyword

A variable can be declared as final. Doing so prevents its contents from being modified.
Such a field must be initialized when the object is constructed. That is, it must be guaranteed
that the field value has been set after the end of every constructor. Afterwards, the field may
not be modified again.

final int x = 1;
Nested and Inner Classes
 It is possible to define a class within another class; such class is called nested class. The
scope of a nested class is bounded by the scope of its enclosing class.

 A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members of
the nested class.

 There are two types of nested classes: static and non-static.

 A static nested class is one which has the static modifier applied. Because it is static, it
must access the members of its enclosing class through an object. That is, it cannot refer
to members of its enclosing class directly. Because of this restriction, static nested classes
are seldom used.

 The most important type of nested class is the inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-static members of the outer class do.
Thus, an inner class is fully within the scope of its enclosing class.
Nested and Inner Classes
// Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
outer_x++;
}
}
}
Nested and Inner Classes

class InnerClassDemo {
public static void main(String args[ ]) {
Outer outer = new Outer();
outer.test();
}
}

Output:
display: outer_x = 100

You might also like