Unit I. Basic Syntactical Constructs in Java

 Chapter-1. Basic Syntactical Constructs in Java

Syllabus:

1.1 Java features and the Java programming environment

 1.2 Defining a class, creating object, accessing class members 

1.3 Java tokens and data types, symbolic constant, scope of variable, typecasting, and different types of operators and expressions, decision making and looping statements 

1.4 Arrays, strings, string buffer classes, vectors, wrapper classes 

1.5 Constructors and methods, types of constructors, method and constructor overloading, nesting of methods, command line arguments, garbage collection, visibility control: public, private, protected, default, private protected 


1.1 Java features and the Java programming environment

1.1.1 Features of java

1)    Platform Independence (Write Once, Run Anywhere):

There are several platform such as windowsOS, macOS, linuxOS, etc, but java is platform independent meaning if the Java Virtual Machine (JVM) is installed on both Windows and Linux or any other OS, and you have saved the Java file on Windows, you can run the Java program on Linux as well.



2)    Object-Oriented Programming (OOP):

Java is Object-Oriented since it follows the concepts of class and objects and also encapsulation, abstraction ,abstraction,  polymorphism and inheritance

3)    Simple to implement and understand:

Java has simple and clean syntax which is easy to understand and it has proper memory managemnt since it uses the concept of garbage collection so it is easy to implement

4)    Robust and Secure:

Robustness refers to the ability of a language to handle errors and exceptions in a way that prevents the program from crashing and ensures reliability. Java is designed to be secure, with a number of built-in features that prevent security breaches like unauthorized access, code tampering, or malicious activities.

5)    Multithreading and Concurrency:

Multithreading allows multiple threads (smallest units of execution) to run independently and concurrently(concurrently means the ability to manage multiple taskes within the same interval) in a program

6)    Rich Standard Library (API):

Java has a rich standard library that makes it a powerful and versatile language for software development. The standard library, also known as the Java API (Application Programming Interface), provides a vast collection of built-in classes, interfaces, and methods

7)    Automatic Memory Management (Garbage Collection):

Garbage Collection refers to the process of automatically identifying and reclaiming memory that is no longer in use by the program. The main objective of GC is to free up memory occupied by objects that are no longer reachable or needed by the application, thus preventing memory leaks.

8)    Distributed Computing:

Java is a powerful platform for distributed computing, which involves multiple computers working together over a network to achieve a common goal.

9)    Dynamic and Extensible:

ava is designed to be extensible, which means developers can easily extend its functionality and add new features without modifying existing code.It allows flexibility and adaptability in runtime behavior, making it possible to modify or adapt the application during execution.


1.1.2 Java Programming Environment

1. Java Development Kit (JDK)

1)     Java Development Kit (JDK) is the most important component of the Java programming environment. It contains all the tools needed to develop Java applications, including compilers, libraries, and other utilities.

  • Java Compiler (javac): Converts Java source code (.java files) into bytecode (.class files) that the Java Virtual Machine (JVM) can execute.

  • Java Runtime Environment (JRE): The JDK includes a JRE, which is the part of Java used for running Java applications. The JRE contains the JVM, along with core libraries that are needed to execute Java programs.

  • Java Debugger (jdb): Used to debug Java programs during development.

  • Java API Documentation: Provides the official documentation for the Java libraries and APIs.



 2.      Java Runtime Environment (JRE):

The Java Runtime Environment (JRE) is the part of the Java programming environment that is responsible for running Java applications. The JRE consists of:

  • Java Virtual Machine (JVM): The JVM is the engine that runs Java bytecode, translating it into machine code for the underlying platform.

  • Core Libraries: The JRE contains standard libraries (such as java.util, java.lang, and java.io) that Java programs need to function.

  • Native Libraries: These are platform-specific libraries required for interacting with the underlying operating system (OS).

3. Java Virtual Machine (JVM)

The Java Virtual Machine (JVM) is a crucial part of the Java programming environment because it allows Java to be platform-independent. The JVM is responsible for:

  • Executing Java bytecode: The JVM interprets or compiles the bytecode into machine-specific instructions.

  • Memory Management: The JVM includes automatic garbage collection, which reclaims memory used by objects that are no longer in use.

  • Cross-Platform Execution: Because the JVM abstracts away platform-specific details, Java programs can run on any device with a JVM installed, making Java platform-independent.

Example:

  • If you write a Java program on a Windows machine and run it on a Linux system, the JVM ensures that the program runs the same way on both platforms.

4. Java Libraries and APIs

