0% found this document useful (0 votes)
24 views97 pages

JAVA NOTES Chapter 1

The document provides an overview of Java programming, highlighting its key features such as simplicity, object-oriented nature, platform independence, security, and robustness. It explains the structure of Java programs, the role of the Java Virtual Machine (JVM), and the distinction between Java Runtime Environment (JRE) and Java Development Kit (JDK). Additionally, it covers Java tokens, keywords, identifiers, and the types and scope of variables.

Uploaded by

ps3639944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views97 pages

JAVA NOTES Chapter 1

The document provides an overview of Java programming, highlighting its key features such as simplicity, object-oriented nature, platform independence, security, and robustness. It explains the structure of Java programs, the role of the Java Virtual Machine (JVM), and the distinction between Java Runtime Environment (JRE) and Java Development Kit (JDK). Additionally, it covers Java tokens, keywords, identifiers, and the types and scope of variables.

Uploaded by

ps3639944
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

Chapter1:

Basic syntactical
Constructs in Java
Features of Java:
Simple, Small and Familiar:

• Java is easy to learn

• Java syntax is Similar to C/C++ in syntax

• But eliminates several complexities of


• Operator overloading
• Explicit pointers: direct pointer manipulation or pointer arithmetic
• Multiple inheritance
• Malloc() and free() –Garbage Collector handles memory automatically
Object-oriented:
• Everything in Java is an object.
• Basic concepts of OOPs are:
❑ Object
❑ Class
❑ Inheritance
❑ Polymorphism
❑ Abstraction
❑ Encapsulation
Compiled and Interpreted:
• Java compiler produces an intermediate code known as byte code for a
machine, known as JVM.

Java
Java Compiler Virtual Machine
Program

• Machine code is generated by the java interpreter by acting as an


intermediary between the virtual machine and real machine.

Bytecode Java Interpreter Machine Code

5/22/2021 Java Programming


6
05/07/2008 Mosarratj Jahan, Dept. of CSE, DU
Platform Independent:

• Java is a write once, run anywhere language.

• Java code can be run on multiple platforms, like, Windows,


Linux, Sun Solaris, Mac , etc.

• Java code is compiled by the compiler and converted into


bytecode.

• This bytecode is a platform-independent code because it


can be run on multiple platforms.

• The Java Virtual Machine (JVM) Convert byte code into


machine level representation.
Secure:
• Java is best known for its security.
• With Java, we can develop virus-free systems.
• Designed with the intention of being secure:

• No explicit pointer

• Java Programs run inside a java virtual machine

• No pointer arithmetic or memory management!

• Strict compile time and run time checking of data type.

• Exception handling

• It verify all memory access

• Ensure that no viruses are communicated with an applet.


Robust:

• Robust simply means strong.

• Java is robust because:

• It uses strong memory management.

• There is a lack of pointers that avoids security problems.

• There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.

• There are exception handling and the type checking mechanism in Java.

• All these makes Java robust.


Architecture-neutral:

• Java is architecture neutral because there are no implementation dependent features.

• Java and the JVM has been designed to overcome this situation, which would enable the
programs to run in spite of severe environmental changes.

• For example, size of primitive types is fixed , in C programming, int data type occupies
2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture.
However, in java occupies 4 bytes of memory for both 32 and 64-bit architectures in
Java.

• Also, up gradation of OS, processor and changes in the core system resources can all be
the factors which may cause malfunction of program is handled by java.
Multi-threaded:
• Java runtime system contains tools to handles multiple tasks simultaneously.
• A thread is like a separate program, executing concurrently.
• We can write Java programs that deal with many tasks at once by defining
multiple threads.
• The main advantage of multi-threading is that it doesn't occupy memory for each
thread.
• It shares a common memory area. Threads are important for multi-media, Web
applications, etc.

Portable:
• Java is portable because it facilitates you to carry the Java bytecode to any
platform.
• It doesn't require any implementation.
High-performance:

• Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.

• It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed:

• Java is distributed because it facilitates users to create distributed applications in Java.

• RMI and EJB are used for creating distributed applications.

• This feature of Java makes us able to access files by calling the methods from any
machine on the internet.
Dynamic:

• Java is a dynamic language.

• It supports dynamic loading of classes. It means classes are loaded on demand.

• Java supports dynamic compilation and automatic memory management (garbage


collection).

• Java can use efficient functions available in C/C++.

• Installing new version of library automatically updates all programs


class classname
Class declaration:
{
data_type instance-variable1;
• Variables, defined within a class are
called instance variables. // ...
• Each object of the class contains its own data_type type instance-variableN;
copy of these variables. return_type methodname1(parameter-list)
{
// body of method
}
...
Return_type methodnameN(parameter-list)
{
// body of method
}
}
Creating Object using new Keyword:

