0% found this document useful (0 votes)
6 views

Java Prograaming (22412)- Notes (Unit-1)

The document provides an overview of basic syntactical constructs in Java, highlighting its features such as simplicity, object-oriented principles, platform independence, and security. It also discusses the Java programming environment, including JDK, JRE, and JVM, as well as class definitions, object creation, data types, constants, dynamic initialization, arrays, variable scope, and typecasting. Additionally, it explains the characteristics of local, instance, and static variables in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Prograaming (22412)- Notes (Unit-1)

The document provides an overview of basic syntactical constructs in Java, highlighting its features such as simplicity, object-oriented principles, platform independence, and security. It also discusses the Java programming environment, including JDK, JRE, and JVM, as well as class definitions, object creation, data types, constants, dynamic initialization, arrays, variable scope, and typecasting. Additionally, it explains the characteristics of local, instance, and static variables in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT-1 BASIC SYNTACTICAL CONSTRUCTS IN JAVA

1. JAVA FEATURES

Simple
Java is a simple programming language and easy to understand because it
does not contain complexities. Java contains the same syntax as in C, C++, so the
programmers who are switching to Java will not face any problem in terms of
syntax. Secondly, the concept of pointers has been completely removed from Java
which leads to confusion for a programmer and pointers are also vulnerable to
security.
Object-Oriented
Means in Java everything is written in terms of classes and objects. Now,
what is an Object? Object is nothing but a real world entity that can represent any
person, place, or thing and can be distinguished from others. Every object near us
has some state and behavior associated with it. For example, my mobile phone, it
is a real world entity and has states like color, model, brand, camera quality, etc.
The main concepts of any Object Oriented Programming language are given below:

1. Class and Object


2. Encapsulation
3. Abstraction
4. Inheritance
5. Polymorphism

Platform Independent
Here platform means a type of operating system and hardware technology.
Java allows programmers to write their program on any machine with any
configuration and to execute it on any other machine having different
configurations.
In Java, Java source code is compiled to bytecode and this bytecode is not
bound to any platform. In Fact, this bytecode is only understandable by the Java
Virtual Machine which is installed in our system. What I meant to say is that every
operating system has its own version of JVM, which is capable of reading and
converting bytecode to an equivalent machine native language. This reduces the
overhead of programmers writing system specific code. Now programmers write
programs only once, compile it, to generate the bytecode and then export it
anywhere.
Portable
The WORA (Write Once Run Anywhere) concept and platform independent
feature make Java portable. Now using the Java programming language, developers
can yield the same result on any machine, by writing code only once. The reason
behind this is JVM and bytecode.
Robust
The Java Programming language is robust, which means it is capable of handling
unexpected termination of a program. There are 2 reasons behind this, first, it has
a most important and helpful feature called Exception Handling. If an exception
occurs in java code then no harm will happen whereas, in other low level
languages, the program will crash. Another reason why Java is strong lies in its
memory management features. Unlike other low level languages, Java provides a
runtime Garbage collector offered by JVM, which collects all the unused variables.
Secure
In today’s era, security is a major concern of every application. As now every
device is connected to each other using the internet and this opens up the
possibility of hacking. And our application build using java also needs some sort of
security. So Java also provides security features to the programmers. Security
problems like virus threat; tampering, eavesdropping, and impersonation (act of
pretending to be another person on the internet.) can be handled or minimized
using Java.
Virus is a program that is capable of harming our system and this is generally
spread with .exe files, image files, and video files but cannot be spread using a text
file and good thing is java bytecode is also a text file (yes .class file also a text file
with non-human readable format).
Interpreted
In programming languages, you have learned that they use either the compiler
or interpreter, but Java programming language uses both a compiler and
interpreter. Java programs are compiled to generate bytecode files then JVM
interprets the bytecode file during execution.
Multi-Threaded
Thread is a lightweight and independent sub process of a running program (i.e.,
process) that shares resources. And when multiple threads run simultaneously is
called multi-threading. In many applications, you have seen multiple tasks running
simultaneously, for example, Google Docs where while typing text, the spell checks
and autocorrect task are running.

2. JAVA PROGRAMMING ENVIRONMENT

JDK (Java Development Kit): JDK is intended for software developers and
includes development tools such as the Java compiler, Javadoc, Jar, and a
debugger.
JRE (Java Runtime Environment): JRE contains the parts of the Java
libraries required to run Java programs and is intended for end-users. JRE can be
viewed as a subset of JDK.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that
provides a runtime environment in which java bytecode can be executed. JVMs
are available for many hardware and software platforms.
STEPS:
 Download & install Jdk 8 version
 Set environment variable & set path

3. CLASS DEFINITION, OBJECT CREATION & ACCESSING CLASS MEMBERS

