Introduction To Java Programming
Introduction To Java Programming
Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language. This site gives you an Introduction to Java Programming accompanied with many java examples. Its a complete course in java programming for beginners to advanced java.
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
Java Virtual Machine What is the Java Virtual Machine? What is its role?
Java was designed with a concept of write once and run everywhere. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.
Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships.
OOP Concepts
Four principles of Object Oriented Programming are Abstraction Encapsulation Inheritance Polymorphism
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.
Encapsulation
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation.
Encapsulation
* Hides the implementation details of a class. * Forces the user to use an interface to access data * Makes the code more maintainable.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Page 2 of 42
Polymorphism is the existence of the classes or methods in different forms or single name denoting different implementations.
Java is Distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.
Java is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.
Java is Secure
Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.
Garbage collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.
Java Applications
Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more. This site outlines the building blocks of java by stating few java examples along with some java tutorials.
Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase. abstract default if private this boolean do implements protected throw
Page 3 of 42
double else
import
public
continue goto
synchronized
Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program.
Line style comments begin with // and terminate at the end of the line. (Shown in the above program)
Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
public static void main(String[] args) { int b; System.out.println("a : "+a); System.out.println("b : "+b); //Compilation error }} Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value. The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types. Java has four main primitive data types built into the language. We can also create our own data types. Integer: byte, short, int, and long. Floating Point: float and double
Character: char Boolean: variable with a value of true or false. The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.Data Type Default Value (for fields) Range byte 0 short 0 int 0 -127 to +128 -32768 to +32767
char \u0000
For Example
String message = hello world
In the above statement, String is the data type for the identifier message. If you dont specify a value when the variable is declared, it will be assigned the default value for its data type.
Identifier Naming Rules Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character. Must begin with a letter, dollar sign, or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope, each user defined item must have a unique identifier Can be of any length.
Classes
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.
Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.
Page 6 of 42
Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which represent an objects state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot . notation with a object reference is used to access Instance Members.
Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in
the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed above./** Comment * Displays "Hello World!" to the standard output.
*/ public class HelloWorld { String output = ""; static HelloWorld helloObj; //Line 1
public static void main (String args[]) { helloObj = new HelloWorld(); //Line 2
Page 7 of 42
System.out.println(helloObj.printMessage()); }
Class Name: HelloWorld Object Reference: helloObj (in Line 1) Object Created: helloObj (In Line 2) Member Function: printMessage Field: output (String) Static Member: helloObj Instance Member : output (String)
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternarymeaning taking one, two, or three arguments, respectively. A unary operator may appear before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.
>
+ <
* >=
/ <=
% ==
++ !=
--
Logical Operators
&&
||
&
^
Page 8 of 42
&
>>
>>>
+=
-=
*=
/=
Conditional Operator
?:
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.
Assignment operators
The java assignment operator statement has the following syntax:
<variable> = <expression> If the value already exists in the variable it is overwritten by the assignment operator (=).public class AssignmentOperatorsDemo {
public AssignmentOperatorsDemo() { // int j, k; j = 10; // j gets the value 10. j = 5; // j gets the value 5. Previous value is overwritten. k = j; // k gets the value 5. System.out.println("j is : " + j); System.out.println("k is : " + k); // Assigning References Assigning Primitive Values
System.out.println("i2 is : " + i2); i1 = i2; System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2); // Multiple Assignments
k = j = 10; // (k = (j = 10)) System.out.println("j is : " + j); System.out.println("k is : " + k); } public static void main(String args[]) { new AssignmentOperatorsDemo(); } } Download AssignmentOperatorsDemoSource code
Arithmetic operators
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java.
The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed. String message = 100 + Messages; //100 Messagespublic class ArithmeticOperatorsDemo {
System.out.println("- operator resulted in " + x); x = y * z; System.out.println("* operator resulted in " + x); x = y / z; System.out.println("/ operator resulted in " + x); x = y % z; System.out.println("% operator resulted in " + x); x = y++; System.out.println("Postfix ++ operator resulted in " + x); x = ++z; System.out.println("Prefix ++ operator resulted in " + x); x = -y; System.out.println("Unary operator resulted in " + x); // Some examples of special Cases int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is // Integer.MIN_VALUE. int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is // Integer.MAX_VALUE. System.out.println("tooBig becomes " + tooBig); System.out.println("tooSmall becomes " + tooSmall); System.out.println(4.0 / 0.0); // Prints: Infinity System.out.println(-4.0 / 0.0); // Prints: -Infinity System.out.println(0.0 / 0.0); // Prints: NaN double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value // 1.0. double d2 = 12.0F / 8; // result: 1.5 System.out.println("d1 is " + d1); System.out.println("d2 iss " + d2);
Page 11 of 42
Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators: greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=). All relational operators are binary operators, and their operands are numeric expressions. Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java. public class RelationalOperatorsDemo {
public RelationalOperatorsDemo( ) {
int x = 10, y = 5; System.out.println("x > y : "+(x > y)); System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x <= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y));
}
Page 12 of 42
Logical operators
Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.public class LogicalOperatorsDemo {
public LogicalOperatorsDemo() { boolean x = true; boolean y = false; System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y)); System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("!x : " + (!x)); } public static void main(String args[]) { new LogicalOperatorsDemo(); }
Page 13 of 42
Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below. x y !x x&y
x && y x|y
x || y x^y
Bitwise operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level. These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java.public class BitwiseOperatorsDemo {
int z; System.out.println("x & y : " + (x & y)); System.out.println("x | y : " + (x | y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("~x : " + (~x)); System.out.println("x << y : " + (x << y)); System.out.println("x >> y : " + (x >> y)); System.out.println("x >>> y : " + (x >>> y)); //There is no unsigned left shift operator } public static void main(String args[]) { new BitwiseOperatorsDemo(); } }
The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below. A B ~A A&B A|B A^B
1 1
Page 16 of 42
0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
Output
Page 17 of 42
3,0,3/* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |, ^, & */
public static void main(String[] args) { int a = 1 | 2 ^ 3 & 5; int b = ((1 | 2) ^ 3) & 5; int c = 1 | (2 ^ (3 & 5)); System.out.print(a + "," + b + "," + c); } }
The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators. Syntax:
The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.public class CompoundOperatorsDemo {
Page 18 of 42
public CompoundOperatorsDemo() { int x = 0, y = 5; x += 3; System.out.println("x : " + x); y *= x; System.out.println("y : " + y); /*Similarly other operators can be applied as shortcuts. Other
, bitwiseand shift operators*/ } public static void main(String args[]) { new CompoundOperatorsDemo(); } }
The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
An example program is shown below that demonstrates the Ternary operator in java.public class TernaryOperatorsDemo {
public TernaryOperatorsDemo() {
Page 19 of 42
int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } public static void main(String args[]) { new TernaryOperatorsDemo(); } }
Download TernaryOperatorsDemo Source code/* * The following programs shows that when no explicit parenthesis is used then the conditional operator * evaluation is from right to left */
static String m1(boolean b) { return b ? "T" : "F"; } public static void main(String[] args) { boolean t1 = false ? false : true ? false : true ? false : true; boolean t2 = false ? false : (true ? false : (true ? false : true)); boolean t3 = ((false ? false : true) ? false : true) ? false : true; System.out.println(m1(t1) + m1(t2) + m1(t3));
Page 20 of 42
} }
Output
FFT
Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified in the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.
In java Conversions can occur by the following ways: Using a cast operator (explicit promotion) Using an arithmetic operator is used with arguments of different data types (arithmetic promotion) A value of one type is assigned to a variable of a different type (assignment promotion) Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement. That is, from left to right. You can use parentheses to override the default precedence.postfix unary ++expr expr +expr -expr ! ~ creation/caste new (type)expr [] . () expr++ expr
& ^ |
bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary ?: assignment = op= && ||
Example In an operation such as, result = 4 + 5 * 3 First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that * takes higher precedence than + according to chart shown above. This kind of precedence of one operator over another applies to all the operators. QUIZ 1. How to generate a random number between 1 to x, x being a whole number greater than 1 Ans: double result = x * Math.random();
Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;
We use control statements when we want to change the default sequential order of execution Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
Below is an example that demonstrates conditional execution based on if statement condition.public class IfStatementDemo {
int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
Page 23 of 42
Output
b>a
Download IfStatementDemo.java
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
Below is an example that demonstrates conditional execution based on if else statement condition.public class IfElseStatementDemo {
public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } }
Page 24 of 42
Output
b>a
Download IfElseStatementDemo.java Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> case labeln: <statementn> default: <statement> } // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Page 25 of 42
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.public class SwitchCaseStatementDemo {
public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } }
Page 26 of 42
Output
c is the greatest
Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.
Access Modifiers
Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class.
Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.
Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers.
The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below.package pckage1;
class BaseClass {
int a = 10; //Implicit Default Access Modifier public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } }
public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are private System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a); subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } }
Page 30 of 42
Output
The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).import pckage1.*;
public static void main(String args[]) { SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage(); SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access specifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access specifiers - Private // // if we remove the comments it would result in a compilaton error as the fields and methods being accessed are private
Page 31 of 42
/*
System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/ //Access specifiers - Protected // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are protected. System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/ System.out.println("Value of z is : " + subClassDiffObj.getZZZ()); //Access Modifiers - Default // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are default.
System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/ } }
Page 32 of 42
Output
The third class is ClassInDifferentPackage.java which is present in a different package then the first one.import pckage1.*;
public static void main(String args[]) { SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Private // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are private System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are protected. System.out.println("Value of z is : "+subClassObj.z);
Page 33 of 42
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/ //Access Modifiers - Default // // /* If we remove the comments it would result in a compilaton error as the fields and methods being accessed are default. System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/ } }
A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some business logic. Java fields and member functions names are case sensitive. Current states of a classs corresponding object are stored in the objects instance variables. Methods define the operations that can be performed in java programming.
Page 34 of 42
<field declarations (Static and Non-Static)> <method declarations (Static and Non-Static)> <Inner class declarations> <nested interface declarations> <constructor declarations> <Static initializer blocks> }
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().public class Cube {
int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } }
Page 35 of 42
This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object. ( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).
For example:
We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static, only a single instance of the associated variable is created common to all the objects of that class. Hence when one object changes the value of a class variable, it affects all objects of the class. We can access a class variable by using the name of the class, and not necessarily using a reference to an individual object within the class. Static variables can be accessed even though no objects of that class exist. It is declared using static keyword. Class Methods Static Methods
Class methods, similar to Class variables can be invoked without having an instance of the class. Class methods are often used to provide global functions for Java programs. For example, methods in the java.lang.Math package are class methods. You cannot call non-static methods from inside a static method. Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence.
Page 36 of 42
Consider this simple Java program showing the use of static fields and static methods// Class and Object initialization showing the Object Oriented concepts in Java class Cube {
int length = 10; int breadth = 10; int height = 10; public static int numOfCubes = 0; // static variable public static int getNoOfCubes() { //static method return numOfCubes; } public Cube() { numOfCubes++; // } }
public static void main(String args[]) { System.out.println("Number of Cube objects = " + Cube.numOfCubes); System.out.println("Number of Cube objects = " + Cube.getNoOfCubes()); } }
Download CubeStaticTest.java
Output
Page 37 of 42
Number of Cube objects = 0 Number of Cube objects = 0 Final Variable, Methods and Classes
In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be changed.
Variables defined in an interface are implicitly final. You cant change value of a final variable (is a constant). A final class cant be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method cant be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error. Introduction to Java Objects
The Object Class is the super class for all classes in Java.
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object encapsulates state and behavior.
Page 38 of 42
An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as integer or float. Each time you create an object, a new set of instance variables comes into existence which defines the characteristics of that object. If you want to create an object of the class and have the reference variable associated with this object, you must also allocate memory for the object by using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator returns the location of the object which you assign o a reference type.
Below is an example showing the creation of Cube objects by using the new operator.public class Cube {
int length = 10; int breadth = 10; int height = 10; public int getVolume() { return (length * breadth * height); } public static void main(String[] args) { Cube cubeObj; // Creates a Cube Reference cubeObj = new Cube(); // Creates an Object of Cube System.out.println("Volume of Cube is : " + cubeObj.getVolume()); } }
Page 39 of 42
Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
void sumOfParams() { // First Version System.out.println("No parameters"); } void sumOfParams(int a) { // Second Version System.out.println("One parameter: " + a); } int sumOfParams(int a, int b) { // Third Version System.out.println("Two parameters: " + a + " , " + b); return a + b; } double sumOfParams(double a, double b) { // Fourth Version System.out.println("Two double parameters: " + a + " , " + b); return a + b; } public static void main(String args[]) { MethodOverloadDemo moDemo = new MethodOverloadDemo(); int intResult; double doubleResult; moDemo.sumOfParams(); System.out.println();
Page 40 of 42
moDemo.sumOfParams(2); System.out.println(); intResult = moDemo.sumOfParams(10, 20); System.out.println("Sum is " + intResult); System.out.println(); doubleResult = moDemo.sumOfParams(1.1, 2.2); System.out.println("Sum is " + doubleResult); System.out.println(); } }
Download MethodOverloadDemo.java
Output
No parameters
One parameter: 2
Below is a code snippet to shows the interfaces that a Class Implements:Class cls = java.lang.String.class; Class[] intfs = cls.getInterfaces();
Page 41 of 42
// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable] // The interfaces for a primitive type is an empty array cls = int.class; intfs = cls.getInterfaces(); // []
Below is a code snippet to show whether a Class Object Represents a Class or Interface:Class cls = java.lang.String.class; boolean isClass = !cls.isInterface(); // true cls = java.lang.Cloneable.class; isClass = !cls.isInterface(); // false
Page 42 of 42