Java Programming Tutorial For Beginners
Java programming basics are easy to understand and the language syntax is similar to other programming languages . And therefore , it is relatively much easier to learn the java programming basics .
Java is one of the most popular , versatile and widely used programming language . Java powers over three billion devices . One of the biggest advantage of java is the platform independence which makes it suitable for wide range of applications.
Java is said to be platform independent because java program once written can run on any platform as long as that device has Java Runtime Environment ( JRE ) .
Java language is simple , powerful , secure , object oriented and versatile high level programming language which makes it perfectly suitable for creating different types of applications .
Java Programming Basics
If you are a student who wants to learn java especially for android development then this tutorial guide you step by step for learning the java programming essential skills for mobile app development using the android studio.
This java tutorial has been specially designed for absolute beginner as well as for experienced programmers . This tutorial is a comprehensive resource to learn all the java fundamental programming concepts , java language syntax and its practical implementation.
Java Programming
Table Of Contents
- Programming Paradigms.
- Object Oriented Programming ( OOP )
- Java Programming Basics.
- Java Program Compilation.
- Java Program Examples.
Java Programming Basics
Table Of Contents
History Of Java
Java was developed by James Gosling and his colleagues while working on a project at Sun Microsystems in year 1991. The Java language was initially developed for developing embedded software for electronic gadgets .
The Java language development project started as a project called “Oak” by James Gosling . However , due to some legal issues this language was later on renamed as Java . Java was officially released in year 1995.
The Java language syntax is quite similar to the syntax of C language and C++ . However , some crucial features of these languages were excluded in Java syntax in order to make the java more secure language .
The primary motive of the development of java was to create language that is platform independent . This means java program should have the capability of “Write Once, Run Anywhere”.
The java’s birth also coincided with the advent of smart mobile handsets . The java’s capabilities were tailor made for mobile and touch screen devices . Java soon became one of the most popular , versatile and widely used language which now powers over 3 Billion devices .
Java Programming Basics
Introduction To Computer Programming
The computer system consist of both software and hardware components . The operating system is a system software that manages all the crucial functions of the computer system.
A computer system is a digital electronic device that needs to be programmed to perform any meaningful task . The computer program directs the computer microprocessor ( CPU ) to perform the desired operations as per the program instructions .
The computer program consist of set of program instructions and each of these instruction performs a specific task . The computer program can be written using any high level programming language .
Some of the most popular and commonly used programming languages include C language , C++ , Java , Python , JavaScript , C # ( C Sharp ) , MS .Net and many other high level languages.
However , the computer system can understand and execute only machine code instructions in binary . The binary code consist of only two numbers that is 0 ( zero ) and 1 ( One ) .
Java Programming Basics
And therefore , all the programs written in any programming language must be first converted to machine code instructions in binary which computer CPU can interpret and execute .This conversion process is known as program compilation.
When the user initiates the program execution , the operating system allocates the necessary resources in terms of processor time and the main memory ( RAM ) . The CPU is the brain of the computer system . The CPU reads these instructions from the memory and executes the program instructions one by one .
What Is A Computer Program ?
Java Programming Basics
What Is Java ?
Java is high level , platform independent , object oriented programming language. Java was developed by James Gosling at Sun Microsystems in year 1991 .
The Sun Microsystems where Java originated defines java as simple , object oriented , network-savvy , interpreted , robust , secure , architecture-neutral , portable, high-performance , multi threaded ,dynamic computer language.
We can think of Java as a general-purpose , object-oriented language that looks a lot like C and C++, but Java is much easier to use and far more versatile . Java lets you create more secure and robust programs that can run on multiple platforms.
Java comes in three editions . Java standard edition is used to create general purpose software . The enterprise edition of java is used to create far more complex and distributed enterprise level applications.
Whereas the micro edition of java is a light weight that is optimized for mobile app and embedded system development .
Java Programming Basics
Java Programming Basics
Why Java Is Preferred For Android Development ?
Android is a Linux based open source software platform and operating system that is optimized for the touch screen and mobile devices. Android applications can be developed by using the Java programming language and the Android SDK.
Java has now become a default choice for android development for all types of mobile application development . Android apps are extensively used on all android devices .
Android is now owned and managed by Google in association with Open Handset Alliance ( OHA ) . The OHA consortium is led by Google.
Android has lion’s market share of over 86% in the mobile operating systems . In addition to Java , android application development can be done in other languages such as JavaScript and Google promoted Kotlin.
Java Programming Basics
However , Java still continues to be the most preferred programming language for android mobile app development . And therefore ,the Java programming professionals are in great demand in various industries and also in the job market.
The Java Platform Micro Edition ( Java ME ) is optimized for mobile applications . The Java ME provides a high performance , flexible and secure environment for creating applications that are suitable for embedded systems and mobile devices.
The mobile applications built with Java ME are portable, secure, and can take the advantage of the native capabilities of the mobile device.
The Android Studio which is most popular and extensively used Integrated Development Environment ( IDE ) has seamless integration with Java . And for this reason expertise in java programming basics is prerequisite for android development.
Java Programming Basics
Programming Paradigms
The programming paradigms are simply different approaches to organize and structure the program code . Alternately , paradigms can also be referred as methodology , approach or a particular style to write and organize the program code .
The computer science has evolved both in the hardware and software domain. Similarly , the computer programming approaches and problem solving techniques has also evolved over the period of last few decades .
There are a number of alternative approaches to program methodology and the manner in which the program is written and organized while building a software. Each of these programming style offers different advantages and limitations.
These different programming styles are referred to as programming paradigms. Each of these paradigm represent fundamentally different approaches to building solutions to specific types of problems using programming.
Different programming languages came in to existence which allow the programmers to write the code as per one paradigm. Most programming languages fall under one paradigm, but some languages have elements of multiple paradigms.
Before we start learning the java programming basics , let us first understand various programming methodologies . The programming paradigms can be broadly be grouped into three types .
Programming Paradigms
Non-Structured Programming
The non-structured programming paradigm was used in the first generation of programming languages . Basic , COBOL and Assembly language are examples of non-structured programming.
As per non-structured programming style of programming, the code is organized as collection of program statement which gets sequentially executed from first statement till the last statement.
In non-structured programming paradigm the code is written in a single continuous file . Each program statement has a statement number or label.
One of the major limitation of non-structured approach was the difficulties due to spaghetti code which makes the program code difficult to debug.
The spaghetti code is a badly entangled code due to liberal use of GOTO statement . In large and complex code it is difficult to track the flow of control due multiple use of GOTO statements.
The non–structured programming also had major limitation in terms of difficulty to reuse the program code. Further , it was not possible to secure the data from unintended changes in this approach.
Java Programming Basics
Structured Programming
The next generation of programming languages like C language and Pascal were based on the concept of structured programming.
In structured programming , the program code is modularized in the form of functions . The function once defined can be called number of times. A large chunk of code can be replaced by a single function .
The structured programming approach also made it easy to debug the program code . For example the logical errors in the program code can be easily fixed by making the necessary corrections in the function code .
A structured language has constructs like IF-THEN-ELSE condition statement , WHILE-NEXT conditional loop , SWITCH-CASE statements, DO-WHILE loop , and FOR-NEXT loop. These statements helps to simplify the program algorithm .
Limitations Of Structured Programming
Although structured programming approach was a major improvement over its predecessor. However , this approach also had some major limitations.
In structured programming approach , it was difficult to secure the data and it was difficult to protect the data was unwarranted operations. In large and complex code , it is difficult to track the operations of various functions operating on the same data which can lead to spaghetti code.
Further , in structured programming approach , it is difficult to perfectly model the real world objects ( Entities ) .
OOP
Object Oriented Programming
OOP Introduction
The object oriented programming ( OOP ) approach was next generation of programming paradigm developed to overcome the limitations of structured programming approach. The OOP methodology addressed two major limitations of the structured programming.
In structured programming , first it was difficult to secure the data and second , it was also difficult to model the real world entities .
The OOP methodology does not provide direct access to the program data . The OOP allows the data to be treated as private and the programmer can restrict the data access .
Further , with object oriented ( OOP ) approach , allows the programmers to easily and realistically model the real world entities .
A good understanding of OOP fundamental concepts is essential for learning the java programming basics.
Java Programming Basics
What Is Object Oriented Programming ?
The object oriented programming is an approach to the software application development where all application components are treated as objects.
An object is a smallest component of a program that has some properties and behavior . The object behavior defines how to perform certain actions and interact with other elements of the program.
The objects are the basic units of object Oriented programming . In OOP methodology , the program code is organized in the form of set of classes . The class defines the object in the program code.
Each and every class represents a real world entity. In other words , the entities are objects that need to be represented in the program code .
OOP Example
Android App Development
The java programming basics is essential skill for android developers . Let us consider one example of android application since java is the post popular and widely used programming language for android development.
Let us consider example of java programming used for an android app development to understand the OOP concept of an Object and class .
An android application consist of set of activities ( Screens ) through which user interacts with the android application. The activity is simply a screen displayed to the app user .
Various controls ( Views in android ) are placed on the each activity for user to give inputs or perform some actions on these controls .
Object Oriented Programming Example
Each activity ( Screen ) and the various controls displayed to the user are objects . For example TextView is an object that displays text on the screen .
These TextView objects are created during the program runtime as defined in the TextView Class . Similarly , command button are objects of button class .
The various object used in the application program has corresponding classes . These classes defines the properties ( data ) and the behavior ( methods ) associated with that object .
You might find it a bit confusing initially but don’t worry , we are going to discuss all these OOP concepts much more in detail later on under java programming basics.
Java Programming Basics
Let us now start getting familiar with java programming basics and the object oriented programming fundamental concepts .
In order to get the best out of this java tutorial it is important for you to maintain a logical learning sequence . This will help you logically correlate various java programming and object oriented programming ( OOP ) fundamental concepts.
The following learning sequence in this java tutorial will guide you understand each topic step by step. So , lets dive in .
Java Programming Basics
Table Of Contents
Java Environment
The java environment refers to the runtime environment provided by the java platform needed for the development and the execution of java programs .
Java is a versatile language which is used for creating different types of software applications . Java is used for building desktop applications , enterprise level applications , web applications , android applications for mobile platforms and applets for web services .
The java developers would typically need all the three components required for the development and also for testing ( JDK = JRE + Tools ) the java applications.
Whereas the end user ( client ) machine would need only components ( JRE = JVM + Class Libraries ) necessary for execution of java program.
The java environment has three major components . These components include :
- Java Development Kit ( JDK ).
- Java Runtime Environment ( JRE ).
- Java Virtual Machine ( JVM ) .
Java Development Kit ( JDK )
The Java Development Kit as the name suggest is primarily required for development of java applications . The JDK consist of two components . These two components are Java Runtime Environment ( JRE ) and some other application development tools.
The java development kit is intended for java developers . The JDK includes all the three components required for the development and also for testing ( JDK = JRE + Tools ) the java applications.
JDK = [ JRE + Development Tools ]
Java Runtime Environment ( JRE )
The Java Runtime Environment as the name suggest is primarily required for providing runtime environment to the java applications . The JRE consist of two components .
These two components are Java Virtual Machine ( JVM ) and some class libraries. The JRE is installed on the end user machines for providing runtime environment to the java software application needed for software deployment.
JRE = [ JVM + Library Classes ]
Java Virtual Machine ( JVM )
The JVM stands for Java Virtual Machine . The JVM is a vital component of the JRE which provides runtime environment to the java application.
The JVM accepts the platform independent bytecode ( dot class file ) generated by the java compiler ( javac.exe ) as input . The JVM converts the bytecode into platform specific native machine code and executes this code line by line .
Java Programming Basics
Java Programming Basics
How Java Program Works ?
Java is a high level programming language . The java program gets compiled in two stages . The java compiler does not directly compile the java program to native machine code .
Instead , the java program first gets compiled into a platform independent bytecode. In the first stage we use the java compiler ( javac.exe ) which compiles the high level java program code into intermediate bytecode ( dot class file ) .
This bytecode ( dot class file ) is a platform independent code that gets further compiled to native machine code. The JVM ( Java Virtual Machine ) then executes this platform specific native machine code line by line .
Java Program Compilation
The java program is said to be platform independent because the java program is compiled and executed in two stages .
In the first stage the java compiler ( javac.exe part of JDK ) converts the java program source code file ( YourProgram.java ) into a bytecode ( Also referred as dot class file YourProgram.class ) .
This java bytecode is a platform independent executable code that can run on any platform ( windows , mac , Linux , Unix ) which has Java Runtime Environment ( JER ) installed on it .
Java Program Compilation
The JVM ( Java Virtual Machine ) is an essential component of the JRE. The JVM is an interpreter and responsible to execute the java bytecode ( .class file ) line by line.
And therefore , java program is platform independent but the JVM part of JRE is platform dependent . And for this reason we need to select the correct version java during the java download depending upon the platform .
Java Programming Basics
Java IDE
How To Write Java Program ?
Writing the java program is easy . In order to develop the java programs you need first install the java development kit ( JDK ) on your computer system . The java installation process has been explained in detail.
In addition to JDK you will also need a special software commonly referred as Integrated Development Environment ( IDE ) . Some of the popular and free Java IDE include :
NetBeans , Eclipse , IntelliJ IDEA Community Edition , Android Studio for android app development using java , Enide Studio 2014 and BlueJ.
How To Write Java Program ?
IMPORTANT
Although many java learners start writing the java programs using any IDE . However , if you are an absolute beginner then writing java programs with IDE may not be the best option .
It is highly recommended to initially start writing your java programs using any simple text editor and save this file as java program source code ( Example.java ). You can also compile these programs from the command prompt.
Writing the java program using any text editor will give far better understanding of how java program works , how java program is compiled and executed at the command prompt.
How To Write Java Program ?
- In this example , we have used Notepad software as a text editor to write the Hello World java program .
- You can simply write your first Java program in Notepad which is commonly used as text editor for windows and save this file as Helloworld.java
- Java is case sensitive And the class name must start with the capital letter .
- Java being object oriented , the program code must be written inside a class.
- The source code Helloworld.java is compiled at command prompt using java compiler javac.exe
- The compilation will generate Bytecode Helloworld.class
- The JVM will start program execution with main method .
- Command Prompt is also known as cmd.exe OR cmd ( after its executable file name ) . The cmd is the command-line interpreter on Windows and for other operating systems.
Java Programming Basics
How To Write Java Program ?
The IDE provides fully automated environment for java program development. The IDE provides a complete set of software and tools to write , debug and deploy professional level Java software applications.
This is similar to learning the car driving either on a fully automatic car or on a manual transmission car. The manually driven car will teach you the judgment of clutch , gear and accelerator . Once you learn the driving then you can switch over to fully automatic car .
So , initially spend some time on the text editor writing your first few initial java programs. And once you understand the whole process of how java program works , then you can always switch over to any suitable IDE.
Java Programming Basics
Class And Object In Java
Java being a object oriented programming language views the various entities that needs to be represented in the program only in the form of objects .
The concept of class and object is a fundamental concept of Java programming basics . In object oriented programming the class contains the description of an object .
And therefore , as a programmer or a software developer , we must have a pretty good clarity about what is an object in the programming world and how to represent the objects in the program that we write .
What Is An Object In Java ?
We are all aware of the objects that exists in the real world . The world around us is full of objects such as house , car , pen , computer , cat , dog and also you as an individual .
We can recognize these objects in real world as per their properties such as shape , weight , height , color and also the behavior associated with these objects .
For example a dog is a real world object which has unique identity in terms of its breed , color , height , weight and other such properties . The dog also exhibits a behavior such as running , walking , sleeping and barking.
Java Programming Basics
What Is An Object In Java ?
However , in the programming world , the entities that we want to represent need to defined in the program while writing the program code .
When the program execution starts, the operating system allocates the necessary resources to the process in terms of processor time and the memory.
An object in object oriented programming ( OOP ) can either be either tangible or intangible entity . For example car is a tangible object whereas a bank account is also a valid object but an intangible object.
An Object Definition In OOP
An object in OOP can be defined as an entity that is represented in the program which has a state , exhibits some well defined behavior and can be uniquely identified.
In OOP, an object is an entity that has properties ( data ) for identifies its state and methods that identifies its behavior or functionality . Every object is unique either by its state or because of its behavior. The events associated with object depicts the change of state.
Java Programming Basics
What Is Class In Java ?
As stated earlier , Java is a object oriented programming language and views the various entities that needs to be represented in the program only in the form of objects .
And therefore , the objects need to defined in the program code . In object oriented programming , a class is a description of an object . In other words , a class is a blue print or a template for creating the object .
In other words , an architect creates a blueprint for the house to be built . This architectural drawing defines the qualitative and quantitative dimensions of the house .
Similarly , the programmer needs to define the object in terms of its properties ( data ) and the behavior in terms of the methods .
For example , the android mobile app developer use Button class to create Button objects on the user interface ( activity ) and then defines the method in java code on button click event .
What Is Class In Java ?
What Is Class In Java ?
The programmer first identifies the various objects that need to be represented in the program . The programmer then define these objects in the form of classes in the program code .
And for this reason , the java program code essentially consist of number of classes . The classes are defined in the java program code as per the java language syntax and the object oriented programming design principles.
In the following example , we have created a class with class name as Vehicle . This class Vehicle has data members and also member functions . The class binds together the data related to an object and the methods ( functions ) which operates on the data .
In this class Vehicle the data members include Model No , Color and Registration No. Whereas the member methods include Start ( ) , Forward ( ) , Backward ( ) and Stop ( ) .
IMPORTANT
The Class Is a design-time entity . Whereas an Object is a run-time entity.
Java Programming Basics
What Is Class In Java ?
Java Programming Basics
Java Program Structure
It is important to understand the java program structure . The java program structure consist of different sections. Each section in the java program code handles a specific part of the program .
The different sections in the java program structure improve the maintainability and the readability of the java program code . The Java program structure include six sections.
- Documentation Section.
- Package Statement
- Import Statements.
- Interface Statement.
- Class Definition.
- Class With Main Method.
Java Documentation Section
The documentation section is optional and contains the comments in the java program code . The comments are part of the program that are ignored and not compiled by the compiler.
The main purpose of the comments in the documentation section is to improve the readability and the maintainability of the java program code.
The comments are added to the program code especially in the large and complex project where number of programmers are writing the program code. The comments inserted in the program code makes it easier to understand the program code.
Java Documentation Example
Single Line Comment // Example Comment Text
Multiple Line Comment /* Example Multi-line Comment Line 1
This Is comment Line 2 */
Documentation Comment /** Example Documentation Comment
Generated Automatically */
Java Programming Basics
Java Package Statement
The java package allows the programmer to create a group of similar types of classes , interfaces and sub-packages . These packages once created can be easily imported into the program code .
The java packages allows the code re-usability and the programmer can simply add the required classes by importing the package that contains these classes . The java packages can be either built-in packages or user-defined package.
The package statement in java program is optional and identifies the package that a Java program is a part of that package. The program belongs to the default package If the java program does not include a package statement.
If program does not include the package statement then the program belongs to the default package, which is simply a package without any name.
Java Package Statement Declaration
package package_name;
Java Import Section
The java programmer can use the classes defined in other packages by directly importing the packages into the program code using import statement. The programmer can either import some classes or all the classes present in the package.
Java import statement is optional. The java programming language provide number of built-in packages which programmer can use to add additional functionality to the program .
Once the required package is imported, the classes in the package become available in the program code and can be referred to directly by using only its name. The import statement is very useful and frequently used in the Java program.
Java Import Statement Declaration
import java.io.* ;
Java Interface Section
Java interfaces are similar to class but contains methods without any implementation details. The interfaces contains only method declarations .Java language does not allow multiple inheritance . However , the programmer can use multiple inheritance using an interface.
Java interface is an optional section. Java interface statement is used when programmers want to implement multiple inheritances within a java program code.
Java Programming Basics
Java Class Definitions
In java program , all the entities that need to be represented in the program in the form of objects are included as class . And therefore , a Java program may contain several classes defined in the program.
The Class declarations are an important element of the java program code and the java program contains number of classes .
Java Class With Main Method
As we have discussed earlier , the java program can contain number of classes . However , the java program file which will be compiled to generate the bytecode ( Dot Class File ) must have one public class that contains the main method .
The java program file must be saved with the same class name that contains the main method . This main method is the starting point of the program execution .
The Java Virtual Machine ( JVM ) which executes the java program initiates the program execution by invoking the main method .
Java Programming Basics
Java Program Hello World
Let us now create and understand our first java program Hello World . You can write this program using any text editor ( such as Notepad ) and then compile this program on the command prompt .
In order to write and successfully execute the Java Program Hello World , you need to follow the following steps .
- Install the JDK on your computer .
- Set the JDK path with environment variable.
- Write the program in text editor .
- Save the program file with class name ( HelloWorld.java ).
- Compile the program : javac HelloWorld.java
- This will create java bytecode ( HelloWorld.class )
- Execute the program : java HelloWorld
- This will print Hello World
Java Programming Basics
How To Write Java Hello World Program ?
Java is object oriented and thus the Java program code is written inside a class . And therefore the first step is to create a class with class name HelloWorld .
A class is declared by using a java keyword class . The first letter of the class name should always be a capital letter ( HalloWorld ). The program code is written inside the class body enclosed within curly braces. For example class HelloWorld { Class Body } .
The file containing the program code should be saved same as class name with java extension . This program file should be saved in the directory that contains the JDK .
You need to download and install the JDK the correct version of java on your computer . Further , you also need to create an environment variable and set the path for JDK. This step is required only once after installing the JDK.
Java Program Hello World
Java Program Compilation And Execution
You can use the java compiler ( javac.exe ) to compile the java program . Now you can start the command prompt and change the directory where the java is installed .
For program compilation , start the command prompt. The Command Prompt is also known as cmd.exe OR cmd ( after its executable file name ) . The cmd is the command-line interpreter on Windows and for other operating systems.
To Compile the Program : javac HelloWorld.java
The HollowWorld.java after the compilation step will create a bytecode HelloWorld.class file in the same directory.
To Execute the Program : java HelloWorld
This command will execute the dot class file HelloWorld.class and Hello World will be displayed on the screen.
Java Programming Basics
Java Installation
How To Install Java ?
JDK Installation
Java Environment
Java installation process is simple . As a java developer , you need all the tools necessary tools for the development and execution of the java program.
For java development , we need to install the Java Development Kit ( JDK ) . The JDK includes the JRE ( Java Runtime Environment ) and essential tools used for java program development.
The JDK download and installation can be carried out in the following steps .
- Download Java JDK.
- Install Java JDK.
- Set the JDK Path With Environment Variable .
Download Java JDK
For java installation on your computer , we need to first download the correct version of java JDK from ORACLE official website . You can download the Java from Oracle official download page .
Depending upon the platform details of your computer ( Microsoft Windows , MacOS , Linux ) , you can select and download the correct version of the JDK.
Java Download Link : Download Java From Oracle Page
The JDK SE 8 supports both 64 Bit And 32 Bit Platforms .
Java JDK Installation
The java installation process is simple and similar to any other software installation process.
Java Programming Basics
How To Setup Java Path ?
After the successful completion of java installation , the next step is to set up java path for JDK location.
The operating system needs to know the location of the JDK tools used for java program compilation and the application launcher . And for this reason we need to set the path for JDK .
The JDK path can be permanently defined either by appending the existing system environment variable or by creating a new system variable.
If you are saving the java source file inside the jdk / bin directory then path is not required to be set because all the tools will be available in the current directory .
However, If your java program source file is saved outside the jdk / bin folder then it is necessary to setup the path of the JDK folder.
The system variables JAVA_HOME and JRE_HOME maintain the locations of the JDK and JRE installed directory respectively.
Let us now create a system variable to setup the path for JDK location . First go to my computer and right click on the C drive to select the properties option . Next select the advanced system settings .
Next select the environment variable . Now under system variable select new and type JAVA_HOME in Variable value . Now paste the path of the bin folder where java.exe and javac.exe are located in JDK folder and click OK.
Java Programming Basics
Java Syntax
Java Program Structure
Java Class Declaration
Java Methods
The java program is essentially a collection of objects which are represented in the program code in the form of a classes . These objects communicate with each other to perform the various tasks as per the program instructions.
Like any other programming language , the java program code must be written as per the set of rules and principles that govern the structure of the java program code and the statements .
The java syntax is verified and enforced by the Java Compiler ( javac.exe ) during the program compilation process . The java compiler will output the bytecode only after all the errors are resolved .
However , If you are writing your java program using any IDE ( Integrated Development Environment ) then the code editor will check and suggest the corrections if any .
Let us now learn the java syntax rules for various program elements.
Java Language Syntax
Table Of Contents
Java Program Structure
Java is a class based language . And therefore, all the program code is enclosed in a class except the package import statements , documentation statements and package declaration.
The java program code can be organized in various packages . The package is a collection of related classes . These pages can be imported into java program code using import keyword .
Java Is Strongly Types Language
Java is said to be a strongly typed language because as the java syntax rules all the variables used in the program code must be declared and the datatype should be specified .
Java Programming Basics
Java Class Declaration
Java program can have any number of classes . These classes are organized in packages to improve the readability of the program code.
The class should be declared as per java syntax rules . The class is declared using the java keyword class followed by the class name . The initial letter of the class name is capitalized by convention.
Example : class YourFirstClass { Class Body }
The java source code file with .java extension can contain only one public class . The java main method should be declared in this public class which is starting point of program execution. The java source code file should be saved with the same name as java public class name .
public class MyFirstJavaProgram
{
public static void main ( String [ ] args )
{
// Main Method Body
}
}
The java class can inherit only one parent class . The sub class can be created using the extend keyword . A class can inherit more than one interfaces using java keyword interface.
Example : class B extends class A { Class B Body }
Example : class C implements interface A , B { Class C Body }
Java Class Name
The class is an important element of the Java program . The java program can have any number of classes . The programmer can organize these classes into different packages .
As per standard naming convention , the first letter of the java class name should in upper case. When more than one word is combined for a class name then the first letter of the each inner word is also kept in uppercase .
The name of the public class that contains the main method must match the java source code file name.
Example : class StudentDetails { Class Body }
Java Programming Basics
Java Methods
Java Method Declaration
The java program contains classes and a class contains member variables and functions ( methods ). A method is a named block of code which performs a specific task as per the program statements.
The variables within a class defines the state of an object whereas the methods defines the behavior of an object . The methods operate on the data ( variables ) to perform various operations.
The method needs to be explicitly called ( invoked ) in the program code along with the arguments. The methods are also alternately referred as functions in other language but both means the same.
The java programmer can make use of either built-in methods or user defined methods created as per the program needs .
The built-in methods are part of the classes that program can readily use by importing the package which contains the class in which these methods have been defined.
Java Method Types
The methods can be classified in java in number of ways . The java methods can either be standard library method ( built-in methods ) or user defined method .
The java languages provides extensive library of standard methods which are predefined in the java language . The programmer can simply import the package which contains the class in which the method is defined to use in the program.
The programmer can also create and define a method as per the program requirements . The programmer can use these methods by organizing the classes containing these methods into various packages .
- Pre-defined ( Builtin ) Methods.
- User-defined Methods.
- Instance Methods.
- Static Methods
The java methods can also be classified on the basis of scope of the method into two types such as instance method and static methods .
Instance Method
The programmer can also create a method by declaring a method within a class body . The method declared inside a class is referred as instance method . Which means each object ( instance ) of the class will have this method.
The instance method can be called ( Invoked ) by creating an object of the class and by using the object reference and the dot operator.
Static Method
A method can also be declared at the class level by using the java static keyword. The static method will be one single method common for all objects . The Static method can access only static member variables within a class.
The static method can be called ( Invoked ) without creating an object of the class and by using the class name and the dot operator. The main method is an example of the static method .
Java Method Example
Java Program To Find The Largest Of Two Numbers
Java Programming Basics
Java Variables
What Is a Java Variable ?
The data is an important element of the java program. The class binds together the data and the methods which operate on the data .
The variables are named memory locations with specific datatype assigned to it which acts as a container for temporarily storing the values in the memory during the program execution.
The variable is temporary memory space created during the program execution that can store some value as per the datatype defined in a program instruction. This memory space can be accessed using a variable name as specified in the program code .
A variable can be declared with only one datatype. Once the variable is declared of a specific datatype then during the program execution different values of same datatype can be stored into the variable.
Each data type has specific range of the minimum and maximum value that can be stored into the variable. Depending upon the variable datatype the required bytes of memory is allocated by the operating system.
Java Variable Datatype And Size
Java Programming Basics
Java Variable Declaration
The variables are used to store the data during the program execution. The variables are referred in the program code by user specified variable names .
And therefore , the program defines the names to these memory locations and the specific datatype is also assigned to these named memory locations. The program data is stored into these named memory locations depending upon the datatype.
The java program variables must be declared in the program code along with its name and datatype. The suitable name is given to the variable as per the variable naming convention.
These variables are created during the program execution and the operating system allocates the required memory as per the datatype of the variable.
The scope and the visibility of the variable depends upon the type of the variable ( Local , Instance or static variable ) . The type of the variable depends upon where it is declared within a class and the type of the value assigned to the variable.
Java Programming Basics
Java Variable Scope
The variables scope defines the visibility of the java variable within the program code . The scope of the variable defines the area within which the variable value can be accessed .
The Java variable is said to be in scope if the variable value can be accessed and operated upon within the segment of the program code .
The java variable scope depends upon the location where the variable is declared and the access modifier that precedes the variable name in the variable declaration statement.
The java programmer can control the scope ( visibility ) of the program variables by using the access modifiers ( Public , Private , Protected And Default ) and the location where the variable is declared .
Java Programming Basics
Java Variable Types
The java programming language makes use of different types of variables . The java variable types can be broadly grouped into two categories based on the type of the value stored into the variable and the scope of the variable.
The first category of the java variable type is based on the type of the data stored in a variable . As per this criterion , the java variable can either be of reference type or it can be of non-reference ( primitive ) type .
The second category of variable type is based on the scope and the life span of the variable . As per this criterion , the java variables can be categorized into three types which includes local variable , instance variable and static variable .
Types Of Java Variables
Java Programming Basics
Reference Variable
The java programming language is said to be extensible because you can create a class and declare a variable of that class type . Then we can use the java new keyword and invoke the constructor to create an object .
Once the class is declared , we can create a variable of that class type and such variables are called reference variable. The reference variable can be assigned the address of an object . And therefore , a reference variable points to an object.
Let us consider one example of a Student class . We can create class Student using java keyword class . After creating the Student class, now we can create a reference variable Student class ( S1 ) which holds the address of an object and this reference variable ( S1 ) points to the actual object.