Class: is a template used to create objects and to define object data types
and methods.
For Example: In Java, the “Cat” class is the blueprint from which all
individual cats can be generated that includes all cat characteristics, such as race,
fur color, tail length, eyes shape, etc.
A class declaration is made up of the following parts:

 Modifiers
 Class name
 Superclass (the name of a class’ parent, if available)
 Implemented Interfaces (if any)
 Appropriate Keywords depending on whether the class extends from a
Superclass and/or implements one or more interface
 Class body within curly brackets {}

Object: an object is an instance of a Java class, meaning it is a copy of a


specific class. Java objects have three primary characteristics: identity, state, and
behavior. These characteristics are the building blocks of any class object.
Identity: The identity of an object is a unique identifier, such as a memory address, ID,
or even a name.
State: The state controls aspects of an object; in the case of describing a fan, you could
have an on, off, low, medium, or high state. State monitors behavior, such as turning a fan on or off,
the state will change when the behavior happens.
Behavior: Object behavior is used to describe what an object can do, such as a fan
turning on or off or changing speeds.
For example: suppose Bicycle is a class
then MountainBike, SportsBike, TouringBike, etc. can be considered as objects of
the class.
Creating an Object in Java
className object = new className();

// for Bicycle class


Bicycle sportsBike = new Bicycle ();
Bicycle touringBike = new Bicycle ();

4. JAVA TOKENS & DATA-TYPES

JAVA TOKENS
The Java compiler breaks the line of code into text (words) is called Java
tokens. These are the smallest element of the Java program. The Java compiler
identified these words as tokens. These tokens are separated by the delimiters. It is
useful for compilers to detect errors.
token <= identifier | keyword | separator | operator | literal | comment
For example, consider the following code.
public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}
In the above code snippet, public, class, Demo, {, static, void, main, (,
String, args, [,],), System, out, println, javatpoint, etc. are the Java tokens.
DATA-TYPES
As the name suggests, data types specify the type of data that can be stored
inside variables in Java.
This means that all variables must be declared before they can be used.
Example: int speed;
Here, speed is a variable, and the data type of the variable is int.
There are 8 data types predefined in Java, known as primitive data types.
Boolean type
The Boolean data type has two possible values, either true or false.
Default value: false.
They are usually used for true/false conditions.
Byte type
If it's certain that the value of a variable will be within -128 to 127, then it is
used instead of int to save memory.
Default value: 0
Short type
If it's certain that the value of a variable will be within -32768 and 32767,
then it is used instead of other integer data types (int, long).
Default value: 0
int type
The int data type can have values from -231 to 231-1 (32-bit signed two's
complement integer).
Default value: 0
Long type
The long data type can have values from -263 to 263-1 (64-bit signed two's
complement integer).
Default value: 0
Double type
The double data type is a double-precision 64-bit floating-point.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0d)
Float type
The float data type is a single-precision 32-bit floating-point. Learn more
about single-precision and double-precision floating-point if you are
interested.
It should never be used for precise values such as currency.
Default value: 0.0 (0.0f)
Char type
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000' (0) and the maximum
value of the is '\uffff'.
Default value: '\u0000'
String type
Java also provides support for character strings via java.lang.String class.
Strings in Java are not primitive types. Instead, they are objects. For
example, String myString = "Java Programming";
Here, myString is an object of the String class.

5. CONSTANTS
A constant is something that in immutable. In Java programming constant is
a variable whose value cannot be changes once it has been assigned.
Constants can be declared using Java's static and final keywords.
The static keyword is used for memory management and final keyword signifies the
property that the value of the variable cannot be changed. It makes the primitive
data types immutable.
Example: static final float PI = 3.14f;

6. DYNAMIC INITIALIZATION
If any variable is not assigned with value at compile-time and assigned at
run time is called dynamic initialization of a variable.
Basically, this is achieved through constructors, setter methods, normal
methods which return a value or object.
public class First{
public static void main( String args[] )
{
int r;
double circumference;
r= 6; //Initialization
circumference = 2 * Math.PI * r; //Dynamic Initialization
System.out.println(" circumference= " + circumference);
}
}
public class First
{
public static void main( String args[] )
{
int [] array = {2,5,7,8,9, 10}; //array initialization
or
int [] array;
array = new int[] {2, 5, 7, 8, 9, 10};
for (int i = 0; i <= 5; i++)
{
System.out.println("Array= " + array[i]);
}
}
}

7. ARRAY & STRING


An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an
array of the string type that can store 100 names.
String [] array = new String [100];

Here, the above array cannot store more than 100 names. The number of values in
a Java array is always fixed.
// declare an array
double [] data;
// allocate memory
data = new double[10];
String is basically an object that represents sequence of char values.
An array of characters works same as Java string.