• Using the new keyword is the most popular way to create an object or instance of
the class.

• When an instance of a class is created by using the new keyword, it allocates


memory for the newly created object and also returns the reference of that object.

• Syntax :

ClassName object_name = new ClassName();

• Example:

Student s1=new Student();


Introducing Methods:
• General form of a method:
return_type method_name(parameter-list)
{
// body of method
}

• Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.

• If the method has no parameters, then the parameter list will be empty.

• Form of the return statement:

return value;
Adding a Method to Class Returning a Value:

class Box
class Box
{
{
double width;
double width;
double height;
double height;
double depth;
double depth;
void volume()
double volume()
{
{
System.out.print("Volume is: ");
return width * height * depth;
System.out.println(width * height * depth); }
} }
}
Basic Structure of Java Programs:

• Documentation Section

• Package Statement

• Import Statements

• Interface Statement

• Class Definition

• Main Method Class

• Main Method Definition


Section Description
Documen • Comments are beneficial for the programmer because they help them
tation understand the code.
Section • These are optional, but suggest you use them because they are useful to
understand the operation of the program.

Package • A package is a group of classes that are defined by a name.


statement • If you want to declare many classes within one element, then that element is
package.
• It is an optional part of the program.

• It is declared as: package package_name;


• Here, the package is a keyword that tells the compiler that package has been
created with package_name.
Section Description

Import • To import java package into a class, import keyword is used.


statements
• Importing packages allows us to access built-in and user-defined packages
into your java source.
• Using packages means your class can refer to a classes that is in another
package directly using its name.
Example import calc.add; //import user-defined packages

import java.lang.*; //import built-in packages


Interface • Interfaces are like a class that includes a group of method declarations.
statement
• It's an optional section.

• Used to implement multiple inheritance.


Section Description

Class • A Java program may contain several class definitions.


Definition • Classes are the main and essential elements of any Java program.

Main • main method is starting point of the Java program.


Method • There may be many classes in a Java program, and only one class
Class defines the main method.
Example: Program to Print "Hello Java"

• Java code is case sensitive.


public class Hello
{ • The name of the class in Java (which
public static void main(String[] args) holds the main method) is the name of
{
the Java program, and the same name
System.out.println("Hello Java");
will be given to file.
}
} • So, the name of the class is "Hello" in
which the main method is, then file will
be named as "Hello.Java".
public class Hello • This creates a class called Hello.
• All class names must start with a capital letter.
• The public word means that it is accessible from any other classes.

/* • The compiler ignores comment block.


Comments • Comment can be used anywhere in the program to add info about
*/ program or code block, which will be helpful for developers to
understand the existing code in the future easily.

Braces • Two curly brackets {...} are used to group all the commands or
statements, so it is known that the commands belong to that class or
method.
public static void • When main method is declared public, it means that it can also
main be used by code outside of its class.
• The word static used when we want to access a method without
creating its object, so we call the main method, before creating
any class objects.
• The word void indicates that main method does not return a
value.
• main method is starting point for execution of Java program.
String[] args • It is an array where each element of it is a string, which
has been named as "args".
• If your Java program is run through the console, you can
pass input parameter, and main() method takes it as input.

System.out.println(); • This statement is used to print text on the screen as output.


• System is a predefined class.
• out is an object of the PrintWriter class defined in the
System.
• The method println prints the text on the screen with a
new line.
• All Java statement ends with a semicolon.
JVM (Java Virtual Machine):

• JVM enables your computer to run a Java program.

• Java compiler first compiles your Java code to bytecode.

• Then, JVM translates bytecode into native machine code (instructions that a computer's
CPU executes directly).
• Java is a platform-independent language because when you write Java code, it's
ultimately written for JVM but not your physical machine.
• JVM ​executes the Java bytecode which is platform-independent, so Java is platform-
independent.
Java Environment:

JRE (Java Runtime Environment):


• JRE is a software package provides Java class
libraries, Java Virtual Machine (JVM), and other
components required to run Java applications.
• JRE is the superset of JVM.

