0% found this document useful (0 votes)
16 views5 pages

Java Keywords and Basic Syntax Guide

This document provides an overview of key concepts in the Java programming language, including keywords, comments, variables and data types, classes, objects, interfaces, and static and instance members. It defines keywords as reserved words that help the compiler understand what a program is supposed to do. It describes the different types of comments in Java and their purposes. It also explains variables and data types, classes, objects, interfaces, and the differences between static and instance members.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

Java Keywords and Basic Syntax Guide

This document provides an overview of key concepts in the Java programming language, including keywords, comments, variables and data types, classes, objects, interfaces, and static and instance members. It defines keywords as reserved words that help the compiler understand what a program is supposed to do. It describes the different types of comments in Java and their purposes. It also explains variables and data types, classes, objects, interfaces, and the differences between static and instance members.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Keywords

There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case. Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase. abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

Keywords are marked in yellow as shown in the sample code below /** This class is a Hello World Program used to introduce the Java Language*/ public class HelloWorld { public static void main(String[] args) { [Link](Hello World); //Prints output to console } } For more information on different Keywords Java Keywords Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to the C programming language. const and goto are Java keywords. The word finalize is the name of a method of the Object class and hence not a keyword. enum and label are not keywords.

Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program. Java supports three comment styles. Block style comments begin with /* and terminate with */ that spans multiple lines. Line style comments begin with // and terminate at the end of the line. (Shown in the above program) Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program) name of this compiled file is comprised of the name of the class with .class as an extension.

Variable, Identifiers and Data Types


Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned. public class localVariableEx { public static int a; public static void main(String[] args) { int b; [Link]("a : "+a); [Link]("b : "+b); //Compilation error }} Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value. The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types. Java has four main primitive data types built into the language. We can also create our own data types.

Integer: byte, short, int, and long. Floating Point: float and double Character: char Boolean: variable with a value of true or false.

The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search. Data Type byte short int long float double char String (object) boolean Default Value (for fields) 0 0 0 0L 0.0f 0.0d \u0000 null false Range -127 to +128 -32768 to +32767

0 to 65535

When we declare a variable we assign it an identifier and a data type. For Example String message = hello world In the above statement, String is the data type for the identifier message. If you dont specify a value when the variable is declared, it will be assigned the default value for its data type. Identifier Naming Rules

Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character. Must begin with a letter, dollar sign, or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope, each user defined item must have a unique identifier Can be of any length.

Classes

A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.

Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.

Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which represent an objects state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot . notation with a object reference is used to access Instance Members.

Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references. Below is a program showing the various parts of the basic language syntax that were discussed above. /** Comment * Displays "Hello World!" to the standard output. */ public class HelloWorld {

String output = ""; static HelloWorld helloObj; public HelloWorld(){ output = "Hello World"; } public String printMessage(){ return output; }

//Line 1

public static void main (String args[]) { helloObj = new HelloWorld(); //Line 2 [Link]([Link]()); } }

Common questions

Powered by AI

Local variables are declared within a method or block and are only accessible within that method or block. They are not initialized automatically, meaning that they must be assigned a value before being used. If a programmer attempts to access a local variable without assigning a value, a compilation error occurs . Instance variables, on the other hand, are associated with an object and are initialized with default values for their data types. They have a broader scope, existing as long as the instance (object) exists, and are accessed via object references .

Data types in Java define the kind of values a variable can hold and the operations that can be performed on them. For instance, an 'int' variable can store integer values and support arithmetic operations, while a 'boolean' variable is restricted to 'true' or 'false' values for logical operations. Data type declarations impact memory allocation, ensure type safety by preventing invalid operations, and help the compiler catch errors. Default values are assigned based on data types when variables are declared as fields without an explicit initialization .

The 'final' keyword serves different purposes based on its context: for variables, it prevents reassignment, making the value constant and enhancing program predictability. For methods, 'final' prevents subclasses from modifying a method's implementation, ensuring consistent behavior across class hierarchies. When used with classes, 'final' inhibits inheritance, stopping further extension or manipulation of the class's behavior by subclasses, enabling the implementation of high-security or highly optimized pieces of code .

Default values in Java provide initial values to fields present in class instances, facilitating predictable behavior when fields are accessed before explicit initialization. For instance, numeric data types like int and long default to 0, char defaults to '', and object references default to null. Booleans default to false . Understanding these values is critical for developers to safeguard against null pointer exceptions or logical errors that can stem from assuming uninitialized variables hold meaningful values. This knowledge is also essential in designing classes that are robust and less prone to errors arising from improper field initialization.

Static members in Java are associated with the class itself rather than any particular instance of the class. They are initialized when the class is loaded and can be accessed using the class name or an object reference. In contrast, instance members are associated with the object instances of the class and require an object reference for access. Static members, which include static variables and methods, provide common functionality to all instances, whereas instance members define state and behavior specific to each instance .

Comments in Java play a crucial role in making code understandable to others and for future reference by the original programmer. They explain the purpose, operation, and nuances of code segments. Java supports three types of comments: block comments (/* ... */) for multi-line explanations, line comments (//) for concise, single line notes, and documentation comments (/** ... */), which are processed by documentation tools like javadoc for generating API docs. Proper use of commenting enhances maintainability and collaborative development .

Java keywords are reserved words with a predefined meaning in the language, instructing the compiler on what operations or tasks the program is intended to perform. These keywords cannot be used for naming variables, classes, or methods because they hold specific significance in how the program functions. All Java keywords are case-sensitive and written in lowercase. Examples of Java keywords include 'if', 'for', 'class', 'void', and 'public' .

Java's strict typing rules require that each variable is declared with a data type, ensuring static type checking at compile-time. This reduces runtime errors and enhances program reliability by catching type mismatches early in the development process. Identifiers, such as variable and method names, must follow specific naming conventions to prevent clashes with reserved keywords and to ensure clarity and maintainability of the code. While this strict typing may initially seem restrictive, it promotes code stability and prevents inadvertent data manipulation through implicit type conversions .

Using interfaces is preferred when defining a contract for behaviors that different classes can implement, ensuring loose coupling between components and enhanced flexibility in object-oriented design. Interfaces allow multiple inheritance of method definitions across unrelated classes, promoting a design where different implementations of the same interface can be swapped with minimal changes to the code. They are particularly useful in scenarios where polymorphism is needed without enforcing a strict hierarchical class structure, unlike class-based inheritance which creates tightly coupled dependencies .

Comments improve software development by promoting clear communication of program logic and intentions among team members and future maintainers, thereby reducing misconceptions during code evolution. They support code readability, aiding debugging and modification tasks. Inadequate commenting might lead to misunderstandings about the code's functionality, causing maintenance difficulties, errors during code updates, and potential introduction of bugs due to misinterpretations. Lack of comments may also slow down onboarding of new team members or transition between teams by extending the time required for understanding unfamiliar code .

You might also like