String greeting = "Hello world!";


String s1 = new String ("Hello world!");
8. SCOPE OF VARIABLE
The scope of variables in Java is a location (or region) of the program
where the variable is visible to a program and can be accessible.
In other words, the variable scope is the location from which we can access
its value. The scope of variables determines its accessibility for other parts of the
program.
Java allows declaring variables within any block. A block defines a scope that
starts with an opening curly brace and ends with a closing curly brace.

1. When we create a local variable inside a method, constructor, or block, its scope
only remains within the method, block, or constructor.
They are visible only within the method, constructor, or block. As you exit from the
method or block, then the scope of a local variable is destroyed.
2. We cannot access local variables from outside the method, constructor, or block.
3. We cannot change their values from outside of any block.
There are three types of variables in java. They are as:
1. Local variables
1. A variable that is declared and used inside the body of methods,
constructors, or blocks is called local variable in java. It is called so
because local variables are not available for use from outside.
2. We must assign a local variable with a value at the time of creating. If
you use a local variable without initializing a value, you will get a compile-
time error like “variable x not have been initialized”.
3. We cannot use access modifiers with local variables.
4. The local variables are visible only within the declared constructors,
methods, or blocks.
5. A local variable is not equivalent to an instance variable.
6. A local variable cannot be static.
2. Instance variables
1. A variable that is declared inside the class but outside the body of the
methods, constructors, or any blocks is called instance variable in java.
They are available for the entire class methods, constructors, and blocks.
It is also called non-static variable because it is not declared as static.
2. Instance variables are created when an object is created using the
keyword ‘new’ and destroyed when the object is destroyed.
3. We can also use access modifiers with instance variables. If we do not
specify any modifiers, the default access modifiers will be used which can
be accessed in the same package only.
4. It is not necessary to initialize the instance variable.
3. Class/Static variables
1. A variable which is declared with a static keyword is called static
variable in java. A static variable is also called class variable because it
is associated with the class.
2. Static variables are always declared inside the class but outside of any
methods, constructors, or blocks.
3. Static variable will get the memory only once. If anyone changes the
value of the static variable using the class name, it will replace the
previous value and display the changed value. This is because it is
constant for every object created.

9. TYPECASTING
The process of converting the value of one data type (int, float, double, etc.)
to another data type is known as typecasting.

1. Widening Type Casting


Java automatically converts one data type to another data type.
In the case of Widening Type Casting, the lower data type (having
smaller size) is converted into the higher data type (having larger size).
Hence there is no loss in data. This is why this type of conversion
happens automatically.
This is also known as Implicit Type Casting.
class Main The integer value: 10
{ The double value: 10.0
public static void main(String[] args)
{
int num = 10;
System.out.println("The integer value: " + num);
// convert into double type
double data = num;
System.out.println("The double value: " + data);
}
}

2. Narrowing Type Casting


we manually convert one data type into another using the parenthesis.
In the case of Narrowing Type Casting, the higher data types (having
larger size) are converted into lower data types (having smaller size). Hence there
is the loss of data. This is why this type of conversion does not happen
automatically.
This is also known as Explicit Type Casting.
class Main The double value: 10.99
{ The integer value: 10
public static void main(String[] args)
{
// create double type variable
double num = 10.99;
System.out.println("The double value: " + num);
// convert into int type
int data = (int)num;
System.out.println("The integer value: " + data);
}
}
10. OPERATORS
Operators are symbols that perform operations on variables and values.
For example, + is an operator used for addition, while * is also an operator used
for multiplication.

1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on
variables and data.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

class Main a + b = 17
{ a -b=7
public static void main(String[] args) a * b = 60
{ a /b=2
// declare variables a %b=2
int a = 12, b = 5;
// addition operator
System.out.println("a + b = " + (a + b));
// subtraction operator
System.out.println("a - b = " + (a - b));
// multiplication operator
System.out.println("a * b = " + (a * b));
// division operator
System.out.println("a / b = " + (a / b));
// modulo operator
System.out.println("a % b = " + (a % b));
}
}
2. Assignment Operators

Assignment operators are used in Java to assign values to variables.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

class Main var using =: 4