Java comes with a vast set of standard libraries and APIs that simplify the development of applications by providing pre-built functionality. These libraries cover a wide range of tasks, including:

  • Collections Framework (e.g., List, Set, Map) for handling data structures.

  • File I/O (e.g., java.io, java.nio) for reading from and writing to files.

  • Networking (e.g., java.net) for creating networked applications.

  • Database Connectivity (e.g., JDBC) for interacting with databases.

  • Multithreading (e.g., java.util.concurrent) for concurrent programming.

Example:

  • Using Java’s java.util package, you can easily manage lists, sets, and maps for tasks such as storing user data or processing collections of objects.

5. Integrated Development Environment (IDE)

An Integrated Development Environment (IDE) is a software application that provides a set of tools for Java developers to write, test, and debug code in a more efficient manner. It typically includes code editors, compilers, debuggers, and sometimes version control integration.


1.2 Defining a class, creating object, accessing class members 

1.2.1 Defining a class.

In Java, a class is a blueprint or a template for creating objects. It defines the properties (also called fields) and behaviors (also called methods) that the objects created from the class will have. A class serves as a blueprint to instantiate objects.

In java instance is referred to object and function are known as methods, also the "main()" is defined in a class.

Always make sure that you save the file with the same name as that of the name of class which contains the main(), the reason for this is the interpreter must understand from where the execution must be started as the all the function call and instance creation is done in main() and it serves as the entry point for all of them.

Syntax for creation of class is:

1) public class class_name{

//Class defination;

}

We have used public so that all the methods within the class must be available in other packages also.We will futher learn the concept of package, if we dont use public by it will be by deafault where the methods are available only within the package.

2) class class_name{

//Class defination;

}

ex.


In the above progrma, we have created a class 'A', in which we have our main() hence the file is also saved with the name A.java.

The public static void main(Strings []a) refers to, public meaning globally access static means the main() must be able to call without creating its object since it the entry point of all the executions, void since it returns nothing and the name main, Now comes the String []a  parameter in the main() method allows Java programs to accept command-line arguments when the program is executed.

Then to print a statement we have used the method println(), out is a static field from a predefined class that provides the access to the resources.

1.2.2 Creating objects:

Syntax:

1) class_name object_name= new class_name();

here class name to specify fast which object is been created then comes the object, and the new operator which initialises them with the help of a by default constructor created of that class.Declaration and intialisation takes place in the samestep.

2) class_name object_name;

    object_name=new Class_name;

This is another method of creating the object of a class in which both the declaration and initialization takes place in 2 different steps.

1.2.3 Accessing class members:

A class is the collection of data members and member functions which are accessed through the objects created of thst specific objects.

Syntax:

 object_name.member_name;

object_name.member_function_name();

We can also pass the arguements at the time after object creation:

object_name=Function_name(list_of_arguements);

The initialization of objects can also be done at runtime too.

1.3 Java tokens and data types, symbolic constant, scope of variable, typecasting, and different types of operators and expressions, decision making and looping statements 


1.3.1. Java Tokens:

 In java, tokens are the basic building blocks of a program, that makes the compiler understand about the letters used in the program and to execute the efficiently and error less.

Java tokens are divided into  5 types, Identifiers:


Java Tokens and Data Types 

What are Tokens in Java?

Tokens are the smallest individual units in a Java program. Similar to how sentences are formed using words, Java programs are constructed using tokens. During compilation, the Java compiler breaks the source code into tokens for processing.

Types of Java Tokens:

  1. Keywords:
    These are reserved words in Java that have a predefined meaning. They cannot be used as identifiers (e.g., class, int, if, else, public, static).

  2. Identifiers:
    These are user-defined names given to variables, methods, classes, and objects (e.g., studentName, main, calculateTotal).

  3. Literals:
    Constants or fixed values assigned to variables. Examples include numbers (10), characters ('A'), strings ("Hello"), boolean values (true, false).

  4. Operators:
    Symbols that perform operations on variables and values (e.g., +, -, *, /, =, ==).

  5. Separators:
    Symbols used to separate code elements. Examples include:

    • Parentheses ()

    • Curly braces {}

    • Semicolon ;

    • Comma ,

    • Square brackets []


Data Types in Java

Java is a strongly typed language, meaning every variable must be declared with a data type.

1. Primitive Data Types (8 types)

Data TypeDescriptionExample
byte8-bit integerbyte a = 10;
short16-bit integershort b = 200;
int32-bit integerint x = 1000;
long64-bit integerlong l = 123456L;
float32-bit floating-point numberfloat f = 3.14f;
double64-bit floating-point numberdouble d = 3.14159;
charSingle 16-bit Unicode characterchar c = 'A';
booleanRepresents true or false valuesboolean flag = true;

2. Non-Primitive (Reference) Data Types

