Unit – 1
An introduction to programming and Introduction to Java
A programming language characterizes a bunch of instructions that are executed together to solve out a particular task by the CPU (Central Processing Unit).
The main purposes of programming languages are predominantly to control the machine performance or to execute algorithms. As of now, thousand programming languages have been designed.
Every programming language is designed with some set of keywords and pre defined syntax, which are then utilized to perform a task with the help of instructions.
Till now there are many languages available in market, but all of them differ with each other in some manner having their own specific purpose.
The difference in these languages can be on the basis of the degree of abstraction they get from the hardware.
The main types of programming languages classified as follows:
1. Procedural Programming Language:
These types of programming language follow a sequence to execute set of instructions to perform a specific task. They are designed using numerous variables, loops and other elements.
2. Functional Programming Language:
Functional Programming language is different from procedural programming language in terms of its design.
FPL does not use the concept of loops; instead they prefer to use the previously stored data with the help of recursive functions.
The main focus of FPL is completely on the return value they are getting after performing a function.
3. Object-oriented Programming Language:
OOP language is designed using the concept of objects. In this language whole data is considered to be a collection of objects that store some internal data and also have access to external data.
The main basis of OOP language is the concept of encapsulation. Encapsulation defines that the internal data of object is hidden from the external world.
4. Scripting Programming Language:
Scripting languages are mostly combination of procedural and object-oriented language; however they have their own class as they are partial programming languages which can support enormous system.
5. Logic Programming Language:
These types of programming language based on logical reasoning. Here programmers design instruction using declarative statements and based on those instructions machine decide what will be the result of those statements.
Compiler
A compiler is a unique program that executes statements implemented in a specific programming language and transforms them into machine language or "code" that a computer's processor understands.
Normally, a developer composes programming instruction in a language, for example, an editor of Pascal or C are utilized to write single line at a time.
The source file is created consisting of statements. The software engineer then, runs the desired language compiler, having the name of the file consisting of source statements.
A compiler is probably going to perform numerous or some of the tasks such as: preprocessing, lexical analysis, parsing, semantic analysis, transformation of input programs to a moderate representation, code optimization and code generation.
Compilers execute these tasks in stages that advance efficient design and desired conversion of source code into target code.
Interpreter
A computer program known as an interpreter is utilized to run various instruction of program which is written in high level languages.
The interpreter changes the high level program into a middle language that it then, at that point executes, or it could parse the high level source code and afterward executes all the commands, which is done line by line or statement by statement.
An interpreter by and large uses one of the accompanying procedures for program execution:
- Scan the source code and performs the necessary steps;
- Translate source code into some productive middle portrayal or object code and quickly execute this;
- Precompiled code is executed externally by a compiler which is essential for the interpreter framework.
1. Re-usability: OOP gave us flexibility to use a code n number of times in spite of creating again and again. And this all happen because of the concept of class.
2. Data Redundancy: It means availability of same kind of data at multiple locations. This helps when a user needs same kind of functionality. By using the same class description and inherits all the data resides in that class. User can save time and effort of creating a new class again.
3. Code Maintenance: OOP provides us the facility to maintain the code by modifying the existing code with the desired changes.
4. Security: The concept of data hiding and abstraction helps the user to hide the important data from external world. Only necessary data will be available for view.
5. Design Benefits: The concept of OOP is design in such a way which allows us to design and fix any bug easily, so that the chances of any risk are reduced. It becomes easy for the programmer to scan the program for any kind of criticality.
6. Better productivity: The above mentioned advantages itself show how productive OOP language will be in terms of designing or usage. OOP consist of huge libraries and inbuilt features to write a program in an effective and efficient way.
7. Easy troubleshooting: The concept of encapsulation helps us with troubleshooting. Normally in other language when something wrong or bug occurs a programmer has to scan the whole code, but this is not the case with OOP. OOP tells us the exact location where to look for any kind of error.
8. Polymorphism flexibility: Polymorphism means having multiple roles. A class can be used at multiple places with different features in it.
Object Oriented Programming language is a programming language which is designed using the concept of object and classes.
This language uses objects to write program which consist of data and code. Data is stored by using fields and code is written in the form of procedures.
This language provides us a flexibility of developing program that is simple and reusable code which we can use at multiple places.
The main aim of OOP is to design real world objects like inheritance, data hiding, polymorphism and so on in programming.
The fundamental concept behind OOP is to tie together the data and functions that work on them so no other piece of the code can access to this information apart from that function.
The different types of object oriented programming languages available in the market are C++, Java, JavaScript and Python.
The most important features of OOP language which make it different from other programming language are discussed below.
1. Classes: In OOP the real world entity can be represented with the help of class which depicts its framework for all the objects.
A class can consist of as many objects as a programmer want.
2. Objects: Objects are used to store data and values. The data is stored by using variables and methods are used to define the behaviour or function of that object.
By using a single class, we can create as many objects as we want and all these objects will have all the variables and behaviour of a class.
3. Encapsulation: It is the way toward restricting object’s state (fields) and behaviours (methods) together in a single entity called "Class".
Since it envelops the two fields and methods by a class, it will be secured from the external access.
We can limit the access to the methods of a class utilizing access modifiers, for example, private, protected and public keywords.
The object deals with its own state by means of these methods and no other class can modify it except if external permission is provided. To use the object, you should use the methods provided.
Whenever a class is created in Java, it implies we are doing encapsulation.
It also helps in accomplishing the reusability of code without compromising its security.
4. Abstraction: Abstraction is an enhancement of encapsulation. It is used to show only required data and hide rest of the data of an object from the client.
5. Inheritance: By using the concept of inheritance we can inherit few/all properties of another object. For instance, a child acquires the qualities of his/her parents.
Reusability is a significant benefit of using inheritance. You can reuse the fields and methods of the already created class.
With the help of inheritance, we can create a new class by inheriting the features and methods of any existing class.
Java provides us different types of inheritance such as single, multiple, multilevel, hierarchical, and hybrid.
6. Polymorphism: Polymorphism provides us the flexibility to define an object in multiple forms. The main use of polymorphism in OOP is when reference of a parent class is made to a child class object.
Here if a message is sent to multiple class objects, then every objects gives response according to their fields and methods. So, response of every class object will be different for a single request.
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.
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.
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.
- 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.
Difference between C/C++ and Java
Parameters | C++ | Java |
Platform dependency | Platform Dependent | Platform Independent |
Used for | System programming | Application programming |
Compiler/Interpreter | Only support compiler | Support both compiler and interpreter |
Programming Language | Both procedural and OOP | Only OOP |
Interface | Native System libraries can be accessed directly | Calls made through Java Native Interface and Java Native Access |
Memory Management | Programmer can access | Controlled by System |
Root hierarchy | No such root hierarchy | Follows single root hierarchy |
Goto | Supports goto statement | Doesn’t support goto statement |
Multiple Inheritance | Support | Doesn’t support |
Operator overloading | Support | Doesn’t support |
Pointers | Support | Supports pointers internally. User cannot use pointers |
Call by value and Call by reference | Support both | Only supports call by value |
Structure and Union | Support both | Doesn’t support |
Thread | Doesn’t support. Depend on third party for thread support | Support |
Virtual keyword | Support | No virtual keyword |
Inheritance tree | Always creates a new inheritance tree | Always uses a single inheritance tree |
- 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).
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
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.
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 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.
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.
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.
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.
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.
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.
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.
Let us know all the s 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.
These are the smallest element of a code which are identified by the compiler for execution.
In Java tokens can be anything including identifiers, keywords, literals, operators, comments and separators.
Consider the first program:
Class FirstProgram
{
Public static void main(String[] args)
{
System.out.println(“My first program”);
}
}
Here in this code class, FirstProgram, {, static, void, main, (, String, args, [, ], ), System, ., out, println, My, first, program, }, } are all examples of tokens.
Various data types are used in Java. These data types are used to represent the memory allocation. Every data type has different amount of memory allocation associated with it.
They are also called as primitive data types in Java.
- Byte: The byte data type is an 8-bit signed two's complement integer. Range is -128 to 127.
2. short: The short data type is a 16-bit signed two's complement integer. Range is -32,768 to 32,767 (inclusive).
3. int: The int data type is a 32-bit signed two's complement integer. Range is -231 to 231-1.
4. long: The long data type is a 64-bit two's complement integer. Range is -263 to 263-1.
5. float: The float data type is a 32-bit IEEE 754 floating point.
6. double: The double data type is a 64-bit IEEE 754 floating point.
7. boolean: true and false are two possible values of the boolean data type.
8. char: The char data type is a single 16-bit Unicode character. Range is '\u0000' (or 0) to '\uffff'.
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.
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
Typecasting is a method which is used to convert one data type into another. It can be done manually or automatically.
In case of manual the conversion is done by programmer while in automatic it is done by compiler.
Java supports two types of type casting:
- Widening Casting: It’s an automatic conversion of a smaller type into larger data type size.
- Narrowing Casting: This is a manual conversion of a larger data type into smaller data type size.
Widening Typecasting
This type casting is an automatic conversion of data type. It is safe in comparison to narrowing casting as there is no chance of losing data.
To do widening type casting both data types must be compatible with each other and the target type must be larger than the source data type.
Example of widening typecasting is shown below:
Public class Example1
{
Public static void main(String[] args)
{
Int myInt = 8;
Double myDouble = myInt; //automatically convert int to double
System.out.println(myInt); // output will be 8
System.out.println(myDouble); // output will be 8.0
}
}
Narrowing Typecasting
This is a manual conversion of larger data type into smaller data type. It is also known as explicit casting as it is done manually by programmer.
To do manual conversion place the data type in parentheses in front of the value.
Example of narrowing typecasting:
Public class Example2
{
Public static void main(String[] args)
{
Double myDouble = 8.51;
Int myInt = (int) myDouble; // manually converting double to int
System.out.println(myDouble); // output will be 8.51
System.out.println(myInt); // output will be 8
}
}
Java Control Structures
Java program or code is nothing but some set of instructions which are executed by compiler.
In certain applications or program a user needs to write some choices which are to be selected by the compiler based on the conditions.
However, Java provides us some statements for such situations known as control structures.
Control structures are used to change the execution path and also control the execution of instructions.
Java provides three types of control structures: Conditional, Loop/Iterators and Branching statements.
Java Arrays
Java arrays are defined as objects which consist of similar types of elements. Array elements are always stored in contiguous memory location.
Java array are index based. The first element is stored at 0th index, second element is stored at 1st index and etc.
Array in Java has feature to inherit object class and are able to implement the concept of Serializable as well as Cloneable interface.
They are capable of storing primitive values or object.
Java array’s are of two types:
- Single dimensional
- Multidimensional
Java provides us three types of control structures:
- Conditional statements: These are used when we want to choose among two or more paths. Conditional statements 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.
- Branching statements: These statements are used to alter the flow of control in loops. Branching statements are of two types: break and continue.
Conditional 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. Ternary Condition
Ternary condition is an enhancement or shorthand to the if-else condition. The working of ternary and if-else condition is same.
Consider an example of if-else:
If (a > 2) {
System.out.println("a is higher than 2");
} else {
System.out.println("a is lower or equal to 2");
}
Now see the same code in ternary condition
System.out.println(a > 2 ? "a is higher than 2" : "a is lower or equal to 2");
5. 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);
}
}
}
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)
}
}
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
An array is a collection of variables having same data type which is referred to by a single name.
Any data type can be used to create arrays and with single or multidimensional. To access any element of array we have to refer its index.
One-Dimensional Arrays
A one dimensional array is nothing but a list of same type of variable. To create an array in Java, an array variable of desired data type is required.
The syntax of a one-dimensional array is
Data_type var_name[];
Example:
Int months[];
The above example shows that num_weeks is an array variable, but still there is no memory allocation is done for it as it is set to null i.e an array without value.
To allocate values to the array, use new and assign it to num_weeks. New operator is used to allocate memory.
Syntax:
Var_name = new data_type[size];
Example:
Months = new int[7];
After the execution of this statement num_weeks array is an array of 7 integers.
After allocation of array, next comes the index. To access a specific element of an array, reference to its index within square brackets is to done.
Months[0] = 31;
Months[1] = 28;
Let’s see an example of a program of an array
Class Demoarray
{
Public static void main(String args[])
{
Int x[];
x = new int[5]; //declaration and instantiation of array
x[0]=10; //initialization of array
x[1]=20;
x[2]=70;
x[3]=40;
x[4]=50;
For(int i=0; i<x.length; i++) //length is the property of array
System.out.println(x[i]);
}
}
Output
10
20
30
40
50
Another way of declaring array is
Int x[] = new int[5];
Arrays can also be initialized at the time of declaration
Int x[] = {3, 4, 2, 8, 2};
Or
Double a[]= {10.1, 12.4, 8.5};
Java supports multidimensional array which is arrays of arrays. These look like an rectangular array.
Syntax to declare multidimensional array is
Int xy[][] = new int[3][2];
This allocates an array of 3 by 2 size.
Example
Class Multiarray
{
Public static void main(String args[])
{
Int a[][]={{6,2,1}, {7,3,1}, {5,7,3}}; //declaring and initializing 2D array
For(int x=0; x<3; x++){
For(int y=0; y<3; y++){
System.out.print(arr[x][y]+" ");
}
System.out.println();
}
}
}
Output
6 2 1
7 3 1
5 7 3
In Java console class provides the facility to read input from console. It provides us methods to read texts and passwords.
When a password is read using console class, it will not be visible to the user.
There are four different types methods of reading input from the user in the command line environment (console) in Java.
- Using Buffered Reader Class
- Using Scanner Class
- Using Console Class
- Using Command Line Argument
Input through command line arguments are stored in the string format which further than converted into integer using parseInt method of the integer class. Same thing is done for float and other data type during execution.
In this input form we use args[]. Information is passed during the runtime of program.
Example
Class Demoinput {
Public static void main(String[] args)
{
If (args.length > 0) {
System.out.println("The command line arguments are:");
// iterating the args array and printing the command line arguments
For (String val : args)
System.out.println(val);
}
Else
System.out.println("No command line " + "arguments found.");
}
}
Output
The command line arguments are:
Good
Day
The most common method to read input in Java is the scanner class and it is found in java.util package.
The main aim of Scanner class is to read primitive types and strings using regular expressions, besides this input can be read through the command line.
Let’s take an example to read data using nextLine() method, which is used to read strings.
Import java.util.Scanner; // Importing the Scanner class
Class Demo {
Public static void main(String[] args)
{
Scanner myObject1 = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Name");
String userName = myObject1.nextLine(); // Read user input
System.out.println("Name is: " + Name); // Output user input
}
}
Output:
Enter Name
Disha
Name is: Disha
Scanner Input Types
To read different types of data, the various methods are:
Method | Description |
NextBoolean() | Read a Boolean value from the user |
NextByte() | Read a Byte value from the user |
NextDouble() | Read a Double value from the user |
NextFloat() | Read a Float value from the user |
NextInt() | Read a Int value from the user |
NextLine() | Read a String value from the user |
NextLong() | Read a Long value from the user |
NextShort() | Read a Short value from the user |
This method was first introduced in JDK 1.0. To use this method, we have to wrapped the System.in (Standard input stream) in an InputStreamReader which is further wrapped in a BufferedReader.
The input can be read from the user in the command line.
The Java BufferedReader class can be declare as:
Class BufferedReader extends Reader
Consider an example
Import java.io.BuffereReader;
Import java.io.IOExeption;
Import java.io.InputStreamReader;
Public class Example {
Public static void main(String[] args)
Throws IOException
{
//BufferReader is used to read data
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//reading data using readLine
String name = reader.readLine();
System.out.println(name);
}
}
Input
Disha
Output
Disha
To read other types of data, functions like Integer.parseInt(), Double.parseDouble(). To read multiple values we use split().
References:
1. Programming in Java. Second Edition. Oxford Higher Education. (Sachin Malhotra/Saura V Choudhary)
2. CORE JAVA For Beginners. (Rashmi Kanta Das), Vikas Publication
3. JAVA Complete Reference (9th Edition) HerbaitSchelidt.