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
, andjava.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:
-
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
). -
Identifiers:
These are user-defined names given to variables, methods, classes, and objects (e.g.,studentName
,main
,calculateTotal
). -
Literals:
Constants or fixed values assigned to variables. Examples include numbers (10
), characters ('A'
), strings ("Hello"
), boolean values (true
,false
). -
Operators:
Symbols that perform operations on variables and values (e.g.,+
,-
,*
,/
,=
,==
). -
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 Type | Description | Example |
---|---|---|
byte | 8-bit integer | byte a = 10; |
short | 16-bit integer | short b = 200; |
int | 32-bit integer | int x = 1000; |
long | 64-bit integer | long l = 123456L; |
float | 32-bit floating-point number | float f = 3.14f; |
double | 64-bit floating-point number | double d = 3.14159; |
char | Single 16-bit Unicode character | char c = 'A'; |
boolean | Represents true or false values | boolean 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:
Using symbolic constants improves code readability and maintainability.
Scope of Variables
The scope of a variable defines where it can be accessed or modified.
-
Local Variable:
Declared inside a method or block. Accessible only within that block. -
Instance Variable:
Declared inside a class but outside any method. Each object has its own copy. -
Static/Class Variable:
Declared with thestatic
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:
-
Implicit Typecasting (Widening Conversion):
Done automatically when converting smaller data type to larger. -
Explicit Typecasting (Narrowing Conversion):
Done manually when converting from larger type to smaller.
Operators and Expressions
Operators are special symbols used to perform operations on variables and values.
Types of Operators:
Operator Type | Examples |
---|---|
Arithmetic Operators | + , - , * , / , % |
Relational Operators | == , != , < , > , <= , >= |
Logical Operators | && , ` |
Assignment Operators | = , += , -= , *= , /= |
Unary Operators | ++ , -- , + , - |
Bitwise Operators | & , ` |
Ternary Operator | condition ? value1 : value2 |
Expression:
An expression is a combination of variables, operators, and values that produces a result.
Decision-Making Statements
Used to execute a block of code based on conditions.
-
if statement
-
if-else statement
-
else-if ladder
-
switch statement
Looping Statements in Java
Used to repeat a set of statements until a condition is met.
-
for loop
-
while loop
-
do-while loop
-
enhanced for loop (used for arrays)
Arrays in Java
-
Arrays store multiple values of the same data type in a single variable.
-
They are indexed from 0 to size-1.
-
Arrays in Java are objects, and memory is allocated at runtime using
new
. -
Java supports single-dimensional and multi-dimensional arrays.
Syntax:
Example:
2. Strings in Java
-
A
String
is a sequence of characters stored in an object. -
Strings are immutable in Java (once created, they cannot be changed).
-
Strings can be created using literals or the
new
keyword. -
The
String
class provides many built-in methods likelength()
,charAt()
,equals()
, etc.
Syntax:
Example:
3. StringBuffer in Java
-
StringBuffer
is a mutable sequence of characters. -
It is used when modifying strings frequently (better performance than
String
). -
It supports methods like
append()
,insert()
,reverse()
,delete()
. -
It is synchronized, making it thread-safe.
Syntax:
Example:
4. Vectors in Java
-
A
Vector
is a resizable array that grows as needed. -
It is found in
java.util
package and is synchronized. -
It stores objects only (not primitive types directly).
-
Provides methods like
add()
,remove()
,get()
,size()
.
Syntax:
Example:
5. Wrapper Classes in Java
-
Wrapper classes convert primitive types into objects.
-
Common wrapper classes:
Integer
,Double
,Character
,Boolean
, etc. -
Useful in collections where only objects are allowed.
-
Supports autoboxing and unboxing (automatic conversion).
Syntax:
Example:
Comments
Post a Comment