These are user-defined types or derived types like:

  • Arrays

  • Strings

  • Classes

  • Interfaces


Symbolic Constant

A symbolic constant is a constant value referenced by a name. It is declared using the final keyword and its value cannot be changed once assigned.

Syntax:

final int MAX_VALUE = 100;

Using symbolic constants improves code readability and maintainability.


Scope of Variables

The scope of a variable defines where it can be accessed or modified.

  1. Local Variable:
    Declared inside a method or block. Accessible only within that block.

  2. Instance Variable:
    Declared inside a class but outside any method. Each object has its own copy.

  3. Static/Class Variable:
    Declared with the static keyword. Shared among all instances of a class.


Typecasting in Java

Typecasting is the process of converting one data type into another.

Types of Typecasting:

  1. Implicit Typecasting (Widening Conversion):
    Done automatically when converting smaller data type to larger.

    int a = 10; double b = a; // automatic conversion
  2. Explicit Typecasting (Narrowing Conversion):
    Done manually when converting from larger type to smaller.

    double x = 10.5; int y = (int) x; // manual conversion

Operators and Expressions

Operators are special symbols used to perform operations on variables and values.

Types of Operators:

Operator TypeExamples
Arithmetic Operators+, -, *, /, %
Relational Operators==, !=, <, >, <=, >=
Logical Operators&&, `
Assignment Operators=, +=, -=, *=, /=
Unary Operators++, --, +, -
Bitwise Operators&, `
Ternary Operatorcondition ? value1 : value2

Expression:

An expression is a combination of variables, operators, and values that produces a result.

int a = 5 + 3 * 2;

Decision-Making Statements

Used to execute a block of code based on conditions.

  1. if statement

    if (a > b) { System.out.println("a is greater"); }
  2. if-else statement

    if (a > b) { System.out.println("a is greater"); } else { System.out.println("b is greater"); }
  3. else-if ladder

    if (a > b) { ... } else if (a == b) { ... } else { ... }
  4. switch statement

    int day = 1; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); }

Looping Statements in Java

Used to repeat a set of statements until a condition is met.

  1. for loop

    for (int i = 1; i <= 5; i++) { System.out.println(i); }
  2. while loop

    int i = 1; while (i <= 5) { System.out.println(i); i++; }
  3. do-while loop


    int i = 1; do { System.out.println(i); i++; } while (i <= 5);
  4. enhanced for loop (used for arrays)

    int[] nums = {1, 2, 3}; for (int n : nums) { System.out.println(n); }


Arrays in Java

  1. Arrays store multiple values of the same data type in a single variable.

  2. They are indexed from 0 to size-1.

  3. Arrays in Java are objects, and memory is allocated at runtime using new.

  4. Java supports single-dimensional and multi-dimensional arrays.

Syntax:

dataType[] arrayName = new dataType[size];

Example:

int[] marks = new int[5]; marks[0] = 90; marks[1] = 85; System.out.println("First Mark: " + marks[0]);

2. Strings in Java

  1. A String is a sequence of characters stored in an object.

  2. Strings are immutable in Java (once created, they cannot be changed).

  3. Strings can be created using literals or the new keyword.

  4. The String class provides many built-in methods like length(), charAt(), equals(), etc.

Syntax:

String str = "Hello";

Example:

String str = "Anuja"; System.out.println("Length: " + str.length()); System.out.println("Uppercase: " + str.toUpperCase());

3. StringBuffer in Java

  1. StringBuffer is a mutable sequence of characters.

  2. It is used when modifying strings frequently (better performance than String).

  3. It supports methods like append(), insert(), reverse(), delete().

  4. It is synchronized, making it thread-safe.

Syntax:

StringBuffer sb = new StringBuffer("Hello");

Example:

StringBuffer sb = new StringBuffer("Anuja"); sb.append(" Gurav"); System.out.println(sb); // Output: Anuja Gurav

4. Vectors in Java

  1. A Vector is a resizable array that grows as needed.

  2. It is found in java.util package and is synchronized.

  3. It stores objects only (not primitive types directly).

  4. Provides methods like add(), remove(), get(), size().

Syntax:

Vector<Type> vectorName = new Vector<>();

Example:

import java.util.Vector; Vector<String> names = new Vector<>(); names.add("Anuja"); names.add("Gurav"); System.out.println(names.get(0)); // Output: Anuja

5. Wrapper Classes in Java

  1. Wrapper classes convert primitive types into objects.

  2. Common wrapper classes: Integer, Double, Character, Boolean, etc.

  3. Useful in collections where only objects are allowed.

  4. Supports autoboxing and unboxing (automatic conversion).

Syntax:

Integer i = Integer.valueOf(10); // Boxing int x = i; // Unboxing

