Java Basic

By | October 25th 2019 08:53:41 PM | viewed 181 times

What is Java?

Java is a High level programming language that produces software for multiple platforms.When a programmer writes a Java application, the compiled code (known as bytecode) runs on most operating systems (OS), including Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming languages.Developed by James Gosling at Sun Microsystems in 1995.

Java Platforms

  • JSE(Java Standard Edition)--– Core Java API used to deploy portable applications for general use.
  • JEE (Java Enterprise Edition)--– an API and runtime environment for developing and running enterprise software, including network and web services, and other large-scale, multi-tiered, scalable, reliable, and secure network applications
  • JME (Micro Edition)--–designed for embedded systems (mobile devices are one kind of such systems)

J2SE vs J2ME vs J2EE….What’s the difference?

j2SE(Java Platform, Standard Edition)

Also known as Core Java, this is the most basic and standard version of the purest form of Java, a basic foundation for all other editions

It consists of a wide variety of general purpose API’s (like java.lang, java.util) as well as many special purpose APIs

J2SE is mainly used to create applications for Desktop environment.

It consist all the basics of Java the language, variables, primitive data types, Arrays, Streams, Strings Java Database Connectivity(JDBC) and much more. This is the standard, from which all other editions came out, according to the needs of the time.

j2ME(Java Platform, Micro Edition)

This version of Java is mainly concentrated for the applications running on embedded systems, mobiles and small devices.(which was a constraint before it’s development)

Constraints included limited processing power, battery limitation, small display etc.

J2ME uses many libraries and API’s of J2SE, as well as, many of it’s own.

The basic aim of this edition was to work on mobiles, wireless devices, set top boxes etc.

J2EE(Java Platform, Enterprise Edition)

The Enterprise version of Java has a much larger usage of Java, like development of web services, networking, server side scripting and other various web based applications.

J2EE uses many components of J2SE, as well as, has many new features of it’s own like Servlets, JavaBeans, Java Message Services, adding a whole new functionalities to the language.

J2EE uses HTML, CSS, JavaScript etc., so as to create web pages and web services. It’s also one of the most widely accepted web development standard.

There are also many languages like .net and php, which can do that work, but what distinguishes it from other languages is the versatility, compatibility and security features, which are not that much prominent in other languages.

Software

Java Software Development Kit (JSDK) is need for run java

Tools

Any Text Editor (Ex: notepad, notepad++, SciTE, etc.) or Any IDE (Ex: Netbeans, Eclipse,Intellij etc.)

How to write java class?

Ecxample:

 class Hello{
		   }

 
  • Here, "Hello" is the class name which follows the keyword “class”.
  • A Java class may contain variable and function declarations. Generally, a function is called method in java
  • The file that contains the java codes known as Java Source file and each source file name has the extension .java.
  • A Java source file can contain one or more class declaration.
  • If a java source file contains only one class declaration, the file name must be given same as the class name in that file.
  • If a source file contains more than one java class declaration and no class is declared as public, the file name can be given according to any of the class name.
  • If a class is declared public, the file name containing the class must be the same as the class name.
  • The above rule implies that a source file can only contain at the most one public class.
Example:

Hello.java or Bye.java=>

class Hello{
}
class Bye{
}

 

Hello.java =>

Public class Hello{
}
class Bye{
}

 
  • Each class declaration in a source file is compiled into a separate class file, containing Java byte code
  • The name of this file contains the name of the class with .class as its extension.
  • The JDK provides tools for compiling and running programs, (to be explained later).
  • The classes in the Java standard library are already compiled, and the JDK tools know where to find them.

The main method

In order to create an application in Java, the program must have a class that defines a method or function named main, which is the starting point for the execution of any application and as follows:

  public static void main( String varName[]){
			 //some code here
	  }

Without main method, a program can be compiled but can not be run.

Sample Java Program

public class HelloWorld{
		public static void main( String args[]){
			 System.out.println(“Hello World”);
			 System.out.print(100);
             System.out.print(“ “);
			 System.out.println(20.0);
			 System.out.println(“Ends”);
	  }
	} 

	
Output is as follows: 
Hello World
100 20.0
Ends

Java Basic Language Elements

Identifiers

  • A name in a program is called an identifier. Identifiers can be used to denote classes, methods, variables, and labels.
  • In Java, an identifier is composed of a sequence of characters, where each character can be either a letter or a digit. However, the first character in an identifier must be a letter.
  • connecting punctuation (such as underscore _ ) and any currency symbol (such as $, ¢, ¥, or £) are allowed as letters, but should be avoided in identifier names.
  • Identifiers in Java are case sensitive
Examples of Legal Identifiers
 number, Number, sum_$, bingo, $$_100, mål, grüß 
 
Examples of Illegal Identifiers
   48chevy, all@hands, grand-sum
 

