Java is a high level programming language in the in the following tradition of C and C++. You will find yourself comfortable and in familiar with java environment, if you have any experience with C and C++ programming language. you can see various updated features in java. The extra features of the Java programming language are listed below.
C and C++ are platform dependent where as Java is platform independent.
Java is the object oriented programming language. And C and ++ are both procedure oriented and object oriented programming language.
Java supports automatic Garbage collection(Garbage Collection is procedure of recovering the runtime unused memory consequently or It is a way to destroy the unused objects.)
Java is the software based programming language where as C and C++ are nearer to hardware based programming language.
Java provides more security than the other programming language.
A development environment, JT provides a large of suit of tools.
The Java language itself is very simple.
Java accompanies a library of classes that give regularly utilized utility capacities that most Java programs can’t manage without.
Types of Java Programs
Internet Applets
Stand-alone Applications
Java Character Sets
Character set is a set of valid characters that a language can recognize. A character represents any letter, digit or any other sign. Java uses the Unicode character set (Unicode is a two-byte character code set that has characters representing almost all characters in almost all human alphabets and writing systems around the world including English, Arabic, Chinese and many more.)
Demonstration of the simple java program
/* program HelloWorld*/
class HelloWorld
{
public static void main(String []args)
{
System.out.println(“Hello World!!”);
}
}
Introduction to Classes and objects
As we already described that java is an object oriented programming language above. The basic unit of object-orientation in Java is the class. It is often called as templates or blueprints of objects. It allows a programmer to define all of the properties and methods that internally define the behavior/state of the object.
An object is a distinct instance of a given class that is structurally identical to all other instances of that class. A class is an object factory because once the class is created n number of object can be created and use them. A class is the program code you write to create objects. The class describes the data and methods that defines objects behavior.
The world we live in is composed of objects. Everything that we see around us is an example of object. We, ourselves, are examples of objects. All the living and Non-living things like:- Chair, car, pets, bikes, dog, computers, cellphones, house you live in etc can be consider as the example of objects.
Elements Inside Java
Tokens
The tokens are the various Java program elements which are identified by the compiler. they are the smallest elements of program that is meaningful to the compiler. Individual words and punctuation marks. Every unit that makes a sentence.
Keywords
The Special words that convey a special meaning to the language compiler. Reserved words for special purpose and must not be used as normal identifier names. There are only 57 keywords in java.
Examples of keywords:
abstract default if private this boolean do implements protected throw break double import public try
Identifiers
The name given to variables, objects, classes, functions, arrays etc.
Some of the Identifier forming rules of Java:
Identifiers can have alphabets, digits and underscore and dollar sign.
They must not be a keyword or boolean literal or null literal
They must not begin with a digit.
They can be of any length.
Java is case sensitive.
Some valid identifiers:
myName
first_name
lastName
my_address
…
Some invalid identifiers:
first-name
int
phone-no.
……
Identifier Naming Conventions
The names of public methods and instance variables should begin with a lower case letter.
E.g. num1, str_a etc.
For names having multiple words, second and subsequent words beginning character is made
capital. E.g. myName, dateOfBirth etc.
Private and local variables should use lower case letters. E.g. height, width etc.
Constants should be named using all capital letters and underscores. E.g. RATE, PI, CHARGE etc.
Class names and interface names begin with an uppercase letter. E.g. MyClass, Person, Car etc.
Data Types
There are 8 primitive and 2 Non-primitive Date Types in Java language and they are as follows:-
Primitive Date Types
int
byte
short
long
boolean
float
double
char
Non-primitive Date Types
String
Object
Description of different Data Types:
Any thing enclosed in single quotes are character(char) data types.
char alphabet= ‘A’;
Numbers without fractions are int, short, byte and long data type.
int num = 150;
byte length= 10;
short breadth= 30;
long height= 50;
Numbers with fractions are float and double data type.
double number= 210.5;
double dis= 0.03;
float res=78.82;
Anything enclosed in double quotes are a string.
String name= “John”
Variables that take in either true or false value are a boolean data type.
boolean result= true
Variables
Variables are the name of memory location. There are three types of variable ( Local, Instance and Static) in java. In other word Named storage locations which holds a data value of a particular data type whose value can be manipulated during program run. They must be declared before initialized.
The following statement declares a variable name of the data type String
String name;
Some more examples:
double salary, area, volume;
int month, day, year;
long distance, breadth;
Initialization of Variables
boolean result = true;
String last_name= “Adhikari”;
int num= 200;
Constants
Constant is the kind of variable whose value never changes. The only way to define constant in java is by using final keyword Often in a program you want to give a name to a constant value.
For example, you might have a fixed tax rate of 0.13 for electric materials and a tax rate of 0.05 for services.
These are constants because their value is not going to change when the program is executed.
The syntax for declaring constant are:
modifier final datatype variableName= value; // global constant
modifier static final datatype variableName= value; //constant within a class
Operators in Java
Java’s rich set of operators comprises of arithmetic, relational, logical, bitwise , assignment and certain other types of operators.
Arithmetic Operators
Those operators which are required to performs all kinds of Arithmetical operations. Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Such as:-
Addition (+)
Subtraction (-)
Division (/)
Multiplication (*)
Modulus (%)
Relational Operators
Those operators which area required to perform comparison between operands. Such as:-
Greater than (>)
Smaller than (<)
Greater equals to (>=)
Smaller equals to (<=)
equals to (==)
not equals to (!= or <>)
The Logical Operator
Those operators required to check the conditions and generates the result in the form of true or false. Such as:-
AND operator (&&)
OR operator (||)
NOT operator (!)
Assignment Operator
This operator is used to assign the value in variable.
For e.g. String name= “naranshiva”;
(Note- ‘=’ is the assignment operator)
Expressions
An expression is composed of one or more operations. The objects of the operation(s) are referred to
as operands. The operations are represented by operators. Therefore, operators, constants, and variables are the constituents of expressions.
The expressions in Java can be of any type:
Arithmetic expressions
Relational /logical expressions
Compound expressions
Java Statements
Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following type of expressions can be made into a statement by terminating the expression with a semicolon(;):
Different Method like ‘Calculate’ and the setter method ‘setc’ is defined in a class called ‘Conversion’ and the main method is defined in another class named ‘Test’.
In this program getter method is used to set the value in the variable c. And the value is passed as an argument form another method from the main method.
Here is the program written inside the class ‘Calculate’.
Methods are either return type or Non-return type. If a void is used in syntax then it is Non-return type and if Data types like(int, String, Double) are used instead of void then it is called a return type method. so, to return value of the variable k the method the keyword ‘return’ is used.
public class Conversion
{
double c;
double k;
public void setc(double c)
{
this.c=c;
}
public double calculate()
{
k=c+273.15;
return k; } }
And the main function written inside the Test class is.
public class Test
{
public static void main(String []args)
{ Conversion c = new Conversion();
c.setc(60.0);
double a= c.calculate();
System.out.println(c.c+” degree celsius to kelvin is “+a); } }
Convert temperature in degree Celsius to Fahrenheit
Different methods are defined to convert temperature into Fahrenheit. you can define the sub-methods and the main method in the same class or the two different two classes, and here we did the same. The calculation method ‘Calculate’ and the setter method ‘setc’ is defined in a class called ‘Conversion’ and the main method is defined in another class named ‘Test’.
Getter methods are used to set the value in variables. The data gets set here when the values are passed as an argument form another method that might be the simple method or the main method.
The syntax for the setter method is,
public void [methodName](Parameter){ Statement(s);}
Here is the program is written inside the class ‘Calculate’.
And the main function written inside the Test class is.
public class Test
{
public static void main(String []args)
{
Conversion c = new Conversion(); //Creating object of the ‘Conversion’ class
c.setc(37.0); //calling setter method ‘setc’ to set the value 37.0 in variable c
Parameterized Methods are defined to calculate the area of a simple triangle and the Right angled triangle and the values are passed as an argument from the main function. Values are taken from the user with the help of Scanner (built-in class of util package in java project ).
import java.util.Scanner; //Calling Scanner Class
public class TriangleArea
{
//Declaring Variables
private int height;
private int base;
private int a;
private int b;
private int c;
private int s;
private boolean T;
public void Area(int height, int base) //Method for calculating area of Right-angled Triangle
{
double area= (height*base)/2; //Processing
System.out.println(“Area of right angled triangle is “+area); //Printing Result
}
public void Area(int a, int b, int c) //Method for calculating area of Scalene Triangle
The data needed to calculate simple interest can be initialized with the default value inside the class and also can be taken from the user. Here ‘Scanner’ class, the built-in class inside the ‘util’ package of ‘java’ project is imported to get value from the keyboard.
import java.util.Scanner; //Calling Scanner class to read input from Keyboard
public class SimpleInterest
{
public static void main(String []args)
{
//Declaring Variables
double Principal;
double Time;
double Rate;
double Interest;
System.out.println(“Enter amount of Principle”); //Instruction for User
Principal= new Scanner(System.in).nextDouble(); //Getting value for Principal from user
System.out.println(“Enter Time period”); //Instruction for User
Time= new Scanner(System.in).nextDouble(); //Getting value of Time from user
System.out.println(“Enter Rate of Interest”); //Instruction for User
Rate= new Scanner(System.in).nextDouble(); //Getting Interest Rate from user
Interest= (Principal*Time*Rate)/100; //Processing
System.out.println(“Simple Interest = “+Interest); //Printing Result
Example of Constructor Overloading in Java program
This is a java program to calculate the area of Triangle.
This program is helpful to understand the constructor overloading. Here many constructors are called with the same name as same as of the class name ‘Rectangle’.
public class Rectangle { //Declaring global variables
int length;
int breadth;
double area;
Declaring global variables is accessible from wherever you want. Here many constructors are called and they need to be stored in the same variable so the global variables are created. The variables ‘length’, ‘breadth’, and ‘area’ stores the length breadth and the area of the rectangle respectively.
public Rectangle() //Non-Parameterised Constructor
{ this.length=4;
this.breadth=2;
}
The constructors with no any parameters are called Non-Parameterised Constructor. Because of no parameters, the variables needed to perform calculation are initialized and stored some values.
Keyword “this” is a reference variable in Java that refers to the current object.
The features of ‘this’ keywords are:-
It helps to pass an argument in the method call.
It can be passed as an argument in the constructor call.
It helps to return the current class instance variables.
It can be used to initialize the variable inside the respected Constructor or Method.
‘this’ keyword can be used to get the handle of the current class.
public Rectangle(int length, int breadth) //Parameterised constructor having multiple arguments
{
this.length=length;
this.breadth=breadth; }
The constructors with parameter(s) are called Parameterised Constructor. Here two parameters ‘int length’ and ‘int breadth’ are passed which accept the values as an argument when the constructor is called from any other method(function).
public Rectangle(int length) //Parameterised constructor having single arguments { this.length=length; }
Here only one parameter is passed which accepts the value as an argument when the constructor is called from any other method(function). The same named constructor ‘Rectangle’ inside the same class ‘Rectangle’ is defined with the different number of parameters and is all about Constructor Overloading.
public static void main(String []args)
{
// 1. Creating obj1 and calling non-paramaterised Constructor
Rectangle obj1= new Rectangle();
obj1.area= obj1.length*obj1.breadth; //Processing
// 2. Creating obj2 and calling parameterised Constructor having multiple arguments Rectangle obj2= new Rectangle(4, 6);
obj2.area= obj2.length*obj2.breadth; //Processing
//3. Creating obj3 and calling parameterised Constructor
Rectangle obj3= new Rectangle(5);
obj3.area= obj3.length*obj3.length; //Processing
//Printing Result
System.out.println(“Area of triangle “+obj1.area); //1
System.out.println(“Area of triangle “+obj2.area); //2
System.out.println(“Area of triangle “+obj3.area); //3 } }
A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method’s name. It is also called as sub-program/function it often returns value.
The method has its own name. When that name is called in a program, the execution of the program goes inside the body of that method. When the method is finished executing, it returns to the area of the program from which it was called, and the program continues on to the next line of code.
Process of calling method is given below: –
Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project. The use of methods will be our first step in the direction of modular programming.
Methods are time savers; in that, they allow for the repetition of sections of code without retyping the code. In addition, methods can be saved and utilized again and again in newly developed programs.
You are using the method when you write the code System.out.print( ) and System.out.println( ).
There are two basic types of methods:
Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).
User-defined: User-defined methods are created by the programmer. These methods take-on names that programmer assign to them and perform tasks that they are created for.
How to invoke (call) a method (method invocation):
When a method is called(invoked), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires. The required data for a method is specified in the method’s parameter list.
Consider this method that we have already been using from Breezy;
String str = str1.toUpperCase(); //Converts all string contained in str1 to Upper class and store in variable str.
The method name is .toUpperCase() which is defined in the class “String”. Since the method is defined in the class String, we must call String class before coding in current class. This particular method returns all the lowercase letter contained in the str1 variable is converted in uppercase and stored in str variable.
You invoke (call) a method by writing down the calling object followed by a dot, then the name of the method, and finally a set of parentheses that may (or may not) have information for the method.