JDK((Java Development Kit):


• JDK is a software development kit required to
develop applications in Java.
• JDK also contains a number of development tools
(compilers, JavaDoc, Java Debugger, etc).

Relationship between JVM, JRE, and JDK.


Program is created in an
Phase 1 Editor Disk editor and stored on disk in
a file ending with .java.

Compiler creates bytecodes


Phase 2 Compiler Disk and stores them on disk in a
file ending with .class.

Primary
Memory
Phase 3 Class Loader Class loader
reads .class files
containing bytecodes
from disk and puts
those bytecodes in
Disk memory.
. ..
. .
.

Primary
Memory
Phase 4 Bytecode Verifier Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
restrictions.
. ..
. .
.

Primary
Memory Interpreter reads
Phase 5 Interpreter bytecodes and translates
them into a language that
the computer can
understand, possibly
storing data values as the
program executes.

. ..
. .
.
29
Java Tokens:

• A token is the smallest element of a program that is meaningful to the compiler. Tokens
can be classified as follows:

1. Keywords

2. Identifiers

3. Constants

4. Separators

5. Operators
Keywords:
• These are the pre-defined reserved words in java.
• Each keyword has a special meaning.
• They are always written in lower case.
• Java provides the following keywords:
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
11. do 12. double 13. else 14. extends 15. final
16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. Int 24. interface 25. long

26. native 27. new 28. Package 29. private 30. protected
31. public 32. return 33. Short 34. static 35. super
36. switch 37. synchronized 38. This 39. throw 40. throws

41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier:
• Java Identifiers are the user-defined names of variables, methods, classes, arrays,
packages, and interfaces.
• Rules while naming the identifiers such as:
✔ Identifiers must begin with a letter, dollar sign or underscore(no digits)
✔ Identifiers in Java are case sensitive.
✔ Java Identifiers can be of any length.
✔ Identifier name cannot contain white spaces.
✔ Most importantly, keywords can’t be used as identifiers in Java.
Valid Identifiers: $myvariable , _variable , variable , edu2019var
Invalid Identifiers: edu variable , Edu_identifier , &variable , 23identifier , switch

, var/edu , edureka's
Variables in Java:

• A variable is a name which stores value that can be changed.

Syntax to Declare variable: data_type variable_name;

Example: int num;

• Here num is a variable and int is a data type, which allows this num variable to hold integer values.

Variables naming convention:

• Variables naming cannot contain white spaces in it.

• Variable name can begin with special characters such as $ and _.

• Variable names are case sensitive in Java.

Types of variables:
1) Local variable 2) Static (or class) variable 3) Instance variable
The Scope and Lifetime of Variables:

• Scope of a variable refers to in which areas or sections of a program can the variable
be accessed.

• Lifetime of a variable refers to how long the variable stays alive in memory.

• General convention for a variable’s scope is, it is accessible only within the block in
which it is declared. A block begins with { and ends with }.

• Java variables are of three kinds

1.Instance variables

2.Class (or static) variables

3.Local variables
Instance variables and Class variables are declared inside class.
Instance variables are created when object is instantiated and
therefore they are associated with object. They take
different values for each object.
Class variables are global to class and belongs to entire set of
objects that class creates.
Only one memory location is created for each class variable.
Variables declared and used inside method are called local
variables.
They are not available outside the method definition.
Local variables can also be declared inside program blocks.
Program a block is begun with an opening curly brace and
ended by a closing curly brace.
A block defines a scope, which determines the lifetime of those
objects.
Instance Variables:
• A variable which is declared inside a class and outside all the methods and blocks
is an instance variable.
• Scope of an instance variable is throughout the class except in static methods.
• Lifetime of an instance variable is until the object stays in memory.
Class (static) Variables:
• A variable which is declared inside a class, outside all the blocks and is
marked static is known as a class variable.
• General scope of a class variable is throughout the class.
• Lifetime of a class variable is until the end of the program.
Local Variables:
• All other variables which are not instance and class variables are treated as local
variables including the parameters in a method.
• Scope of a local variable is within the block in which it is declared.
• Lifetime of a local variable is until the control leaves the block in which it is
declared.
// Example to Demonstrate Life Time. // Example to Demonstrate scope.
class LifeTime class Scope
{ {
public static void main(String args[]) public static void main(String args[])
{ { int x=10;
int x; if(x == 10)
for(x = 0; x < 3; x++) {
{ int y = 20;
int y = -1; System.out.println("x and y: " + x + " " + y);
System.out.println("y is: " + y); x = y * 2;
y = 100; }
System.out.println("y is now: " + y); // y = 100; // Error!
} System.out.println("x is " + x);
}
}
}
}
• Variables are created when their scope/block is entered, and destroyed when their

scope/block is left. Thus, the lifetime of a variable is confined to its scope.

• Therefore, variables declared within a method will not hold their values between

calls to that method.

• If a variable declaration includes an initializer, then that variable will be

reinitialized each time the block in which it is declared is entered.


Literal / Constants:

• Any constant value which can be assigned to the variable is called as


literal/constant.

• Literals are data used for representing fixed values.

• Literals available in Java are:

1. Integer-literal

2. Floating-literal