Keywords

  • Keywords are reserved words that are predefined in the language and cannot be used to denote other entities.
  • All the keywords are in lowercase, and incorrect usage results in compilation errors.
  • Three identifiers are reserved as predefined literals in the language: the null reference, and the boolean literals true and false
  • A reserved word cannot be used as an identifier
The following are keywords
  1. abstract
  2. assert
  3. boolean
  4. break
  5. byte
  6. case
  7. catch
  8. char
  9. class
  10. continue
  11. default
  12. do
  13. double
  14. else
  15. enums
  16. extends
  17. final
  18. finally
  19. float
  20. for
  21. if
  22. implements
  23. import
  24. instanceof
  25. int
  26. interface
  27. long
  28. native
  29. new
  30. package
  31. private
  32. protected
  33. public
  34. return
  35. short
  36. static
  37. strictfp
  38. super
  39. switch
  40. syncronized
  41. this
  42. throw
  43. throws
  44. transient
  45. try
  46. void
  47. volatile
  48. while
Reserved Keywords Not Currently in Use
  1. cons
  2. goto

What is Literals

Any constant value which can be assigned to the variable is called as literal/constant.

A literal denotes a constant value, i.e., the value that a literal represents remains unchanged in the program

Literals represent numerical (integer or floating-point), character, boolean or string values.

In addition, there is the literal null that represents the null reference

Example of Literals
    Integer
  1. 200
  2. 0
  3. -7
    Floating-point
  1. 3.14
  2. -3.14
  3. .5
  4. 0.5
    Character
  1. "a"
  2. "A"
  3. "0"
  4. ":"
  5. "-"
  6. ")"
    Boolean
  1. true
  2. false
    String
  1. "abba"
  2. "3.14"
  3. "for"
  4. "a piece of action"
Reserved Literals in Java
  1. null
  2. true
  3. false

Comments in Java

Comments are for documentation purposes only and are ignored by the compiler.

Java provides 3 types of comments:

Single line comments:
     // Something …… 
Multiple line comments:
   /* comments on
	multiple lines 
	*/
A documentation Comment:
/**
* Developed by Company
* @author :  S. R.
* @version 1.0
*/

Java Data Types

Java supports two data types:

  1. Reference types or object types
  2. Primitive or primary or basic types

Reference types or object types

Reference variables are created using defined constructors of the classes. They are used to access objects. These variables are declared to be of a specific type that cannot be changed.

For example, Employee, Puppy etc.

Class objects, and various type of array variables come under reference data type

Default value of any reference variable is null.

A reference variable can be used to refer to any object of the declared type or any compatible type.

Example : Animal animal = new Animal("giraffe");

The following are primitive data type

  1. Boolean Type
  2. Numeric Type
    1. Integral Type
      1. Character Type
        1. char
      2. Integer Type
        1. byte
        2. short
        3. int
        4. long
    2. Floating-point Type
      1. float
      2. double

Summary of primitive data type

Data type Width(bits) Min Value Max Value Wrapper Class
boolean N/A true,false   Boolean
char 16 0*0 0*ffff Character
byte 8 -27 27-1 Byte
short 16 -215 215-1 Byte
int 32 -231 231-1 Integer
long 64 -263 263-1 Long
float 32 +-1.40129846432481707e-45f Long
Double 64 Double

Java Variables

In Java, there are 3 (three) types of variable depending on the location of the variable declaration

  • – Local variable:---

    declared inside the method or function

  • – Instance variable or Non-static variable or attribute or field:---

    declared outside the method or function but inside the class

  • – Class variable or Static variable:---

    declared outside the method or function but inside the class and follows a keyword static

Instance variable and static variable will be discussed later

Variable Declaration & Initialization

Syntax:         

                data_type  variable_name;  [declaration]
			    variable_name = value;     [initialization] 

Example:

		int x,w,p,y;    [declaration] 

		x = 20; 	   [initialization] 
		y = 30;      [initialization] 
		int z=10;

Example:

public class HelloWorld{
		int x = 10;   // instance variable 
		static int y = 20;  // static or class variable 

		public static void main( String varName[]){
		int z = 30; // Local variable                    	 
		System.out.println(“Hello World”);
		}
}

ARRAY in JAVA

  • An array is a data structure that defines an indexed collection of a fixed number of homogeneous or same data elements. This means that all elements in the array have the same data type.
  • A position in the array is indicated by a non-negative integer value called the index
  • An element at a given position in the array is accessed using the index. The size of an array is fixed and cannot be changed.
  • In Java, arrays are objects. Arrays can be of primitive data types or reference types
  • The first element is always at index 0 and the last element at index n-1, where n is the value of the length field in the array.
  • Simple arrays are one-dimensional arrays, that is, a simple list of values
  • Since arrays can store reference values, the objects referenced can also be array objects. Thus, multi-dimensional arrays are implemented as array of arrays.

