Unit - 1
Java Language Basics
Java is a robust, cross platform high level language. Java is based on object oriented programming which means it design using the concepts of object and classes.
Whenever a programmer writes a code in Java, that code can be available to run on any platform like LINUX, Windows or Mac OS. Also, this language is free to access for all user.
Most of the syntax in Java is derived from C and C++ programming language but eliminates the concept of pointers.
Why Java?
Java was intended to be not difficult to utilize and is hence simple to compose, compile, troubleshoot, and learn in comparison to other programming language.
Since Java is object-oriented, this permits you to make flexible program and reusable code
Probably the main motivation why Java is so well known is one of its feature platforms independent.
Programs written in Java can run on numerous computer; as long as the computer has a Java Runtime Environment (JRE) installed, which allows a Java program to run on it.
Almost all kinds of computers are flexible with a JRE including computers running on Windows, Macintosh computers, Unix or Linux computers, and huge mainframe server computers, including mobile phones.
Since Java is from such a long time, probably the greatest organizations in the world are constructed utilizing the language such as Numerous banks, retailers, insurance agencies, etc.
History behind Java
Now a day’s Java is one such language which is used worldwide including internet, mobiles, games, e-commerce etc.
Let’s have a look at the history of Java and see how it comes so far:
- In June 1991, the first project written in Java is initiated by a team of three members having James Gosling, Mike Sheridan and Patrick Naughton. This team of sun engineers become famous as Green Team.
- The initial purpose of using Java was for small, embedded systems such as TV set-top boxes.
- At first it was referred as Green talk by James Gosling and the file extension for it was decided is .gt.
- Then James Gosling referred it as Oak which was developed as a part of Green project.
- Since Oak was already a trademark used by Oak Technologies, so in 1995 it was renamed as Java.
- Before selecting the name Java the team had huge discussion among names suggested like dynamic, revolutionary, silk, jolt, DNA etc. Team wants to select such a name which reflects the nature of technology. So finally the team members preferred Java over other names.
- The first public implementation of Java was made in 1995 as Java 1.0 by Sun. It is based on the concept of Write once and Run Anywhere on any platforms.
- In 2006, Sun finally released Java’s some code as free and open source software Under GNU General Public License (GPL).
- And finally, in 2007 Sun declared Java’s all core code free and open source so that anyone can use it without any restrictions.
Different versions of Java
- JDK Alpha and Beta: The first version which was released in 1995 as Java Alpha and Beta was highly unstable because of its APIs and ABIs.
- JDK 1.0: The first stable version came on 23 January 1996 JDK 1.0.2 also known as Java 1.
- JDK 1.1: This version was released on 19 February 1997 which includes new features like AWT event model, addition of inner classes, JavaBeans, JDBC, RMI, reflection and JIT.
- J2SE 1.2: This version release on 8 December 1998 with the codename playground. This version a signification release by Java as its size was three times of the Java platform. This version consists of 1520 classes in 59 packages. Some new features added like strictfp keyword, Swing graphical API, Java plug-in, Java IDl and collections.
- J2SE 1.3: This version was one of the famous version came on 8 May 2000 with codename Kestrel. The main changes done in this version were inclusion of HotSpot JVM, modified RMI compatible with COBRA, Java Naming and Directory Interface (JNDI) libraries, Java Platform Debugger Architecture (JPDA) and Java Sound.
- J2SE 1.4: This version was the first version to release under Java Community Process as JSR on 6 February 2002. The major changes in this version include: addition of assert keyword and library improvement (such as exception chaining, IPv6 support, Non-blocking I/O etc).
- J2SE 5.0: This version was initially named as 1.5 but further changed to 5.0 to show the maturity, stability, scalability and security. This version was released on 30 September 2004 with code name tiger. New language features that were added like generics, metadata, autoboxing, enumerations, Varags, improved semantics and static imports.
- Java SE 6: Released on 11 December 2006 with codename mustang. Sun released this version as Java SE instead of J2SE. Some of the major changes include in this version were scripting language support, JDBC 4.0 support Java compiler API, support for Pluggable annotations etc.
- Java SE 7: This update with codename dolphin was released on 7 July 2011. Major additions in Java 7 were JVM support for dynamic languages, compressed 64-bit pointers, concurrency utilities under JSR, upstream updates to XML, java deployment rule sets.
- Java SE 8: This version was released on 18 March 2014 with codename spider. Some of the major changes that were done in Java SE 8 are support for lambda expression, JavaScript embed into applications, repeating annotations, launching of JavaFX applications and permanent generation removal.
- Java SE 9: The release of this version was delayed many time and finally released on 21 September 2017. This version provides improved support to native code integration, multi-gigabyte heaps, garbage collector and self tuning JVM.
- Java SE 10: Java SE 10 was released on 20 March 2018. This version was released with aim to remove primitive data types and support to 64 bit addressable arrays with some additional new features. These features were local variable type inference, application class data sharing, parallel full GC for GI, root certificates and many more.
- Java SE 11: This version also known as JDK 11 was released on 25 September 2018. Still its bug fixes are going on.
- Java SE 12: This was version was released 19 March 2019 with some fewer changes.
Features of Java
- Object Oriented: Java is a complete object oriented language. This means that everything in Java revolves around the use of Objects.
- Secure: Java is a very secure language; one of the main reasons is the lack of pointers. Virus free software’s can be developed using Java programming constructs.
- Robust: Java is a very robust language because of features like automatic garbage collection, memory management, exception handling, etc.
- Portable: One of the very important features of Java is that can be used on any platform without any problems. This means that it allows you to run the Java Bytecode on any platform.
- Simple: Java is a simple language because of its ease of use and less complicated features.
- Platform Independent: Java is a ‘write’ once, ‘run’ anywhere language, which means that once written, it has the capability to be executed on any machine that has Java Runtime Environment (JRE).
JVM (Java Virtual Machine) is a program that gives us the flexibility to execute Java programs. It provides a runtime environment to execute the Java code or applications.
This is the reason why Java is said to platform independent language as it requires JVM on the system it runs its Java code.
JVM is also used to execute programs of other languages that are compiled to Bytecode.
JVM can also be describe as:
- A specification where JVM working is pre defined.
- An implementation like JRE (Java Runtime Environment) is required.
- Runtime Instance means wherever a program is run on command prompt using java command, an instance of JVM is created.
Significance of JVM
JVM is used for two primary functions
- It allows Java programs to use the concept of “Write Once and Run Anywhere”.
- It is utilized to manage and optimize memory usage for programs.
Architecture of JVM
Java applications require a run-time engine which is provided by JVM. The main method of Java program is called by JVM. JVM is a subsystem of JRE (Java Runtime Environment).
Let’s see the internal architecture of JVM as shown in the figure below:
- Class Loader: This part is used to load class files. There are three major functions of class loader as Loading, Linking and Initialization.
- Method Area: Structure of class like metadata, the constant runtime pool, and the code for methods are stored method area.
- Heap: Heap is the memory where all the objects, instance variables and arrays are stored. This is a shared memory which is accessed by multiple threads.
- JVM Language Stacks: These hold the local data variables and their results. Each thread has their own JVM stack used to store data.
- PC Registers: The currently running IVM instructions are stored in PC Registers. In Java, every thread has its their own PC register.
- Native Method Stacks: It hold the instruction of native code depending on their native library.
- Execution Engine: This engine is used to test the software, hardware or complete system. It doesn’t contain any information about the tested product.
- Native Method Interface: It is a programming interface. It allows Java code to call by libraries and native applications.
- Native Method Libraries: It consists of native libraries which are required by execution engine.
The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
The Java Development Kit (JDK) is a cross-platform software development environment that includes a set of tools and libraries for creating Java-based applications and applets. Along with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment), it is a key package used in Java (Java Runtime Environment).
Beginners frequently confuse JRE and JDK; nevertheless, if all you want to do is launch Java programmes on your machine, you may do so with ease using Java Runtime Environment. However, if you want to create a Java-based software programme, you'll probably need some extra tools, such as JDK, in addition to JRE.
JDK is an implementation of any of Oracle Corporation's Java Platforms, as listed below:
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform
To finish the creation of a Java application, the JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and so on.
Fig: JDK
Components of JDK in Java
The following is a list of the JDK's core components in Java.
● java - In older SUN Java, it serves as a deployment launcher. It interprets the source code compiled by the javac compiler after loading the class files.
● javac - The java compiler is used to transform the source code to bytecode, as specified by javac.
● javadoc - The javadoc tool creates documentation for comments contributed to source code.
● jar - The jar aids in the management of jar files in the package library by the archives.
● jps - Java Virtual Machine Process Status Tool is abbreviated as jps. It keeps track of the active JVMs for the current programme.
● appletviewer - The appletviewer is a programme that allows you to run and debug Java applets without using the internet.
● idlj - An IDL-to-Java compiler converts a Java IDL file into Java bindings.
● javap - The javap performs the function of a file disassembler.
● JConsole - JConsole is a Java management and monitoring application.
● javah - The javah is a stub-generator, and native methods are written with C-Header.
● javaws - For JNLP apps, javaws serves as a Web Start launcher.
● jhat - The jhat is a tool for heap analysis.
● jmc - The abbreviation jmc stands for Java Mission Control.
Why JDK used?
The Java Development Kit includes a number of tools as well as knowledge on Java development. Downloading JDK software and blending it with the classpath is all it takes to deploy Java software. After downloading and installing JDK, the only method to run the software is to select the correct version of Java. Although Java 8 is the most widely used version, Java 10 is the most recent version that is also available online.
JDK is a collection of directories that are used to implement the Java platform standard, including class libraries and the compiler. It's also referred to as the JRE's superset.
Key takeaway
The term JDK stands for Java Development Kit. The Java Development Kit (JDK) is a software development environment for creating Java programmes and applets. It is a real thing. It includes JRE as well as developer tools.
Java is an object oriented programming language, so the complete program must be written inside a class.
Let’s consider an example
Class FirstProgram
{
Public static void main(String[] args)
{
System.out.println(“My first program”);
}
}
Save the above file as FirstProgram.java
Prerequisites Before start writing a java program
Before writing java program one must make sure that following software or applications are properly installed.
- First of all, download JDK and install it.
- Set path of the jdk/bin directory.
- Create the Java program.
- Compile and run the program.
Besides this learning Java is easy doesn’t require any previous knowledge of other programming language but required some logics for writing programs.
The syntax of writing a Java program is similar to that of C, so if you know C language little bit then it will be easy for you to write Java Program.
Also, if you have any idea of C++ then it will easy to understand the concept of object oriented programming which in turn helps to understand Java better.
Writing the program
To write a program, first of all open the notepad by following the sequence start menu -> All Programs -> Accessories -> Notepad and then write the below code.
Class FirstProgram
{
Public static void main(String[] args)
{
System.out.println(“My first program”);
}
}
After writing the code save the file as FirstProgram.java.
Different ways to write a Java program
- Sequence of the modifiers doesn’t matter, prototype of method will be same.
Static public void main(String args[])
2. The string array can be written in many ways all have the same meaning.
Public static void main(String[] args)
Public static void main(String []args)
Public static void main(String args[])
3. By using three ellipses we can provide var-args to the main().
Public static void main(String...args)
4. Placing a semicolon at the end of class is not necessary its optional.
Class FirstProgram
{
Static public void main(String...args)
{
System.out.println(“My first program”);
}
};
Compiling the program
Compiling a Java program is easy. Given are the steps to compile and run a program.
Step 1: To compile a Java program you need to open command prompt by following steps start menu -> All Programs -> Accessories -> command prompt.
Step 2: Next set the directory path where you saved your Java program. Let us consider my current directory is c:\dis. Following needs to be done to change the directory.
C:\> cd dis (press enter key)
Step 3: Compile the program by running following command.
C:\dis> javac FirstProgram.java (press enter key)
This step will inform the compiler to compile the program. The compiler will look for any error, if there is no error it will tell you to perform next step.
After successful compilation the system will generate a FirstProgram.class file in the same directory.
How Java program compiles?
After successful compilation, the Java compiler will convert the java source code into machine independent code known as bytecode.
This bytecode file will be stored with the extension .class in the same directory where your program is saved.
Executing the program
Now to run the program as shown below
C:\dis> java FirstProgram
You will be able to see the desired output on the command prompt.
How Java program executes?
The compiler will generate the class files which are machine independent or OS, which allows them to execute or run on any system.
At the time of execution, the main class file is passed to JVM (Java Virtual Machine) which the goes through following stages:
- Classloader: It is a sub part of JVM which is used to load class files.
- Bytecode Verifier: It checks part of code which contain access verifier to see any illegal access to the code.
- Interpreter: It read the Bytecode in stream and then run the instructions.
We have already seen how to write, compile and run program in Java.
Moving a step further let us use an example having comments in it.
Class SecondProgram
{
/* This is my second java program.
* This is an example of multi-line comments.
*/
public static void main(String []args) {
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Like any other programming language Java also uses the concept of comments to explain the Java code and make it more understandable. All characters written inside a comment is completely ignored by Java compiler.
Comments in Java are of two types:
- Single-line comments: It either start with two forward slashes (//) or (/* */). These are used for short comments as shown in above example.
- Multi-line comments: It start with /* and ends with */ in multiple line.
Understanding every term of the program
Let us know all the terms used in the above program.
- Class: Classes in Java is declared using the keyword class.
- Public: This keyword is an access specifier which represent that this function is visible to everyone.
- Static: This keyword is used to make a function static. Benefit of making a static function is that there is no requirement to create an object to call that function. JVM execute the main() function that is why it is declare static.
- Void: Represent the return type of method. It doesn’t return any value.
- Main: All the code resides inside the main method. The compilation of the program starts from here only. If in case you forgot to write main method then the system gives compilation error.
- String[] args or String args[]: This keyword show an array with data type as String and name as args. It is used for command line argument.
- System.out.println: This is used to print statement on console.
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword | Description |
Try | The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. |
Catch | The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. |
Finally | The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not. |
Throw | The "throw" keyword is used to throw an exception. |
Throws | The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature. |
A) try block:
a) Syntax of try block with catch block:
Try {
//Block of statement}
Catch(Exception Handler class)
{
}
b) Syntax of try block with finally block:
Try {
//Block of statement}
Finally {
}
c) Syntax of try block with catchand finally block:
Try {
//Block of statement}
Catch(Exception Handler class)
{
} finally{
}
B) Catch block:
a) Syntax of try block with catch block:
Try {
//Block of statement}
Catch(Exception Handler class)
{
}
b) Multiple catch block:
Syntax of try block with catch block:
Try {
//Block of statement}
Catch(Exception Handlersub class)
{
}catch(Exception Handler super class){
}
C) Nested try block:
Syntax of nested try block
Try{ // block of statement
try{
// block of statement
}
Catch(Exception Handler class)
{
}
Catch(Exception Handler class)
{
}
D) Finally:
a) Syntax of finally without catch
Try{
//block of statement
}
Finally {
}
b) Syntax of finally with catch
try {
//Block of statement}
Catch(Exception Handler class)
{
} finally{
}
E) throw:
Syntax:
Throw exception_object;
F) throws:
Syntax:
MethodName () throws comma separated list of exceptionClassNames{}
Difference between throw and throws
Throw keyword | Throws keyword |
|
|
Difference between final, finally and finalize
- The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality.
- The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Key | Final | Finally | Finalize |
Definition | Final is the keyword and access modifier which is used to apply restrictions on a class, method or variable. | Finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. | Finalize is the method in Java which is used to perform clean up processing just before object is garbage collected. |
Applicable to | Final keyword is used with the classes, methods and variables. | Finally block is always related to the try and catch block in exception handling. | Finalize() method is used with the objects. |
Functionality | (1) Once declared, final variable becomes constant and cannot be modified. | (1) finally block runs the important code even if exception occurs or not. | Finalize method performs the cleaning activities with respect to the object before its destruction. |
Execution | Final method is executed only when we call it. | Finally block is executed as soon as the try-catch block is executed. It's execution is not dependant on the exception. | Finalize method is executed just before the object is destroyed. |
The different sizes and values that can be stored in the variable are defined by data types. In Java, there are two types of data types:
● Primitive data types - Boolean, char, byte, short, int, long, float, and double are examples of primitive data types.
● Non - primitives data types - Classes, Interfaces, and Arrays are examples of non-primitive data types.
Primitive data types
Primitive data types are the building blocks of data manipulation in the Java programming language. These are the most basic data types in the Java programming language.
Let's take a closer look at each of the eight primitive data types.
Boolean
Only two potential values are stored in the Boolean data type: true and false. Simple flags that track true/false circumstances are stored in this data type.
The Boolean data type specifies a single bit of data, but its "size" cannot be precisely defined.
Byte
The primitive data type byte is an example of this. It's an 8-bit two-s complement signed integer. It has a value range of -128 to 127. (inclusive). It has a minimum of -128 and a high of 127. It has a value of 0 by default.
The byte data type is used to preserve memory in huge arrays where space is at a premium. Because a byte is four times smaller than an integer, it saves space. It can also be used in place of "int" data type.
Short
A 16-bit signed two's complement integer is the short data type. It has a value range of -32,768 to 32,767. (inclusive). It has a minimum of -32,768 and a maximum of 32,767. It has a value of 0 by default.
The short data type, like the byte data type, can be used to save memory. A short data type is twice the size of an integer.
Int
A 32-bit signed two's complement integer is represented by the int data type. Its range of values is - 2,147,483,648 (-231 -1) to 2,147,483,647 (231 -1). (inclusive). It has a minimum of 2,147,483,648 and a maximum of 2,147,483,647. It has a value of 0 by default.
Unless there is a memory constraint, the int data type is usually chosen as the default data type for integral values.
Long
A 64-bit two's complement integer is the long data type. It has a value range of -9,223,372,036,854,775,808(-263 -1) to 9,223,372,036,854,775,807(263 -1). (inclusive).
Its lowest and maximum values are 9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. It has a value of 0 by default. When you need a larger range of values than int can supply, you should utilize the long data type.
Float
The float data type is a 32-bit IEEE 754 floating point with single precision. It has an infinite value range. If you need to preserve memory in big arrays of floating point integers, use a float (rather than a double). For precise numbers, such as currency, the float data type should never be used. 0.0F is the default value.
Double
A double data type is a 64-bit IEEE 754 floating point with double precision. It has an infinite value range. Like float, the double data type is commonly used for decimal values. For precise values, such as currency, the double data type should never be utilized. 0.0d is the default value.
Key takeaway
The different sizes and values that can be stored in the variable are defined by data types.
In Java, type casting is a method or procedure for manually and automatically converting one data type into another. The compiler performs the automatic conversion, whereas the programmer performs the manual conversion.
Fig: Type casting
The act of allocating a value from one primitive data type to another is known as type casting. When you assign the value of one data type to another, you should consider the data type's compatibility. If they are compatible, Java will convert them automatically (Automatic Type Conversion), but if they aren't, they must be cast or converted directly.
In Java, there are two different methods of casting:
- Widening Casting
When two data types are automatically converted, this type of casting occurs. Implicit Conversion is another name for it. This occurs when the two data types are compatible, as well as when a smaller data type's value is assigned to a larger data type.
This entails converting a smaller data type to a larger data type.
Byte -> short -> char -> int -> long -> float -> double
Example: The numeric data types are interchangeable, however there is no automatic translation from numeric to char or boolean. Furthermore, char and boolean are not interchangeable. To better understand how Implicit type casting works, let's construct a reasoning for it.
Public class Conversion{
Public static void main(String[] args)
{
Int i = 200;
//automatic type conversion
Long l = i;
//automatic type conversion
Float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output
Int value 200
Long value 200
Float value 200.0
2. Narrowing Casting
Narrowing type casting is the process of converting a higher data type to a lower one. It's also known as casting up or explicit conversion. The programmer performs this task manually. The compiler will raise a compile-time error if we do not perform casting.
Converting a larger data type to a smaller data type is what this entails.
Double -> float -> long -> int -> char -> short -> byte
Example
//Java program to illustrate explicit type conversion
Public class Narrowing
{
Public static void main(String[] args)
{
Double d = 200.06;
//explicit type casting
Long l = (long)d;
//explicit type casting
Int i = (int)l;
System.out.println("Double Data type value "+d);
//fractional part lost
System.out.println("Long Data type value "+l);
//fractional part lost
System.out.println("Int Data type value "+i);
}
}
Output
Double Data type value 200.06
Long Data type value 200
Int Data type value 200
Key takeaway
- In Java, type casting is a method or procedure for manually and automatically converting one data type into another.
- The compiler performs the automatic conversion, whereas the programmer performs the manual conversion.
- When you assign the value of one data type to another, you should consider the data type's compatibility.
Operators are special symbols that are used to perform some specific operations on variables and values. For example +, *, -, /, <, > etc.
Since there are so many operators available, system has decided some precedence among them. The precedence of operators helps the compiler to decide which operator will perform first in case of availability of multiple operators.
The below table shows the precedence of operator.
Operators | Precedence |
Postfix | Expr++, expr-- |
Unary | ++expr, --expr, +expr, -expr, ~! |
Multiplicative | * / % |
Additive | + - |
Shift | << >> >>> |
Relational | < > <= >= instanceof |
Equality | == != |
Bitwise AND | & |
Bitwise exclusive OR | ^ |
Bitwise inclusive OR | | |
Logical AND | && |
Logical OR | || |
Ternary | ? : |
Assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
The precedence of the operator in the table is given as top operator has precedence and last operator has low precedence.
Operator having higher precedence will be evaluated by the compiler first. While operators on the same line have same precedence.
Different types of Operators
Following are various types of operators in Java:
- Arithmetic Operators
- Unary Operators
- Relational Operators
- Logical Operators
- Boolean Operators
- Bitwise Operators
- Ternary Operators
- New Operators
- Cast Operators
1. Arithmetic Operators: They are the type of operators that perform an operation on two operands.
+, -, *, /, % are various Arithmetic operators
+ is the Addition operator
- is the Subtraction operator
* is the Multiplication operator
/ is the division operator
% is the remainder operator also called as modulus operator
Lets see a program on this concept
Code:
Class ArithmeticOperators{
public static void main(String[] args) {
Double n1 = 12.5, n2 = 3.5, add, subtract, multiply, divide, mod;
// This is how you use the addition operator
Add = n1 + n2;
System.out.println("n1 + n2 = " +add);
// This is how you use the subtraction operator
Subtract = n1 - n2;
System.out.println("n1 - n2 = " +subtract);
// This is how you use the multiplication operator
Multiply = n1 * n2;
System.out.println("n1 * n2 = " +multiply);
// This is how you use the division operator
Divide = n1 / n2;
System.out.println("n1 / n2 = " +divide);
// This is how you use the mod or remainder operator
Mod = n1 % n2;
System.out.println("n1 % n2 = " +mod);
}
}
Output:
2. Unary Operators: They are the types of operators that perform an operation on one operand.
+ is the Unary Plus Operator
- is the Unary Minus Operator. It inverts sign of an expression
++ is the Increment Operator. Increments value by 1
-- is the decrement Operator. Decreases value by 1
! is the Logical complement Operator. It inverts the value of a boolean, i.e. true to false and false to true
Program:
Class UnaryOperator {
Public static void main(String[] args) {
Double number = 5.2, unaryPlus, unaryMinus, increment, decrement, unaryLogical;
Boolean flag = false;
System.out.println("+ unaryPlus = " + +number);
System.out.println("- unaryMinus= " + -number);
System.out.println("++ increment = " + ++number);
System.out.println("-- decrement= " + --number);
System.out.println("! unaryLogical: !flag = " + !flag);
}
}
Output:
3. Relational Operators: Also called as equality and relational operators, these operators determine the relationship between the two operands.
== is the Equal to operator
!= is the Not equal to operator
> is the Greater than operator
>= is the Greater than or equal to operator
< is the Less than operator
<= is the Less than or equal to operator
Program:
Class RelationalOperators {
Public static void main(String args[]) {
Int x = 50;
Int y = 70;
System.out.println("x == y = " + (x == y) );
System.out.println("x != y = " + (x != y) );
System.out.println("x < y = " + (x < y) );
System.out.println("x > y = " + (x > y) );
System.out.println("y <= x = " + (y <= x) );
System.out.println("y >= x = " + (y >= x) );
}
}
Output:
4. Logical Operators: Also called as conditional operators, Logical operators operate on boolean expressions. Various Logical operators are:
&& Conditional-AND, its true only if all boolean expressions are true
|| Conditional-OR, its true if either of the boolean expression is true
Program:
Class LogicalOperators{
Public static void main(String args[]) {
Boolean n = false;
Boolean m = true;
System.out.println("m && n = " + (m&&n));
System.out.println("!(m && n) = " + !(m && n));
System.out.println("m || n = " + (m||n) );
}
}
Output:
5. Boolean Operators: These operators operate only on Boolean Operands
& denotes the AND operator
| denotes the OR operator
^ denotes the XOR operator
! denotes the NOT operator
!= denotes the NOT EQUAL TO operator
== denotes the EQUAL TO operator
Program:
Class BooleanOperators{
public static void main(String args[]){
Boolean X = true;
Boolean Y = false;
System.out.println("X&Y = "+(X&Y));
System.out.println("X|Y = "+(X|Y));
System.out.println("X^Y = "+(X^Y));
System.out.println("!X = "+(!X));
System.out.println("X!=Y = "+(X!=Y));
System.out.println("X==Y = "+(X==Y));
System.out.println("(X|Y)&X = "+((X|Y)&X));
}
}
Output:
6. Bitwise Operators: They are used to perform bit shift operators in Java.
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
Program:
Class BitwiseOperators {
public static void main(String[] args)
{
int x = 5;
int y = 7;
// bitwise AND 0101 & 0111=0101 = 5
System.out.println("x&y = " + (x & y));
// bitwise OR 0101 | 0111=0111 = 7
System.out.println("x|y = " + (x | y));
// bitwise XOR 0101 ^ 0111=0010 = 2
System.out.println("x^y = " + (x ^ y));
// bitwise AND ~0101=1010, will give 2's complement of 1010 = -6
System.out.println("~x = " + ~x);
// can be combined with assignment operator for shorthand assignment x=x&y
x &= y;
System.out.println("x= " + x);
}
}
Output:
7. Ternary Operators: It is the only operator that takes three operands. It can be used to replace if-else statements as well as switch statements.
Program:
Class TernaryOperator {
Public static void main(String[] args) {
Double num = -5.5;
String verdict;
Verdict = (num>0.0) ? "Positive" : "Not Positive";
System.out.println("The Number " +num+ " is " +verdict);
}
}
Output:
8. New Operator: The new operator instantiates a class by dynamically allocating (i.e., allocation at run time) memory for a new object and returning a reference to that memory.
Program:
Class Square
{
double squareSide;
}
public class NewOperator
{
public static void main(String[] args)
{
Square s1 = new Square();
// assigning s2 to s1
Square s2 = s1;
s2.squareSide = 20;
System.out.println(s1.squareSide);
System.out.println(s2.squareSide);
}
}
Output:
M
Up casting: Java Virtual Machine (JVM) performs automatic conversion.
Byte => short => int => long => float => double
e.g.int j = 5;
Long i = j;
Down Casting: Also called as explicit casting, this can be best explained through an example.
e.g.int j = 5;
Long i = j;
Byte b1=j; //compile time error
byte b2=(byte)j; //allowed. Explicit casting is done
Java provides us three types of control structures:
- Branching statements: These are used when we want to choose among two or more paths. These are of three types in java: if/else/else if, ternary operator and switch.
- Loop/Iterators: Loops are used when we want to repeatedly run some part of the code. Java provides three types of loop: for, while and do while.
- Jumping statements: These statements are used to alter the flow of control in loops. These are of two types: break and continue.
Branching statements
Branching statements are used to choose the path for execution. These are of three types: if/else/else if, ternary and switch.
1. If statement
The simplest form of control structure is if statement. This statement checked a Boolean expression, if the expression value is true then the program enters a block of code; otherwise if Boolean expression value is false it skip if statement block.
Syntax of if statement is:
If(Boolean condition)
{
Line 1;//it will execute only when if statement holds true
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“Output is true”);
}
}
}
Output:
Output is true
2. If-else statement
An extended version of if statement, which use a second block of code which is known as else block in the situation when if condition fails.
Syntax of if else statement:
If(Boolean condition)
{
Line 1;// it will execute only when if statement holds true
}
Else
{
Line 2;// it will execute only when if statement holds false
}
Example
Public class Program {
Public static void main(String[] args)
{
Int a = 5;
Int b = 15;
If(a+b>=20)
{
System.out.println(“if condition is true”);
}
Else
{
System.out.println(“if condition is false”);
}
}
}
Output:
If condition is true
3. If-else-if ladder or Nested if-else condition
In nested if-else condition first if condition is followed by many else-if conditions. In other way we can define it as a decision tree of if-else-if statement where we have to make multiple choices based on combination of conditions.
Syntax of nested if-else condition:
If(Boolean condition 1) {
Statement 1; //it will executes when condition 1 is true
}
Else if(Boolean condition 2) {
Statement 2; // it will executes when condition 2 is true
}
Else {
Statement 2; //it will executes when all the conditions are false
}
Example:
Public class Example {
Public static void main(String[] args) {
Int a = 15;
If(a < 10) {
System.out.println("a is less than 10");
}else if (a = 12) {
System.out.println("a is equal to 12");
}else if(a > 10) {
System.out.println("a is greater than 10");
}else {
System.out.println(a);
}
}
}
Output:
a is greater than 10
4. Switch condition
Switch conditions in Java are almost same as nested if-else statement.
Switch conditions are designed using multiple blocks of codes known as cases. Among so many cases a single case is executed based on the condition mentioned in the switch.
They are simple to use in comparison to nested if-else. While writing switch statements few things need to be kept in mind:
- We cannot create duplicate case. Each case will be different.
- The variables we can use in case are int, short, byte, char or enumeration. Strings are also supported.
- If all cases fail, then only default statement will be executed.
- While using switch statement, we use break statement also. Break statement will terminate the execution after switch case is satisfied, otherwise next case will be executed.
- The case expression variable must be same as at the time of declaration.
Syntax of switch statement:
Switch (condition){
case data1:
statement 1;
break;
.
.
.
case dataN:
statement N;
break;
default:
default statement;
}
Example:
Class Student
Public static void main(String[] args) {
Int a = 2;
Switch (a){
Case 0:
System.out.println("value is 0");
Break;
Case 1:
System.out.println("value is 1");
Break;
Default:
System.out.println(a);
}
}
}
Iterative statements-
In programming, there are certain situations when we want our code to execute some instructions repeatedly until the desired condition is met.
The above given situation can be implemented using the concept of loop. Loops are used to repeat the same instruction many times in succession.
Java provides us three types of looping statements as:
- For loop,
- While loop and
- Do-while loop.
1. For loop
Just like C and C++, for loop in Java is also same. A for loop is used to execute a set of code several times.
For loop consists of three parts. First part is used to initialize the loop variable, second part contains the condition and the third part increment/decrement the variable. For loop is defined in a single line.
Syntax of for loop:
For(initialization, condition, increment or decrement)
{
//block of statements to be executed
}
Example
Class Example
{
Public static void main(String[] args)
{
Int s = 1;
For(int i = 1; i<=5; i++) {
s = s + i;
}
System.out.println("The sum = " + s);
}
}
Output:
The sum = 6
2. While loop
The while loop statement is also used to repeat the execution of code multiple times.
While loops are preferable to use when we don’t know the exact number of iterations to be done in advance.
Here the initialization of variable and increment/decrement is done outside the loop statement.
In while loop the condition is checked first, if the condition is true then only execution will be done inside the loop; otherwise outside loop statements will be executed.
While loops are also know as entry controlled loop.
Syntax of while loop
While(condition){
//looping statements
}
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
While(a<=5) {
System.out.println(a);
a = a+ 1;
}
}
}
Output:
The list of first 5 even numbers
1
2
3
4
5
3. Do-while loop
In do-while loop statements are executed first then the condition is evaluated at the end of the loop.
It can we use on those places where we want to execute the statements at least once.
The do-while loops are also known as the exit controlled loop.
Syntax of do-while loop:
Do
{
Statements
} while (condition);
Example
Class Example {
Public static void main(String[] args) {
Int a = 1;
System.out.println("The list of first 5 numbers \n");
Do {
System.out.println(a);
a = a+ 1;
} while(a<=5)
}
}
Jumping Statements
Jump statements are used to change the execution flow of the program to some other specific statements.
In Java there are two types of jump statements: break and continue.
1. Break statement
It is used to immediately terminate the execution of a loop and the control will be passing on to the next statement after the loop.
Break statement are always used inside a loop or switch statement, they cannot be used independently.
Example
Class Example {
Public static void main(String[] args) {
For(int a = 1; a<= 5; a++) {
System.out.println(a);
If(a==3) {
Break;
}
}
}
}
Output
1
2
3
2. Continue statement
Continue statements are used when we want to skip only specific part of the loop and jumps to the next instruction in the loop immediately, while break statement terminates the loop.
It can be used with for or while loop.
Example
Class Example
{
public static void main(String arg[])
{
for(int x = 0; x <=3; x++)
{
if(x == 1)
continue;
System.out.println("Number= " + x);
}
}
}
Output
Number = 0
Number = 2
Number = 3
References:
1. Herbert Schildt, Java2: The Complete Reference, Tata McGraw-Hill
2. Object Oriented Programming with JAVA Essentilas and Applications, Mc Graw Hill
3. Core and Advanced Java, Black Book- dreamtech
4. Programming with JAVA- E Balagurusamy