3. Boolean-literal

4. Character-literal

5. String-literal
Integer Literals:These are the whole numbers without any fractional part.
Rules of writing integer constants are:
1. It must have at least one digit and must not contain any decimal points.
2. Commas cannot appear in an integer constant.
3. It may contain either + or – sign.
4. Valid integer literals are: 56 , +8902 , -235 , 090 etc.
Types of integer literals:
5. Decimal (base 10) : eg. int decNumber = 34;

6. Binary (base 2) : eg. int binaryNumber = 0b10010;

7. Octal (base 8) : denoted in java by a leading 0. eg. int octalNumber = 027;


8. HexaDecimal (base 16): denoted by leading 0x or 0X.
Eg. int hexNumber = 0x2F; 44
Floating-point Literals:

• floating literals are having fractional parts.

• Valid floating literals are: 2.0 , +17.5 , -13.0 , -0.000875 etc.

• Floating point literals are by default of type double.

• To specify a float literal, we must append an F or f to the constant.


double myDouble = 3.4;

float myFloat = 3.4F;


Character Literals:

• A literal character is single character enclosed inside a pair of single quotes.


•For example,

char letter = 'a';

•Here, a is the character literal.

• We can also use escape sequences as character literals.

• For example, \b (backspace), \t (tab), \n (new line), etc.


Boolean Literals:

• Represents two values – true and false.

• True is equal 1 and false is equal to 0.

• They can be assigned to variable declared as Boolean

• Denoted by keyword boolean

• Uses only one bit for storage

• For example,
• boolean flag1 = false;
• boolean flag2 = true;
-Here, false and true are two boolean literals.
String literals

• A sequence of characters between a pair of double quotes.

• In java string must begin and end on the same line.


• String str1 = "Java ";
• String str2 = " Programming ";
• Here, Java and Programming are two string literals.
Symbolic Constants:
• symbolic constants are named constants

• Final variables serve as symbolic constants.

Syntax : final data_type symbolic_name= value;

Example: final float PI =3.14159;

• They are constants because of the 'final' keywords.

• They cannot be reassigned a new value after being declared as final

• A NON symbolic constant is like the value of '2' in expression


int foo = 2 * 3

• Symbolic names are written in capitals (only convention not a rule)


Separators / Punctuators: There are nine separators in Java, are as follows:

1 Square Brackets [] • Used to define array elements. A pair of square brackets