{ var using +=: 8
public static void main(String[] args) var using *=: 32
{
// create variables
int a = 4;
int var;
// assign value using =
var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}

3. Relational Operators

Relational operators are used to check the relationship between two

operands.

It returns either true or false.

Relational operators are used in decision making and loops.


Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

class Main a is 7 and b is 11false


{ true
public static void main(String[] args) false
{ true
// create variables false
int a = 7, b = 11; true

// value of a and b
System.out.println("a is " + a + " and b is " + b);
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}

4. Logical Operators

Logical operators are used to check whether an expression

is true or false. They are used in decision making.

Operator Example Meaning


&& (Logical expression1 && true only if both expression1
AND) expression2 and expression2 are true

|| (Logical expression1 || true if either expression1 or


OR) expression2 expression2 is true

! (Logical true if expression is false and


!expression
NOT) vice versa

class Main truefalse


{ true
public static void main(String[] args) true
{ false
// && operator true
System.out.println((5 > 3) && (8 > 5)); // true false
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}

5. Unary Operators

Unary operators are used with only one operand. For example, ++ is a

unary operator that increases the value of a variable by 1.

Operator Meaning

Unary plus: not necessary to use since numbers are


+
positive without using it

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

Logical complement operator: inverts the value of a


!
boolean
Java Increment & decrement operator Value of a: 12
class Main After increment: 13
{ Value of b: 12
public static void main(String[] args) After decrement: 11
{
// declare variables
int a = 12, b = 12;
int res1, res2;
// original value
System.out.println("Value of a: " + a);
// increment operator
result1 = ++a;
System.out.println("After increment: " + res1);
System.out.println("Value of b: " + b);
// decrement operator
result2 = --b;
System.out.println("After decrement: " + rest2);
}
}

6. Bitwise Operators

Bitwise operators in Java are used to perform operations on individual

bits.
Bitwise complement Operation of 35
35 = 00100011 (In Binary)

~ 00100011
________
11011100 = 220 (In decimal)
Here, ~ is a bitwise operator. It inverts the value of each bit

(0 to 1 and 1 to 0)

Operator Description

~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift


& Bitwise AND

^ Bitwise exclusive OR

7. instanceof Operator

Operator checks whether an object is an instanceof a particular class.


class Main Is str an object
{ of String? true
public static void main(String[] args)
{
String str = "Programiz";
boolean res;
// checks if str is an instance of
// the String class
res = str instanceof String;
System.out.println("Is str an object of String?"+ res);
}
}

8. Ternary Operator

The ternary operator (conditional operator) is shorthand for the if-then-

else statement.
Variable = Expression ? expression1: expression2

Here's how it works.

 If the Expression is true, expression1 is assigned to the variable.

 If the Expression is false, expression2 is assigned to the variable.


class Java { Leap year
public static void main(String[] args) {

int februaryDays = 29;


String result;

// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
11. OPERATOR PRECEDANCE & ASSOCIATIVITY
Operator precedence determines the order in which the operators in an
expression are evaluated.
The table below lists the precedence of operators in Java; higher it appears
in the table, the higher its precedence.

Java Operator Precedence

Operators Precedence

postfix increment and decrement ++ --

prefix increment and decrement, and


++ -- + - ~ !
unary

multiplicative */%

additive +-

shift << >> >>>

relational < > <= >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

= += -= *= /= %=
assignment &= ^= |= <<= >>=
>>>=
class Precedence 2
{
public static void main(String[]
args)
{
int a = 10, b = 5, c = 1, result;
result = a-++c-++b;

System.out.println(result);
}
}

If an expression has two operators with similar precedence, the expression is


evaluated according to its associativity (either left to right, or right to left).
The table below shows the associativity of Java operators along with their
associativity.

Java Operator Precedence and Associativity

Operators Precedence Associativity

postfix increment and


++ -- left to right
decrement

prefix increment and


++ -- + - ~ ! right to left
decrement, and unary

multiplicative */% left to right

additive +- left to right

shift << >> >>> left to right

< > <= >=


relational left to right
instanceof

equality == != left to right

bitwise AND & left to right

bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right


logical AND && left to right

logical OR || left to right

ternary ?: right to left

= += -= *= /= %=
assignment &= ^= |= <<= right to left
>>= >>>=

12. EXPRESSION
Expression consists of variables, operators, literals.
Double a = 2.2, b = 3.4, result;
result = a + b - 3.4;
Here in this example, a + b - 3.4 is an expression.
13. MATHEMATICAL FUNCTIONS
Java Mathematical functions are predefined functions which accept values
and return the result. To use mathematical functions, we have to
use Math class in our program.
With the help of mathematical functions we can easily solve a complex
equation in our program
abs()
The abs() function returns the absolute value of a number. The
number can be an integer, long, float or double value. Here Absolute
value means number without negative sign. The absolute value of a
number is always positive.
min()
The min() function returns the smallest among two numbers.
The number can be an integer, long, float or double value.
max()
The max() function returns the greater among two numbers.
The number can be an integer, long, float or double value.
sqrt()
The sqrt() function returns the square root of a positive number.
Remember that square root of a negative cannot be calculated.
ceil()
The ceil() function returns the nearest integer number greater
than the number passed as argument.
floor()
The floor() function returns the nearest integer number less
than the number passed as argument.
pow() The pow() function is used to computes the power of a number.

You might also like