JAVA BASIC TO ADVANCED
Introduction
Java, the programming language, was introduced by Sun Microsystems. This work was
initiated by James Gosling and the final version of Java was released in the year 1995.
However, initially Java was released as a component of the core Sun Microsystem
platform for Java called J2SE or Java 1.0. The latest release of Java or J2SE is Java
Standard Version 6.
The rising popularity of Java, as a programming platform and language has led to the
development of several tools and configurations, which are made keeping Java in mind.
For instance, the J2ME and J2EE are two such configurations. The latest versions of Java
are called Java SE and Java EE or Java ME instead of J2SE, J2EE and J2ME. The biggest
advantage of using the Java platform is the fact that it allows you to run your code at any
machine. So, you just need to write your code once and expect it to run everywhere.
As far as the features of Java are concerned, they are as follows:
Object Oriented
In Java, everything is an object. Java can be effectively stretched out and extended
to unimaginable dimensions since it is focused around the Object model.
Independent of the platform
Dissimilar to numerous other programming dialects including C and C++, when
Java is aggregated, it is not converted into a form, which is particular to any
machine. Instead, it is converted into a machine-independent byte code. This byte
code is conveyed over the web and deciphered by Virtual Machines or JVM on
whichever stage it is generally run.
Simple
Java is intended to be not difficult to learn. In the event that you comprehend the
essential idea of OOP, Java would not be difficult to ace.
Secure
With Java’s security framework, it empowers to create frameworks, which are free
of viruses and tampering. Public-key encryption is used as the core authentication
strategy.
Independent of Machine Architecture
Java compiler produces an object file format, which is independent of the
architecture of the machine. The assembled code can be executed on numerous
processors, with the single requirement that they must all have Java runtime
framework.
Portability
The fact that Java code is machine and platform independent makes it extremely
compact. Compiler in Java is composed in ANSI C with a clean conveyability
limit, which is a POSIX subset.
Robustness
Java tries to kill circumstances, which can lead to potential system failures, by
stressing chiefly on runtime checking and compile time checking.
Support for Multithreaded Applications
With Java’s multithreaded feature, it is conceivable to compose programs that can
do numerous assignments at the same time. This configuration gimmick permits
designers to build easily running intelligent applications.
Interpreted Code
Java byte code is interpreted on the fly to local machine. The advancement
methodology is more quick and expository since the interfacing is an incremental
and lightweight process.
High Performance
With the utilization of Just-In-Time compilers, Java enhances the performance of
the system.
Distributed
Java is intended for the conveyed environment of the web.
Dynamic
Java is thought to be more dynamic than C or C++ since it is intended to adjust to
an advancing environment. Java projects can convey broad measure of run-time
data that can be utilized to check for accesses and respond to the same on run-time.
History of Java
James Gosling started working on the Java programming language in June 1991 for
utilization in one of his numerous set-top box ventures. The programming language, at
first, was called Oak. This name was kept after an oak tree that remained outside Gosling’s
office. This name was changed to the name Green and later renamed as Java, from a list of
words, randomly picked from the dictionary.
Sun discharged the first open usage as Java 1.0 in 1995. It guaranteed Write Once, Run
Anywhere (WORA), giving no-expense run-times on prominent stages. On 13 November
2006, Sun discharged much of Java as free and open source under the terms of the GNU
General Public License (GPL). On 8 May 2007, Sun completed the procedure, making the
greater part of Java’s center code free and open-source, beside a little parcel of code to
which Sun did not hold the copyright.
Pre-requisites
In order to run and experiment with the examples given in this book, you shall require a
Pentium 200-Mhz machine with at least 64 MB of RAM. You additionally will require the
accompanying programming platforms:
Microsoft Notepad or Any Word Processor
Java JDK 5
Linux 7.1 or Windows XP or higher Operating Systems
Java - Basic Syntax
A basic Java program can be broken down into several constructs and elements. Typically,
it can be characterized as a collection of objects, which communicate with each other by
calling each other’s routines. The basic definitions of objects and classes are given below:
Class
A class can be described as a blueprint that portrays the practices/expresses all the
behaviors and states of its objects.
Object
Objects are characterized by two components namely, methods and attributes or
variables. For instance, if you consider the example of a puppy, then it has the
following attributes or states: name, color and breed. In addition, it also has the
following behaviours, which include woofing, wagging and consuming. Any
object is nothing but an instance of a class.
Instance Variables
Each object has its set of variables. An object’s state is made by the qualities
alloted to these variables during program execution.
Methods
A method is the definition of a method. Moreover, a class can contain numerous
methods. It is in these methods that behaviours like where the rationales are
composed, information is controlled and all the activities are executed.
First Java Program:
In order to start with basic basic Java programming, let us look at the standard Hello
World program.
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println(“Say Hello World To The World!”);
}
}
As you can see, the program uses a single line of code in the main() function, which prints
the statement ‘Hello World!’. However, before that can be done, let us look at the steps
that you must follow in your quest to execute the file.
Open any text editor and paste this code in that file.
Save the file with a .java extension. For example, you can save the file as
Sample.java.
The next step is to to open the command prompt of the system and relocate its
reference to the directory in which the file is saved. For instance, if you have saved
the file in C:\, then you must take the prompt to the same directory.
In order to compile the code, you must type the following:
javac Sample.java
If there are no errors, you will automatically be taken to the next line. You can now
execute the code using the following command:
java Sample.java
You should be able to see the following output on the screen.
Say Hello World To The World!
Basic Syntax
About Java programs, it is paramount to remember the accompanying points.
Class Names –
For all class names, the first letter ought to be in Upper Case.
On the off chance that few words are utilized to structure a name of the class,
every internal word’s first letter ought to be in Upper Case. For example, a
standard class name is as follows:
class Sampleclass
Case Sensitivity - Java is case sensitive, which implies that the identifier Hi and hi
would have distinctive importance in Java.
Method Names - All system names ought to begin with a Lower Case letter. In the
event that few words are utilized to structure the name of the method, then every
internal word’s first letter ought to be in Upper Case. An example of this
convention is follows:
public void mysamplemethod ()
Filename –
The name of the system record ought to precisely match the class name. At the
point when you are saving the file, you ought to save it utilizing the class name.
Remember Java is case touchy and affix “.java” to the end of the name. If the
document name and the class name don’t match your system won’t assemble.
Consider the example of a class name Sample. In this case, you must name the file
as sample.java.
public static void main(string args[])
Java system handling begins from the main() function, which is a required piece of
each Java program.
Java Identifiers
All Java components require names. Names utilized for classes, variables and strategies
are called identifiers. In Java, there are a few focuses to recall about identifiers. They are
as per the following standard:
All identifiers ought to start with a letter (beginning to end or a to z), underscore
(_) or special character ($).
After the first character, identifiers can have any mix of characters.
You cannot use a keyword as an identifier.
Most significantly, identifiers are case sensitive. So, Sample is not same as sample.
Examples of identifiers include $salary, age, __1_value and _value.
Examples of illicit identifiers include –compensation and 123abc.
Java Modifiers
Like is the case with any programming language, it is conceivable to alter classes and
systems by utilizing modifiers. There are two classifications of modifiers:
Access Modifiers: public, default, protected and private
Non-access Modifiers: strictfp, final and abstract
We will be researching more insights about modifiers in the following chapters.
Java Variables
Several types of variables are supported by Java. These types of variables include:
Instance Variables (Non-static variables)
Class Variables (Static Variables)
Local Variables
Java Arrays
Arrays are contiguous memory locations that store different variables of the same sort. On
the other hand, an array itself is an article on the memory. We will research how to
proclaim, develop and instate these in the chapters to follow.
Java Enums
Enums were introduced as part of the Java package in java 5.0. Enums limit a variable to
have one of just a couple of predefined qualities. The qualities in this identified list are
called enums. With the utilization of enums it is conceivable to diminish the quantity of
bugs in your code. Case in point, in the event that we consider an application for a cafe, it
would be conceivable to limit the mug size to extra large, large, medium and small. This
would verify that it would not permit anybody to request any size other than the sizes
mentioned in the menu or application listing.
Please note that enums can be pronounced as their own or inside a class. However,
routines, variables, constructors can be created inside the body of enums as well.
Java Keywords:
Keywords or reserved words in Java are shown in the table below. As a rule, these words
cannot be used as names for variables or constants.
assert
abstract
break
boolean
case
byte
char
catch
const
class
default
continue
double
do
enum
else
final
extends
float
finally
goto
for
implements
if
instanceof
import
int
long
interface
new
native
private
package
protected
return
public
static
short
super
strictfp
synchronized
switch
throw
this
transient
throws
while
try
volatile
void
Comments in Java
Just as in the case of C++ and C, Java supports two types of comments namely, single line
comments and multi-line comments. The syntax for these types of comments are as
follows:
Single line comment:
//
Multiple line comment:
/**/
All characters that exist in the comments region are simply ignored by the Java compiler.
Using Blank Lines:
Any line that is only composed of whitespace characters or comments is considered a
blank line. These lines are just ignored by the compiler and are not included in the
executable.
Inheritance:
Java supports inheritance. In other words, it is possible to derive one class from another
class in this programming language. For instance, if you need to create a new class, which
is an extension of an existing class, then you can simply derive this new class from an
existing class. This allows the new class to access the elements already implemented in the
existing class. In this case, the new class is called the derived class and the existing class is
referred to as the super class.
Interfaces:
As mentioned previously, Java is all about interaction between objects. The manner in
which different objects communicate with each other is defined in what is called an
‘interface.’ Moreover, interfaces are also an important aspect of the inheritance feature of
java. As part of an interface, the methods that can be used by a derived or sub-class are
declared. However, all the methods declared as usable for the subclass must be
implemented in the subclass.
Objects and Classes
Java is an Object-Oriented programming language. As an issue that has the Object
Oriented peculiarity, Java underpins the accompanying essential ideas:
Inheritance
Polymorphism
Abstraction
Encapsulation
Objects
Message Parsing
Classes
Method
Instance
In this part, we will investigate the concepts of Classes and Objects.
Class - A class can be described as an blueprint that declares and defines the
attributes and methods that its objects will implement and use.
Object - Objects are simple real world entities that possess a state and its
characteritic behaviour.
For example, if you consider a real world entity, a labrador dog, then this dog is an object.
However, it belong to the class of dogs. Therefore, the associated class is Dog.
Objects in Java
Let us now look profoundly into what are objects. In the event that we consider this
present reality, we can discover numerous entities around us, Cars, Humans, Dogs and
several other. N fact, any real world entity can be modelled as an object. The one common
thing between all these entities is the fact that they contain states and behaviours. On the
off chance that we consider a dog, then its state is - breed, name and color. However, its
behaviour includes eating habits and other characteristics like running and barking.
Classes in Java
A class is a blue print from which individual objects are made. A specimen of a class is
given underneath:
open class Dogs {
String breed;
String shade;
int age;
void eating (){ }
void barking (){ }
}
A class can contain any of the accompanying variable sorts.
Local variables
Variables that are declared and used inside routines, constructors or pieces of code
are called local variables. The variable will be proclaimed and instated inside the
method or scope and the variable will be destroyed when the execution of a
method terminates.
Instance variables
Instance variables are variables inside a class yet outside any system. These
variables are instantiated when the class is stacked. These variables can be gotten
to from inside any technique, constructor or squares of that specific class.
Class variables
Class variables will be variables, which are declared within a class, outside any
system, with the static word before them.
A class can have any number of routines to get to the estimation of different sorts of
methods. In the above illustration, eating() and barking() are the used methods.
Underneath specified are a percentage of the vital subjects that need to be examined when
researching classes of the Java Language.
Constructors
At the point when talking about classes, a standout amongst the most vital sub theme
would be constructors. Each class has a constructor. In the event that we don’t
unequivocally compose a constructor for a class, the Java compiler manufactures a default
constructor for that class. Each time an object is made, no less than one constructor will be
summoned.
The fundamental principle of constructors is that they ought to have the same name as the
class. A class can have more than one constructor and depending on the parameters given
and return type expected, the matching constructor is called. A sample implementation for
this type of a method is given below:
public class Puppies{
public Puppies(){
}
public Puppies(string puppyname){
}
The above class has two constructors. One of the constructors requires no parameters.
However, the other constructor requires a string equivalent to the name of the puppy. Java
additionally upholds Singleton Classes where you would have the capacity to make one
and only object of a class.
Making Objects
As specified previously, a class gives the outlines to object creation. So, fundamentally an
object is made from a class. In Java, the new essential word is utilized to make new
objects.
There are three steps involved in the creation of any object. These steps are illustrated
below:
Declaration: A variable assertion with a variable name and object type.
Instantiation: The “new” word is utilized to make the object of an already declared
class.
Initialization: The “new” word is trailed by a call to a constructor. This call
instantiates the class and creates an object of the same, as a result.
Sample implementation is given below for better understanding of the concept.
public class Puppies{
public Puppies(string name){
System.out.println(“Passed Name of the puppy is:” + name );
}
public static void main(string []args){
Puppies samplepuppy = new Puppies( “jimmy” );
}
On the off chance that we compile and run the above project, then it would deliver the
accompanying result:
Passed Name of the puppy is: jimmy
Getting to Instance Variables and Methods:
Variables and methods are gotten to by means of made objects of classes. To get to a
variable, the qualified way ought to be the following:
The following statement creates an object.
Newobject = new Constructormethod();
The following statements can be used to access the variable and method associated with
the object.
Newobject.variablesname;
Newobject.methodsname();
A sample implementation of this concept is given below:
public class Dog{
int dogAge;
public dogAge(String dogname){
System.out.println(“Dog Name Passed is :” + dogname );
}
public void initAge( int dogage ){
dogAge = dogage;
}
public int getDogAge( ){
System.out.println(“Dog’s present age is:” + dogAge );
return dogAge;
}
public static void main(String []args){
Dog myDog = new Dog( “jimmy” );
myDog.initAge( 5 );
myDog.getDogAge( );
System.out.println(“Variable dogAge Value is:” + myDog.dogAge );
}
}
Upon compilation and execution of the following code, you shall be able to see the
following result.
Variable dogAge Value is: 5
Declaration Guidelines for Source Files
As the last piece of this area how about we now investigate the source file declaration
standards. These tenets are key when declaring classes, importing declarations and
packages in a source file.
There can be stand out public class for every source record.
A source document can have numerous non public classes.
The public class name ought to be the name of the source document. The name of
the source file must be affixed by the string .java. For instance, the class name is
public class Employeerecord{}, then the source document ought to be saved as
Employeerecord.java.
If the class is declared inside a package, then the package articulation ought to be
the first proclamation in the source record.
If import articulations are available, then they must be composed between the
package proclamation and the class revelation. On the off chance that there are no
package proclamations, then the import articulation ought to be the first line in the
source file.
Import and package articulations will intimate to all the classes show in the source
record. It is impractical to announce diverse import and/or package explanations to
distinctive classes in the source file.
Classes have a few access levels. Moreover, there are diverse sorts of classes, which
include final classes, in addition to several others. Separated from the aforementioned
sorts of classes, Java likewise has some uncommon classes called Inner classes and
Anonymous classes.
Java Packages
Basically, it is a method for classifying the classes and interfaces. At the point when
creating applications in Java, many classes and interfaces will be composed. In such a
scenario, ordering these classes is an unquestionable requirement and makes life much less
demanding. In Java, if a completely qualified name, which incorporates the class and
package name, is given, then the compiler can without much of a stretch find the source
code or classes. Import declarations is a method for giving the correct area for the
compiler to find that specific class.
Case in point, in order to load all the classes accessible in java_installation/java/io, you
must use the following statement:
import java.io.*;
A sample implementation for this concept is given below:
The following code uses two classes Employeerecord and Employeerecordtest. The first
step is to open the text editor you intend to use at your system and copy and paste the code
shown below into the text editor application. Keep in mind that the public class in the code
is Employeerecord. Therefore, the name of the file should be Employeerecord.java. This
class uses the variables, methods and constructor as shown below:
import java.io.*;
public class Employeerecord {
int empage;
String empname;
double empcompensation;
public Employee(string empname){
this.empname = empname;
}
public void employeeage(int employeeage){
empage = employeeage;
}
public void empcompensation(double empcompensation){
empcompensation = empcompensation;
}
public void printemp(){
System.out.println(“empname:”+ empname );
System.out.println(“empage:” + empage );
System.out.println(“empcompensation:” + empcompensation);
}
As specified awhile ago in this exercise, handling begins from the main function.
Accordingly, with this goal, we should create a main function for this Employeerecord
class. Given beneath is the Employeerecordtest class, which makes two instances of the
class Employeerecord and conjures the techniques for each one item to allot values for
every variable. You can save this file as Employeerecordtest.java.
import java.io.*;
public class Employeerecordtest{
public static void main(String args[]){
Employeerecord employee1 = new Employeerecord(“Jack Wright”);
Employeerecord employee2 = new Employeerecord(“Mary John”);
employee1.employeeage(32);
employee1.empcompensation(5000);
employee2.employeeage(25);
employee2.empcompensation(2000);
employee1.printemp();
employee2.printemp();
}
}
Upon compilation and execution, you must get the following output:
empname: Jack Wright
empage: 32
empcompensation: 5000
empname: Mary John
empage: 25
empcompensation: 2000
Basic Data Types
Variables are only saved memory areas to store values. This implies that when you make a
variable, you save some space in memory. In light of the data type of a variable, the
working framework distributes memory and chooses what can be put in the held memory.
Consequently, by appointing diverse data types to variables, you can store whole numbers,
decimals, or characters in these variables.
There are two data types accessible in Java:
Reference/Object Data Types
Primitive Data Types
Primitive Data Types
There are eight primitive information types, which are supported by Java. Primitive data
types are predefined by the dialect and named by a catchphrase. This section discusses
these data types in detail.
byte:
byte information sort is a 8-bit marked two’s supplement whole number.
Maximum worth is 2^7 -1, which is equal to 127. This value is also included in the
range of these values.
Minimum worth is -2^7, which is equal to -128.
Default value stored in a variable of this type is 0.
byte information sort is utilized to spare space in vast exhibits, principally set up of
numbers, since a byte is four times littler than an int.
Example:
byte x = 200, byte y = -20
short:
short information sort is a 16-bit marked two’s supplement number.
Maximum value is 2^15 -1, which is equal to 32,767. This number is also included
in the range.
Minimum value is -2^15, which is equal to -32,768.
short information sort can likewise be utilized to spare memory as byte information
sort. A short is 2 times littler than an int
The default value for this data type is 0.
Example:
short x = 425164, short y = -76686
int:
int information sort is a 32-bit marked two’s supplement number.
Maximum value for this data type is 2^31 -1, which is equal to 2,147,483,647. This
number is also included in the range for this data type.
Minimum value for this data type is -2^31, which is equal to - 2,147,483,648.
int is for the most part utilized as the default information sort for its indispensable
qualities unless there is a worry about memory.
The default value for this data type is 0.
Example:
int x = 826378, int y = -64782
long:
long information sort is a 64-bit marked two’s supplement whole number.
Maximum value for this data type is 2^63 -1, which is equal to
9,223,372,036,854,775,807.
Minimum value for this data type is -2^63, which is equal to
-9,223,372,036,854,775,808.
This sort is utilized when a more extensive memory range than int is required.
The default value for those data type is 0l.
Example:
long x = 174636l, int y = -536452l
float:
float is a data type, which is know for its solitary exactness, 32-bit IEEE 754
gliding point.
float is for the most part used to spare memory in vast exhibits of coasting point
numbers.
The default value for this data type is 0.0f.
float information sort is never utilized for exact values, for example, money.
Example:
float x = 254.3f
double:
double information sort is a float with twofold exactness 64-bit IEEE 754 drifting
point.
This information sort is for the most part utilized as the default information sort for
decimal qualities.
double information sort ought to never be utilized for exact values, for example,
money.
The default value for this data type is 0.0d.
Example:
double x = 321.4
boolean:
boolean information sort speaks to one bit of data.
Any boolean variable can assume one of the two values: true or false.
This information sort is utilized for basic banners that track genuine/false
conditions.
The default value for this data type is false.
Example:
boolean check = true;
char:
char information sort is a solitary 16-bit Unicode character.
Maximum value for a variable of this type is “\uffff” (or 65,535 comprehensive).
Minimum value for a variable of this type is “\u0000” (or 0).
char information sort is utilized to store any character.
example:
char text =‘a’
Reference Data Types
Reference variables are made utilizing characterized constructors of the classes.
They are utilized to get to objects. These variables are proclaimed to be of a
particular data type that can’t be changed. A few examples of such data types are
Employee and Dog.
Class objects, and different kind of variables go under reference data type.
Default estimation of any reference variable is invalid.
A reference variable can be utilized to allude to any object of the announced sort.
Example: myanimal = new Animals(“rabbit”);
Java Literals
A literal in Java is a source code representation of a settled worth. They are spoken to
specifically in the code without any calculation. Literals can be appointed to any primitive
sort variable. Case in point:
byte x = 86;
char x = “a”
int, byte, short and long can be communicated in hexadecimal(base 16), decimal(base 10)
or octal(base 8) number frameworks too. Prefix 0 is utilized to show octal while prefix 0x
demonstrates hexadecimal when utilizing these number frameworks for literals. For
example,
int numd = 134;
int numo = 0243;
int numx = 0x95;
String literals in Java are determined like they are in most different programming
languages by encasing a grouping of characters between a couple of twofold quotes.
Illustrations of string literals are:
“Hi Everyone” “two\nlines” “"these characters are inside quotes"”
String sorts of literals can contain any Unicode characters. For instance:
String news = “\u0001”
You can also use escape sequences with Java. Here is a list of escape sequences that you
can use.
Double quote - "
Carriage return (0x0d) - \r
Newline (0x0a) - \n
Single quote - '
Backspace (0x08) - \b
Formfeed (0x0c) - \f
Tab - \t
Space (0x20) - \s
Octal character (ddd) - \ddd
Backslash - \
Hexadecimal UNICODE character (xxxx) - \uxxxx
Variable Types
A variable gives us named capacity that our code can control. Every variable in Java has a
particular sort, which decides the size and format of the variable’s memory; the scope of
values that can be put away inside that memory; and the set of operations that can be
connected to the variable. You must make an explicit declaration of all variables before
they can be utilized. Variables can be declared in the following manner:
Data type ;
Here data type is one of Java’s datatypes. On the other hand, a variable is the name or the
identifier associated with the variable. To pronounce more than one variable of the pointed
out type, you can utilize a comma-divided rundown. Here are a few examples of
declarations:
The following declaration declares three integer variables.
int x, y, z;
In a similar manner, variables of other data types may also be declared.
Java supports three types of variables. These types are as follows:
Class/static variables
Instance variables
Local variables
Local Variables
Local variables are announced in systems, constructors, or scopes.
Local variables are made when the constructor or method is entered and the
variable will be decimated once it retreats the system, constructor or scope.
Access modifiers can’t be utilized for neighborhood variables.
Local variables are noticeable just inside the announced method, constructor or
scope.
Local variables are executed at stack level.
There is no default value for these variables. So, local variables ought to be
declared and a beginning value ought to be relegated before the first utilization.
Sample Implementation:
Here, age is a neighborhood variable. This is characterized inside pupage() strategy and its
degree is constrained to this system just.
public class myTest{
open void newfunc(){
int myvar = 1;
myvar = myvar + 10;
System.out.println(“The value of myvar is: ” + myvar);
}
public static void main(string args[]){
mytest = new myTest ();
mytest.myfunc();
}
The output of the execution of this code is:
The value of myvar is: 11
Instance Variables
The declaration of an instance variable is made inside the class. However, it is
made outside the system, constructor or any scope.
Instance variables are made when an object is made with the utilization of the
keyword “new” and obliterated when the item is destroyed.
When a space is dispensed for an item in the memory, an opening for each one
variable value is made.
Instance variables can be pronounced in class level before or after utilization.
Instance variables hold values that must be referenced by more than one method,
constructor or piece, or key parts of an object’s express that must be available all
through the class.
Access modifiers can be given for sample variables.
Instance variables have default values. For numbers, the default quality is 0.
However, for Booleans, it is false and for object references, it is invalid. Qualities
can be relegated amid the statement or inside the constructor.
The case variables are unmistakable for all methods, constructors and scope in the
class. Regularly, it is prescribed to make these variables private (access level).
However perceivability for subclasses can be given with the utilization of access
modifiers for these variables.
Instance variables can be gotten to by calling the variable name inside the class.
The following statement can be used for this purpose:
Objectreference.variablename.
Sample Implementation:
import java.io.*;
public class Employeerecord{
public String empname;
private double empcompensation;
public Employee (String name){
empname = name;
}
public void initsalary(double empsalary){
empcompensation = empsalary;
}
public void printemployee(){
System.out.println(“Employee name : ” + empname );
System.out.println(“Employee salary :” + empcompensation);
}
public static void main(string args[]){
Employeerecord employee1 = new Employeerecord(“Mary”);
employee1.initsalary(7500);
employee1.printemployee();
}
The compilation and execution would deliver the accompanying result:
Employee name : Mary
Employee compensation :7500.0
Class/Static Variables
Class variables otherwise called static variables are declared with the static
keyword in a class, yet outside a constructor, method or scope.
There would just be one duplicate of each class variable for every class, paying
little mind to what number of objects are made from it.
Static variables are seldom utilized other than being pronounced as constants.
Constants are variables that are announced as private/public, static and final.
Consistent variables never show signs of change from their introductory quality.
Static variables are put away in static memory. It is uncommon to utilize static
variables other than announced final and utilized as either private or public
constants.
Static variables are made when the system begins and annihilated when the
execution stops.
Visibility is like instance variables. In any case, most static variables are
announced public since they must be accessible for clients of the class.
Default values for these variables are also same as instance variables. For numbers,
the default value id typically 0. However, the same value for Booleans is false and
for object reference is invalid. Values can be doled out amid the assertion or inside
the constructor. Furthermore, values can be appointed in unique static initializer
brackets.
Static variables can be gotten to by calling with the class name .
Classname.variablename.
When announcing class variables as public static final, variables names (constants)
must all be in upper case. Moreover, the static variables are not public and the
naming convention is the same as local and instance variables.
Sample Implementation:
import java.io.*;
public class Employeerecord{
private static double empcompensation;
public static final String empdept = “HR “;
public static void main(string args[]){
empcomp = 7500;
System.out.println(empdept+” Compensation: “+empcompensation);
}
The compilation and execution of this code shall create the accompanying result:
HR Compensation: 7500
Modifier Types
Modifiers are catchphrases that you add to definitions to change their implications. The
Java programming language has a wide and mixed bag of modifiers, including the
accompanying:
Non-Access Modifiers
Java Access Modifiers
In order to utilize a modifier, you incorporate its catchphrase in the meaning of a class,
variable or method. The modifier goes before whatever is left of the announcement.
Access Control Modifiers:
Java gives various access modifiers to set access levels for classes, variables, routines and
constructors. The four right to gain access are:
Private: visible to the class.
Default: visible to the bundle. No modifiers are required.
Secured: visible to all subclasses and package.
Public: visible to the world.
Non Access Modifiers:
Java gives various non-access modifiers to attain numerous other usefulness.
Static:
The static modifier for making class variables and methods.
Final
The final modifier for concluding the executions of classes, variables and methods.
Abstract
This modifier is used for for creating abstract methods and classes.
Volatile and Synchronized
These modifiers are typically used for threads.
Comments
Post a Comment