represents the single-dimensional array.
2 Parentheses () • It is used to call the functions and parsing the parameters.
3 Curly Braces {} • The curly braces denote the starting and ending of a code block.
4 Comma (,) • It is used to separate two values, statements, and parameters.
5 Assignment Operator • It is used to assign a variable and constant.
(=)
6 Semicolon (;) • Represents end of the statements. It separates the two
statements.
7 Period (.) • It separates the package name form the sub-packages and class.
• It also separates a variable or method from a reference variable.
8 Single Line • It begins with a pair of forwarding slashes (//).
Comments
9 Multiline Comments • It begins with /* and continues until it founds */.
Operators in Java:

Operator Symbols

Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Relational ==, != , < , >, <= , >=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~
Shift << , >> , >>>
public class IncDecOperators
public class ArithmeticOperators
{
{
public static void main(String[] args)
public static void main(String[] args)
{
{
int a = 20, b = 10, c = 0, d = 20;
int a = 20, b = 10;
String x = "Thank", y = "You"; boolean condition = true;
System.out.println("a + b = "+(a + b)); c = ++a;
System.out.println("a - b = "+(a - b)); System.out.println("Value of c (++a) = " + c);
System.out.println("x + y = "+x + y); c = b++;
System.out.println("a * b = "+(a * b)); System.out.println("Value of c (b++) = " +
c);
System.out.println("a / b = "+(a / b));
c = --d;
System.out.println("a % b = "+(a % b));
System.out.println("Value of c (--d) = " + c);
}
}
}
}
Assignment Operator : public class ArithmeticShortHandOperators
{
• ‘=’ Assignment operator is used to public static void main(String[] args)
assign RHS value to LHS variable. {
int a = 20, b = 10, e = 10, f = 4;
• It has a right to left associativity.
a-=1; //a = a - 1;
Syntax: b+=1; //b = b + 1;
data_type variable = value; e/=2; //e = e / 2;
Example: f*=2; //f = f * 2;
int age= 5; System.out.println("a,b,e,f= " + a + "," +
b + "," + e + "," + f);
• For example, instead of a = a+5 , we can
}
write a += 5. }

• Likewise : += , -= , *= , /= , %=
Logical operators: class Main
{
Operator Example Meaning public static void main(String[] args)
true only if both {
&&
(Logical exp1 && exp2
expression1 and System.out.println((5 > 3) && (8 > 5));
expression2 are
AND) System.out.println((5 > 3) && (8 < 5));
true
System.out.println((5 < 3) || (8 > 5));
true if either
|| (Logical
OR)
exp1 || exp2 expression1 or System.out.println((5 > 3) || (8 < 5));
expression2 is true
System.out.println((5 < 3) || (8 < 5));
! (Logical true if expression is System.out.println(!(5 == 3));
!exp
NOT) false and vice versa
System.out.println(!(5 > 3));
}
}
public class RelationalOperators
Relational Operators : {
1.!= , Not Equal to public static void main(String[] args)
2.< , less than { int a = 20, b = 10;
3.== , Equal to String x = "Thank", y = "Thank";
4.<= , less than or equal to int ar[] = { 1, 2, 3 }; int br[] = { 1, 2, 3 };
5.> , Greater than boolean condition = true;
6.>= , System.out.println("a == b :" + (a == b));
Greater than or equal to System.out.println("a < b :" + (a < b));
System.out.println("a <= b :" + (a <= b));
System.out.println("a > b :" + (a > b));
System.out.println("a >= b :" + (a >= b));
System.out.println("a != b :" + (a != b));
System.out.println("x == y : " + (x == y));
System.out.println("ar == br : " + (ar == br));
System.out.println("condition==true :" + (condition == true));
}
}
Ternary operator :
• Ternary operator is a shorthand public class operators
version of if-else statement. It has {
three operands and hence the name public static void main(String[] args)
ternary. {
int a = 20, b = 10, c = 30, result;
• General form- result = ((a > b) ? (a > c) ? a :c : (b > c) ? b : c);
System.out.println("Max of three numbers =
condition ? if true : if false
"+result);
}
• The above statement means that if }
the condition evaluates to true,
then execute the statements after
the ‘?’ else execute the statements
after the ‘:’.
Bitwise operators in Java: 2. Bitwise AND (&) :
• Used to perform manipulation on • It returns bit by bit AND of input values.
bits of a number. • For example: a=5= 0101, b = 7= 0111
1. Bitwise OR (|): • Bitwise AND Operation of 5 and 7
• It returns bit by bit OR of inputs. 0101
• If either of the bits is 1, it gives 1, & 0111
else it gives 0.
___________
• For example,
0101 = 5 (In decimal)
a = 5 = 0101, b = 7 = 00011001
Bitwise OR Operation of 5 and 7
0101
| 0111
________________________________________________________________________________

0111 = 7 (In decimal)


3. Bitwise XOR (^) : 4. Bitwise Complement (~):
• This operator is binary operator, • This operator is unary operator, denoted by
denoted by ‘^’. ‘~’.
• It returns bit by bit XOR of input • It returns the one’s compliment
values, i.e, if corresponding bits are representation of the input value, i.e, with
different, it gives 1, else it gives 0. all bits inversed, means it makes every 0 to
1, and every 1 to 0.
• For Ex: a =5=0101,b=7= 0111
• For example,
a = 5 = 0101
0101
• Bitwise Compliment Operation of 5
^ 0111
~ 0101 =>1010 = 10 (In decimal)
___________

0010 = 2 (In decimal)


public class operators
{
public static void main(String[] args)
{
int a = 5;
int b = 7;

System.out.println("a&b = "+ (a & b)); // 0101 & 0111=0101 = 5

System.out.println("a|b = "+ (a | b)); // 0101 | 0111=0111 = 7

System.out.println("a^b = "+ (a ^ b)); // 0101 ^ 0111=0010 = 2

System.out.println("~a = "+ ~a); // ~0101=1010 , will give 2’C of 1010=-6


}
}
class Demo
Shift Operators:
{
• These operators are used to shift the bits of a number
public static void main(String Args[])
left or right.
{
Bitwise Left shift operator (<<) :
int i=5;
• Shifts the bits of the number to the left and fills 0. System.out.println(i<<2);
• It results to multiplying the number with some (no. of i=-5;
bits shifted) power of two. System.out.println(i<<2);
For example,
i=5;
a = 5 = 0000 0101 a << 1 = 0000 1010 = 10
System.out.println(i>>2);
Bitwise Right shift Operator (>>): i=-5;
• The operator ‘>>’ uses the sign bit (left most bit) to fill System.out.println(i>>2);
the trailing positions after shift. i=5;
• If the number is negative, then 1 is used as a filler and System.out.println(i>>>2);
if the number is positive, then 0 is used as a filler. i=-5;
• For example: System.out.println(i>>>2);
a = 5 = 0000 0101 a >> 1 = 0000 0010 = 10 }
32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
i=5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
i<<2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 5<<2=20
i=-5 1C 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0
1 1
i=-5 2C 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1
i<<2 i=-5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0
~i 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1
1 1 i=-5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 i<<2=-20
sign retain
i>>2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 i=1
i>>2 i=-5
i=-5 2C 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0
1C 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
1
2C of -5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 i=-2
sign retain
i=5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
i>>>2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 i=1
i=-5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1
i>>>2 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1073741822
new operator in Java:
Creating objects of a class is a two-step process :
1. Declaration : Declare a reference variable that can refer to an object.
Syntax : class-name var-name;
Example : Box mybox ;
• Here, mybox is reference variable pointing to nothing.
2. Instantiation and Initialization : Acquire physical copy of the object and assign to
reference variable.
Syntax : var-name = new class-name();
Example : mybox = new Box();
• The new operator instantiates a class by dynamically allocating memory for a new
object and returning a reference which will be stored variable.
Effects of declaration of a class variable, instantiation of a class and initialization of
an object of class can be together illustrated as follows :
Java instanceof Operator:
• The instanceof operator in Java is used to check whether an object is an instance of a
particular class or not.
class Main
{ Output:
public static void main(String[] args) name is an instance of String: true
obj is an instance of Main: true
{
String name = "Tpoly";
boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);
Main obj = new Main();
boolean result2 = obj instanceof Main;
System.out.println("obj is an instance of Main: " + result2);
}
}
dot operator in Java: public class Sample
{
The (.) operator is also known as void display()
member operator it is used to access {
int i = 20;
the member of a package or a class.
System.out.println(i);
}
public static void main(String args[])
{
Sample s = new Sample();
s.display();
}
}
OPERATOR PRECEDENCE:
• It specifying the order in which the operators in an expression are evaluated in several
operators.

• For example, multiplication and division have a higher precedence than addition and
subtraction.

• Precedence rules can be overridden by explicit parentheses.


Precedence order:
• When two operators share an operand the operator with the higher precedence goes
first.
For example:
1 + 2 * 3 is treated as 1 + (2 * 3)

1 * 2 + 3 is treated as (1 * 2) + 3
Associativity:

• When an expression has two operators with the same precedence, the expression is
evaluated according to its associativity.
For example:
• x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value
17, since the = operator has right-to-left associativity (and an assignment statement
evaluates to the value on the right hand side).

• On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right
associativity.

• Some operators are not associative:

• for example, the expressions (x <= y <= z) and x++-- are invalid.
Level Operator Description Associativity
[] access array element
16 . access object member left to right
() parentheses
++ unary post-increment
15 not associative
-- unary post-decrement
++ unary pre-increment
-- unary pre-decrement
+ unary plus
14 right to left
- unary minus
! unary logical NOT
~ unary bitwise NOT
() cast
13 right to left
new object creation
12 */% multiplicative left to right
+- additive
11 left to right
+ string concatenation
Level Operator Description Associativity
<< >>
10 shift left to right
>>>
< <=
9 > >= relational not associative
instanceof
==
8 equality left to right
!=
7 & bitwise AND left to right
6 ^ bitwise XOR left to right
5 | bitwise OR left to right
4 && logical AND left to right
3 || logical OR left to right
2 ?: ternary right to left
= += -=
*= /= %=
1 assignment right to left
&= ^= |=
<<= >>= >>>=
Data Types in Java:
byte:
• Smallest integer type.
• This is an 8-bit (1 byte) signed integer.
• Its range is from -128 to 127.
• Default value is 0.
• Declared using the byte
• For example: byte b, c;
short:
• short data type is a 16-bit signed integer.
• Its range is from -32,768 to 32,767.
• Default value is 0.
• Declared using the short
• For example: short s;
int:

• This is the most commonly used data type.

• Int data type is a 32-bit signed integer.

• Minimum value is - 2,147,483,648.(-2^31)

• Maximum value is 2,147,483,647(inclusive).(2^31 -1)

• int is generally used as the default data type for integral values unless there is a concern
about memory.

• The default value is 0.

• Declared using the int

• Example : int a = 100000; int b = -200000;


long:

• is useful for those occasions where an int type is not large enough to hold the desired
value.

• Long data type is a 64-bit signed integer.

• Minimum value is -9,223,372,036,854,775,808.(-2^63)

• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)

• This type is used when a wider range than int is needed.

• Default value is 0L.

• Declared using the long

• For example: long distance;


float:
• float is a 32-bit floating point number.
• Its range is from 1.4e-045 to 3.4e+038.
• Default value is 0.0f.
• Declared using the float
• For example: float pi;
double:
• double is a 64-bit floating point number.
• Its range is from 4.9e-324 to 1.8e+308.
• Default value is 0.0d.
• Declared using the double
• For example: double area;
boolean:
• Boolean represents one bit of information for logical values.
• It can have only one of the two values, true or false.
• Default value is false.
• Declared using the boolean
• For example: boolean b;
char:
• char is a single 16-bit Unicode character.
• It is used to store any characters.
• Its range is from 0 (or ‘\u0000’) to 65,536 (or ‘\uffff’).
• There are no negative characters.
• Declared using the char
• For example: char letterb=’B’;
Type Conversion and Casting:

• The process of converting a value from one data type to another is known as type
conversion in Java.

• If the two types are compatible, then Java will perform the conversion automatically
called as Implicit type casting.

• For example, it is always possible to assign an int value to a long variable.

• But, not all type conversions are implicitly allowed, For example, there is no automatic
conversion defined from double to byte.

• The conversion between incompatible types can be done using casting, called as
explicit type casting.
Implicit type casting:
• When one type of data is assigned to another type of variable, an automatic/ Implicit
type conversion will take place if the following two conditions are met:

1. The two types are compatible.

2. The destination type is larger than the source type.

• When these two conditions are met, a widening conversion takes place, guarantees
no loss of information.

• For example, the int type is always large enough to hold all valid byte values, so no
explicit cast statement is required.
Explicit type casting:
• If a double value is assigned to int variable, this conversion cannot be performed
automatically because an int is smaller than a double.

• In this case, we must use the explicit type casting to create a conversion between two
incompatible types. This kind of conversion is also known as narrowing.

• The conversion of a higher data type into a lower data type is called narrowing.

• As this conversion is performed by the programmer, not by the compiler automatically,


therefore, it is also called explicit type casting in java.
Syntax to cast:
(target-type) value;
• Here, target-type specifies the desired type to convert the specified value to.

Example:
int a;
byte b;
b = (byte) a;
• Above casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the)
byte’s range.
class ExplicitTypeConversion {
public static void main(String args[])
{
byte b; int i = 257; double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println(i + "--->" + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println( d + "---> " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println(d + "---> " + b);
}
}
Automatic Type Promotion in Expressions:
• Consider expression:
byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;

• The result of term a * b easily exceeds the range of either of its byte operands.

• To handle this kind of problem, Java automatically promotes each byte, short, or char
operand to int when evaluating an expression.

• This means that the sub expression a*b is performed using integers, not bytes.

• Thus, 2,000, the result of the intermediate expression, 50 * 40, is legal even though a
and b are both specified as type byte.
• Consider code:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte
variable.
• However, because the operands were automatically promoted to int when the
expression was evaluated, the result has also been promoted to int.
• Thus, the result of the expression is now of type int, which cannot be assigned to a
byte without the use of a cast. This is true even if, as in this particular case, the value
being assigned would still fit in the target type.
• In cases where you understand the consequences of overflow, you should use an
explicit cast, such as
byte b = 50;
b = (byte)(b * 2);//which yields the correct value of 100.
The Type Promotion Rules:

• Java defines several type promotion rules that apply to expressions.

1) All byte, short, and char values are promoted to int.

2) If one operand is a long, the whole expression is promoted to long.