Declaring One Dimensional Array variables:

Syntax:	data_type variableName [ ];
Or	data_type [ ] variableName ;
Example:
int	x [ ];    // x is an Array Variable that can hold int element.
int	x [], y;    // x is an Array Variable, but y is an int primitive.
int   [] x, y;    // x and y both are Array Variables those can hold int element.

Constructing an One Dimensional Array:

Syntax:	variableName = new data_type [size] ;
Example:	x = new int [5];    // 5 consecutive memory locations are created and referred by  x.

Initializing an One Dimensional Array:

Syntax:	variableName[index] = value ;
Example:	x [0] = 10;    
		x [1] = 20;    
		x [2] = x[0] + x[1];    
		x [3] = 40;    
		x [4] = 50;    

Declaring and Constructing One Dimensional Array in One Statement:

Syntax:	data_type  variableName [] = new data_type [size] ;
Example:	int   x []  = new int [5];    

Declaring, Constructing & Initializing One Dimensional Array in One Statement:

Syntax:	data_type  variableName [ ] = { value1, ….., valueN} ; 

Here, an array of size N is created. At index 0, we have value1 and at index N-1, we have valueN.

Example:	int   x [ ]  = { 10, 20, 30, 40, 50};    

Array Example:

class MyArray{	
	public static void main(String args[]){		
		int a [];
		a =new int[3];		
		a[0] = 10;
		a[1] = a[0]*2;
		a[2] = a[1]*2;		
		// Printing the value of an Individual Array Element
		System.out.println(a[0]);
		System.out.println(a[1]);
		System.out.println(a[2]);	
		
		
		          // Printing the values of an Array using LOOP
        for(int index = 0; index<a.length; index++){
                         // Here, "index" is the loop control variable
						// and is the variable to represent INDEX
			System.out.println(a[index]);		
		}		
	}			
}
  

The following code displays all the elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}
This would produce following result:
1.9
2.9
3.4
3.5

Demonstrate a two-dimensional array.

class TwoDArray { 
public static void main(String args[]) { 
int twoD[][]= new int[4][5]; 
int i, j, k = 0; 
for(i=0; i<4; i++) 
for(j=0; j<5; j++) { 
twoD[i][j] = k; 
k++; 
} 
for(i=0; i<4; i++) { 
for(j=0; j<5; j++) 
System.out.print(twoD[i][j] + " "); 
System.out.println(); 
} 
} 
} 
This program generates the following output: 
0 1 2 3 4 
5 6 7 8 9 
10 11 12 13 14 
15 16 17 18 19


Manually allocate differing size second dimensions

class TwoDAgain { 
public static void main(String args[]) { 
int twoD[][] = new int[4][]; 
twoD[0] = new int[1]; 
twoD[1] = new int[2]; 
twoD[2] = new int[3]; 
twoD[3] = new int[4]; 
int i, j, k = 0; 
for(i=0; i<4; i++) 
for(j=0; j<i+1; j++) { 
twoD[i][j] = k; 
k++; 
} 
for(i=0; i<4; i++) { 
for(j=0; j<i+1; j++) 
System.out.print(twoD[i][j] + " "); 
System.out.println(); 
} 
} 
} 
This program generates the following output: 
0 
1 2 
3 4 5 
6 7 8 9

Unicode System

Unicode is a universal international standard character encoding that is capable of representing most of the world's written languages.

Why java uses Unicode System?

Before Unicode, there were many language standards:
  • ASCII (American Standard Code for Information Interchange) for the United States.
  • ISO 8859-1 for Western European Language.
  • KOI-8 for Russian.
  • GB18030 and BIG-5 for chinese, and so on.

Problem

This caused two problems:
  1. A particular code value corresponds to different letters in the various language standards.
  2. The encodings for languages with large character sets have variable length.Some common characters are encoded as single bytes, other require two or more byte.

Solution

To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF

Modifiers are keywords that you add to those definitions to change their meanings. Java language has a wide variety of modifiers, including the following -

  • Java Access Modifiers

  • Non Access Modifiers

To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement, as in the following example.

Example

public class className {     // ...  }    private boolean myFlag;  static final double weeks = 9.5;  protected static final int BOXWIDTH = 42; 

Access Control Modifiers

Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are -

  • Visible to the package, the default. No modifiers are needed.
  • Visible to the class only (private).
  • Visible to the world (public).
  • Visible to the package and all subclasses (protected).

Non-Access Modifiers

Java provides a number of non-access modifiers to achieve many other functionality.

  • The static modifier for creating class methods and variables.

  • The final modifier for finalizing the implementations of classes, methods, and variables.

  • The abstract modifier for creating abstract classes and methods.

  • The synchronized and volatile modifiers, which are used for threads.

bONEandALL