Example:

Integer age = 20; // autoboxing int newAge = age; // unboxing System.out.println("Age is: " + newAge);

Constructors

  • A constructor is a special method in Java used to initialize objects when they are created.

  • It has the same name as the class and does not have any return type.

  • It is automatically called when an object of the class is created.

  • Java provides a default constructor if no constructor is defined.

  • Constructors can be overloaded with different parameters.

  • It helps set default or initial values to object properties.

Syntax:
ClassName() { }

Example:

class Demo { Demo() { System.out.println("Constructor called"); } public static void main(String[] args) { Demo d = new Demo(); } }

Types of Constructors

  • Java supports default, parameterized, and copy constructors.

  • Default constructor has no parameters and is auto-created by Java.

  • Parameterized constructor accepts arguments to initialize variables.

  • Copy constructor manually copies data from another object.

  • Constructors can be overloaded using different parameter types.

  • Constructors must have the same name as the class.

Syntax:
ClassName() { }
ClassName(String s) { }

Example:

class Student { Student() { System.out.println("Default Constructor"); } Student(String name) { System.out.println("Name: " + name); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student("Anuja"); } }

Methods

  • A method is a set of statements that perform a task in a program.

  • It may return a value or be declared as void if it returns nothing.

  • Methods help reuse code by calling them multiple times.

  • They can accept parameters and perform operations based on inputs.

  • Methods belong to classes and are called using objects unless static.

  • The method name and return type must be defined properly.

Syntax:
returnType methodName(parameters) { }

Example:

class Test { void greet() { System.out.println("Hello Anuja"); } public static void main(String[] args) { Test t = new Test(); t.greet(); } }

Method and Constructor Overloading

  • Overloading means using the same name with different parameter lists.

  • Method overloading allows different ways of calling the same method.

  • Constructor overloading lets us create objects with different initial values.

  • It is an example of compile-time polymorphism.

  • Parameters must differ by number, type, or order for overloading.

  • Return type alone is not sufficient for overloading.

Syntax:
void display() { }
void display(int a) { }

Example:

class Overload { Overload() { System.out.println("Default"); } Overload(String msg) { System.out.println("Message: " + msg); } void show() { System.out.println("No param"); } void show(String s) { System.out.println("Param: " + s); } public static void main(String[] args) { Overload o = new Overload(); Overload o2 = new Overload("Anuja"); o.show(); o.show("Hello"); } }

Nesting of Methods

  • Nesting refers to calling one method inside another method.

  • It improves code modularity and readability.

  • The inner method executes when called by the outer method.

  • Methods should belong to the same class to be nested.

  • It is useful for breaking complex logic into simpler steps.

  • Helps in organizing repetitive code blocks.

Syntax:
void method1() { method2(); }

Example:

class Nesting { void display() { show(); } void show() { System.out.println("Nested method called"); } public static void main(String[] args) { Nesting n = new Nesting(); n.display(); } }

Command Line Arguments

  • Command line arguments are passed through the main method while running the program.

  • They are always treated as strings and stored in the args[] array.

  • Each argument can be accessed using an index like args[0].

  • Useful for passing values dynamically to the program.

  • Arguments are separated by spaces in the terminal.

  • The program must be run using the java ClassName value1 value2 format.

Syntax:
public static void main(String[] args) { }

Example:


class CommandLine { public static void main(String[] args) { System.out.println("Hello " + args[0]); } }

Garbage Collection

  • Java handles memory cleanup using an automatic garbage collector.

  • Unused objects with no references are removed to free memory.

  • System.gc() is used to request garbage collection.

  • The finalize() method can be overridden to clean up before deletion.

  • It prevents memory leaks and improves application performance.

  • Helps in efficient memory management without manual deallocation.

Syntax:
System.gc();

Example:

class GarbageDemo { protected void finalize() { System.out.println("Object deleted"); } public static void main(String[] args) { GarbageDemo g = new GarbageDemo(); g = null; System.gc(); } }

Visibility Control (Access Modifiers)

  • Access modifiers define where class members can be accessed from.

  • public members are accessible from everywhere in all packages.

  • private members are only accessible within the declared class.

  • protected members are accessible in the same package and subclasses.

  • Default (no modifier) is accessible only within the same package.

  • Access modifiers ensure encapsulation and secure data access.

Syntax:
public int a; private int b; protected int c; int d;

Example:


class AccessControl { public int a = 10; private int b = 20; protected int c = 30; int d = 40; void display() { System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } public static void main(String[] args) { AccessControl obj = new AccessControl(); obj.display(); } }

Comments

Popular posts from this blog

Syllabus

Unit VI: Interacting with Database

V. Java Networking