3) If one operand is a float, the entire expression is promoted to float.

4) If one operand is a double, the entire expression is promoted to double.


Decision making statements in Java:

1) if statements

2) If else statement

3) Else if ladder

4) Nested if else

5) switch statements
if Statement:
public class Test
If condition is true body statements executes. {
public static void main(String args[])
Syntax: {
if(Boolean_expression) int x = 10;
{ if( x < 20 )
{
//Statements
System.out.print("This is if statement");
} }
}
}
This would produce following result:
This is if statement
if...else Statement: public class Test
Syntax: {
if(Boolean_expression) public static void main(String args[])
{
{
int x = 30;
//True side statements
if( x < 20 )
}
System.out.print("This is if statement");
else
{ else
//False side statements System.out.print("This is else statement");
} }
}
else-if ladder : public class Test
Syntax: {
if(Boolean_expression 1) public static void main(String args[])
{ {
//statements int x = 30;
}
if( x == 10 )
else if(Boolean_expression 2)
System.out.print("Value of X is 10");
{
else if( x == 20 )
//statements
} System.out.print("Value of X is 20");
else if(Boolean_expression 3) else if( x == 30 )
{ System.out.print("Value of X is 30");
//statements else
} System.out.print("This is else statement");
else }
{ }
//statements
Nested if...else : Example:
Syntax:
if(Boolean_expression 1) public class Test
{ {
if(Boolean_expression) public static void main(String args[])
{ {
//Statements int x = 30, y = 10;
} if( x == 30 )
else {
{ if( y == 10 )
//Statements {
} System.out.print("X = 30 and Y = 10");
} }
else }
{ }
if(Boolean_expression) }
{
public class Test {
The switch Statement: It tests variable for equality against a
list of values. Each value is called a case, and the variable is public static void main(String args[]) {
checked for each case. char grade =‘A’;
Syntax: switch(grade) {
switch(expression) case 'A' : System.out.println("Excellent!");
break;
{
case 'B' : System.out.println(“Very Good!!");
case value :
//Statements; break;
break; case 'C' : System.out.println("Well done");
case value : break;
case 'D' : System.out.println("You passed");
//Statements;
break;
break;
case 'F' : System.out.println("Better try again");
----
break;
default : //Optional default :
//Statements; System.out.println("Invalid grade"); break;
break; //optional }
} System.out.println("Your grade is " + grade);
Loops in java: Example:
1) For public class Test
2) While {
3) Do-while public static void main(String args[])
1) For Loop: {
Syntax: for(int x = 10; x < 20; x = x+1)
for(initialization; Boolean_expression; {
update statement) System.out.println("value of x : " + x );
{ }
//Statements }
} }
Enhanced for / for each loop: public class Test
• for-each loop is used to iterate through {
arrays. public static void main(String args[])
Sytnax {
for(dataType item : array) int [] numbers = {10, 20, 30, 40, 50};
{ for(int x : numbers )
//statements System.out.println( x+”,” );
}
Here, String [] names ={“Ankit", “Rahul",
• array - an array “Sam”};
• item - each item of array is assigned to for( String name : names )
this variable System.out.print( name+”,” );
• dataType - the data type of the }
array/collection
}
The While Loop: public class Test
Syntax: {
initialisation public static void main(String args[])
while(Boolean_expression) {
{ int x = 10;
//Statements while( x < 20 )
incr/decr statement {
} System.out.println("value of x : " + x );
x++;
}
}
}
The do...while Loop: Example:
public class Test
Syntax: {
Initilisation; public static void main(String args[])
do {
{ int x = 10;
//Statements do{
Incr/decr statement System.out.println("value of x : " + x );
} while(Boolean_expression); x++;
}while( x < 20 );
}
}
Jump statements in java : public class Test
• Java supports three jump statements: {
1) break 2)continue 3)return public static void main(String args[])
• These statements transfer control to another part {
of your program.
int [] numbers = {10, 20, 30, 40, 50};
The break statement:
for(int x : numbers )
• Used to exit a loop or switch case. {
• The break keyword must be used inside any loop if( x == 30 )
break;
or a switch statement.
System.out.print( x );
• The break will stop the execution of loop and }
start executing the next line of code after the }
block. }

Syntax: break;
Continue statement: public class Test
{
• The continue causes the loop to
public static void main(String args[])
immediately jump to the next iteration of {
the loop. int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers )
• In a for loop, the continue keyword causes
{
flow of control to immediately jump to the
if( x == 30 )
update statement. continue;
• In a while loop or do/while loop, flow of System.out.println( x );
}
control immediately jumps to the Boolean
}
expression.
}
• Syntax: continue;
The return statement

• The return statement is used to return a value from a method.

• It causes program control to transfer back to the caller of the method.

• It is used to exit from the method.

• It is not allowed to use return keyword in void method.

• The value passed with return keyword must match with return type of the method.
Labelled loop:
• In nested loop, if break executes in inner loop, compiler will jump out from inner loop
and continue the outer loop again.
• What if we need to jump out from the outer loop using break statement given inside
inner loop?
• The answer is, we should define label along with colon(:) sign before loop.
• Syntax of Labelled loop
class WithoutLabelledLoop class WithLabelledLoop
{ {
public static void main(String args[]) public static void main(String args[])
{ int i,j; { int i,j;
for(i=1;i<=5;i++) loop1: for(i=1;i<=5;i++)
{ {
System.out.println(); System.out.println();
for(j=1;j<=10;j++) loop2: for(j=1;j<=10;j++)
{ {
System.out.print(j + " "); System.out.print(j + " ");
if(j==5) if(j==5)
break; //Statement 1 break loop1; //Statement 1
} }
} }
} }
} }
public class MathFunctions
{
public static void main(String[] args)
{
double x = 4; double y = 2; int z=-10;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Minimum number of x and y is: " +Math.min(x, y));
System.out.println("Absolute of x is: " +Math.abs(z));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("exp of x is: " +Math.exp(x));
System.out.println("exp of x is: " +Math.round(10.s));
}
}

You might also like