Introduction to Java
Java is a popular third generation object oriented programming language. Java was developed by Sun Microsystems Company of USA In 1991 later acquired by Oracle Corporation in 2010. Java is a simple, object oriented, distributed, interpreted, robust, secure, portable, highly performance, multithreaded and dynamic language.
Java is both a programming language and a platform. Like any other language we can develop application by java so it is a programming language. Java is a Platform because a palateform is the combination of system software and hardware e.g. operating system, windows XP, NT etc.
Java provides the facilities like an operating system that’s why it is known as a platform. Its platform is designed to deliver and run highly interactive, dynamic and secure applications on networked computer system.
James Gosling and Patrick Naughton are the father of java. Java is well suited for both standalone and web application development and is designed to provide solutions to most of the problems faced by users of the internet era. It helps to create modular programs and reusable code. The target of Java is to write a program once and then run this program on multiple operating systems (WORA - Write Once Run Anywhere).
History of Java
In 1990 Patric Naughton and James Goslin with his co-workers started a secrete project called “Green” in Sun Microsystem Company. This project was started to develop a platform for development of software for consumer electronic devices like cable, TV, switch boxes, microwave, Oven and remote control etc.
Goslin give the name to this language “OAK” (named after the OAK tree outside the Gosling’s office). OAK was renamed to java when a group of Sun people visited a local coffee shop along with Goslin, the name Java was suggested, and it stuck. This name is combination of initial letter of names of James goslin, Arthur, Van Hoff, Andy bechtolsheim, team member of java project.
In 1992 by the help of Java they develop a remote control known as “*7”. In 1993 by the development of WORLD WIDE WEB, Green project team decides to develop tiny java Applet graphical programs to make the Internet rich with graphics. Java Applets were the tinny java programs that can run on any computer connected to the internet.
In 1994 this team develops a web browser known as “HOT JAVA” to run Applet program on Internet. In 1995 “OAK” was renamed as “JAVA” because it was already a trade name of Oak technologies. Many Companies like MICROSOF, NETSCAP etc. supported this name. At 1996 java established itself as master of internet programming language and Sun releases first version of java known as jdk1.0 or java 1 on January 23, 1996.
Goslin give the name to this language “OAK” (named after the OAK tree outside the Gosling’s office). OAK was renamed to java when a group of Sun people visited a local coffee shop along with Goslin, the name Java was suggested, and it stuck. This name is combination of initial letter of names of James goslin, Arthur, Van Hoff, Andy bechtolsheim, team member of java project.
In 1992 by the help of Java they develop a remote control known as “*7”. In 1993 by the development of WORLD WIDE WEB, Green project team decides to develop tiny java Applet graphical programs to make the Internet rich with graphics. Java Applets were the tinny java programs that can run on any computer connected to the internet.
In 1994 this team develops a web browser known as “HOT JAVA” to run Applet program on Internet. In 1995 “OAK” was renamed as “JAVA” because it was already a trade name of Oak technologies. Many Companies like MICROSOF, NETSCAP etc. supported this name. At 1996 java established itself as master of internet programming language and Sun releases first version of java known as jdk1.0 or java 1 on January 23, 1996.
Version of JAVA
- J2SE 1.2 (December 8, 1998)
- J2SE 1.3 (May 8, 2000)
- J2SE 1.4 (February 6, 2002)
- J2SE 5.0 (September 30, 2004)
- Java SE 6 (December 11, 2006)
- Java SE 7 (July 28, 2011)
- Java SE 8 (March 18, 2014)
- Java SE 9 (September 21, 2017)
- Java SE 10 (March 20, 2018)
- Java SE 11 (September 25, 2018)
- Java SE 12 (March 19, 2019)
- Java SE 13 (September 17, 2019)
- Java SE 14 (March 17, 2020)
Types of java programs or Java Application
Standalone programs
Standalone programs are like simple C and C++ programs. These program can read and write files and perform certain operations that applets cannot do. Executing of these programs involves two steps. First compiling the source code into byte code using javac compiler and second executing the byte code program using java interpreter.
These are also known as desktop application or window-based application because we need to install them on every machine or server to use them. AWT, Swing are used to create these programs. Example Management Software (Library, Inventory, Salary Management), Antivirus, Accounting System, Media players etc.
These are also known as desktop application or window-based application because we need to install them on every machine or server to use them. AWT, Swing are used to create these programs. Example Management Software (Library, Inventory, Salary Management), Antivirus, Accounting System, Media players etc.
Java Applets
Java applets are small programs developed for internet application. These are graphical in nature. We can develop applets from simple animated graphics to highly complex games. Since applets are embedded in an HTML document and run inside a Web page, creating and running applets are more complex than creating an application.
Java Web Applications or Java Servlet
Java servlets are the Java programs that run on a web server to generate dynamic web contents. To create server-side web applications java use Servlet, JSP, Struts, JSF, etc. technologies.
Mobile Application or Android Application
We can create application software for mobile devices by Java. Java ME (Mobile Edition) is specially designed for building applications for small devices like mobile, iPod, tablets etc. Java is a programming language for Google Android application development.
Enterprise Application
Application which are used and distributed on a very big scale are developed under Java EE (Enterprises Edition). These application needs high level of security, load balancing and clustering. Java EJB is used for development of such applications like Banking Application, Railway, Airlines applications etc.
Features of Java
Java compiler first translates java source code into byte code instruction which is not machine readable form so they are not able to run on the computer.
There for in second stage Java Interpreter generates machine code that run on the computer and can execute directly.
Thus java is a compiled and interpreted language.
Platform Independent
Java application programs written in one Operating system able to run on any Operating system unlike c or c++ where application programs written in one Operating system cannot run in any other Operating system.
For example any program written on UNIX operating system can run on windows operating system. So we can say that java is platform independent language.
Portable
Java portability is due to byte code (.class file) because a program in byte code can be transfer to any system without any difficulty and then JVM at that system will convert it into the machine code by the help of Java Interpreter (Java).
The second reason is the primitive data types that are machine independent.
Object Oriented
- Object oriented programming is a way of organizing programs as collection of objects, each of which represents an instance of a class and those instance (object) communicate and cooperate to accomplish tasks.
- Java follows the five concepts of OOPs (class, inheritance, abstraction, polymorphism, encapsulation). Object oriented programming treat data as most critical element in the program and does not allow it to be scattered around the program.
- Objecct oriented programming breaks a problem into a number of entities called objects and then builds data and functions around these objects.
- The data of an object is accessed by functions associated with it.
- Java is a pure object oriented language. Almost everything in java is in class and object. All program code and data remain within classes and object.
Data Hiding
Data hiding enables us to completely encapsulate an object’s data members. Data hiding prevents the users of an object from directly accessing the data members of the class. The uses of data hiding provide the following benefits:
1. Users of the class are isolated from the actual representation of the data.
2. Class programmer can change how data is represented or where data comes from, without affecting applications that use the class.
Robust (Reliable)
Java programming language is developed in a way that puts a lot of emphasis on early checking for possible errors, that’s why java compiler is able to detect errors that are not easy to detect in other programming languages. The main features of java that makes it robust are garbage collection, Exception Handling and memory allocation.
Java has strict run time and compiles time checking for data types. It represents the concept of exception handling due to which series of errors can be eliminated from the program and we can save our program from crashing.
Secure
Security is another important issue for java because it is an internet programming language which is a place of viruses and abuse of resources. When dealing with java applet, java first ensure that applet should be error free if there is error in the program it will not be communicate to the computer and any java program can not gain access into a system without proper authorization.
Beside this java provides a wide range of protection from viruses and malicious programs. It ensures that there will be no damage and no security will be broken.
Distributed
Java is distributed because it allowed multiple programs at multiple remote locations to collaborate and work together on a single project. Beside this it has ability to share the data and programs. Java programs can open on internet as easy as they can run on local System.
RMI (Remote Method Invocation) and EJB (Enterprise Java Beans) are used for creating distributed applications in java. The java programs can be distributed on more than one systems that are connected to each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures on a remote JVM.
Simple and Familiar
Java is a simple and familiar language because it is developed with the help of ‘C’ and ‘C++’. Programmers who have work on C and C++ languages can understand java very easily. To bring familiarity in java it was modeled on ‘C ‘and ‘C++’. Java code looks like a ‘C’ and ‘C++’ code. Java does not supports complex features like Pointers, Multiple inheritance and Operator overloading.
Multi threaded
Multi threading means handling multiple threads at the same time or to perform more than one operation at a single time. It is one of the most striking feature of java that increase the performance of java and provide maximum utilization of CPU. For example we can download a file at a time while we are playing a song at the same time.
High Performance
Java performance is very high mainly due to just in time compilation and its feature of Interpretation beside this multithreading also help full in improvement of its performance.
Its architecture is also designed in such a manner so that overheads may be reduced at run time from the program due to all these feature Java performance is very well.
Dynamic and Extensible
Java is a dynamic language. It is capable in adding new class, Objects, Methods at run time. Java also support function (native function) written in other language like ‘C’ and ‘C++’. These function can use by java at run time.
Easy Development
J2SE 5.0 (Java2 Standard Edition) is the development kit that provides many advance tool like auto boxing and unboxing, type safe, enum and varargs etc, with the help of these tools programming become easier and the source code also is bug free and error free. Program develop in J2SE5.0 also reduced the memory space used so it is one of the good feature of java.
Java Virtual Machine (JVM)
A JVM (Java Virtual Machine) translates byte code into machine language (binary code) this process is called just in time compilation (JIT). The JVM is the environment in which java program execute. Each operating system has different JVM, however the output they produce after execution of byte code is same across all operating systems. That is why we call java as platform independent language.
Java Development Kit (JDK)
Components of JDK (Java Development Kit)
Javac (java compiler)
It is use for compilation of java programs that convert the source code into byte code.
Java (java Interpreter)
It is use for interpretation (execution) of java programs that convert the byte code into the machine code so that program may run on computer.
Appletviewer
To view output of Java Applets, applet viewer is used.
Javap (Java Dissembler)
It is used to convert byte code into the program description. For example: javap hellojava
Jdb (Java Debugger)
It is used to helps us in finding errors in the java program.
Javadoc (for creating HTML document)
It is used to convert java source code to HTML format document. But for this class must be declared in public mode. For exmple: javadoc demo.java
Javah (for C header files)
It produced header files which is required by the native methods when we are using native method in our program. (javah demo) Will send header file into bin folder.
Compiler
Byte Code
When java compiler (javac) compiles source code then it converts it into a special code known as byte code. It is also known as .class file. This is an assembly language code which is neither readable to human nor to machine.
Java byte code is a low level representation of a java source code. It can be executed using the java interpreter because interpreter will convert it into machine code or binary code. The byte code might be transported across the web prior to begin executed by a java interpreter. Java interpreter is part of a web browser.
Interpreter
It is a software or program present in jdk that converts byte code into machine code or binary code. It converts code into binary format line by line. If any error found at any line of byte code the program execution will stop at once from that point and program will crash. This line by line conversion of byte code into machine code is called Just In Time Compilation.
Java Library
The Java Class Library (JCL) is a set of dynamically loadable libraries that Java applications can call at run time. A java library contains useful code that implements in many common programming tasks. When we write new java programs, we usually combine our own new code with code extracted from these libraries. To facilitate the process of execution, the java compiler and the JVM must access the libraries.
Difference between applet and Standalone program
Standalone
Program
|
Applet
|
| Applets are feature rich application programs that are specifically designed to be executed within an HTML web document to execute small tasks or just part of it. | ava applications, on the other hand, are stand-alone programs that are designed to run on a stand-alone machine without having to use a browser. |
| Required main method. | Do not required main method |
| Run directly on command prompt. | Run on web browser or applet viewer |
| Run by java (interpreter) command. | Run by appletviewer command or by using web browser. |
| Can access all the resources of the system including data and information on that system. | Cannot access any resource from system except web browser services. |
| Can run independently as they are trusted. | Cannot run independently but required high level of security. |
Structure of java program
{
public static void main(String args[])
{
System.out.println("Hello java");
}
}
Class Declaration
The first line "class SimpleProgram" declares a class, which is an object oriented construct. Java is true object oriented language and there for everything must be placed inside a class. class is a keyword which is used to declare a new class. SimpleProgram is the valid java identifier to identify the class by this name. Class name should start with capital letter.
Braces { }
Every class in java begins with an opening braces “{“ and ends with a closing braces “}”. These braces makes the body of class in which we perform all operations. These braces are used to group all commands together.
The Main Line
public static void main (String args[]) is main function/method of program. Execution of a java program starts from main function. A java program must have single main method. A java application can have a number of classes but only one out of those class can have main method.
public
The keyword public is the access specifier that declares the main method as unprotected and therefore making it accessible to all the class in a program. Means it can also be used by code outside of its class
Static
static keyword makes the main method as one that belongs to the entire class. The main must always be declared as static since the interpreter uses this method before any object is created. Static makes a variable or method as global.
Keyword static used when we want to access a method without creating its object, and in our programe always we call the main method, before creating any class objects.
Why we should define the main() method as static. This is because, the main() method is called by JVM before any object of the class exist and therfore must be called independent of any objects. Henc main() method should be static.
void
void keyword indicates that method will not return any value. main() method is declared as static because in java main() does not return any value.
String args[ ]
here string is the class and args[ ] is String array. This string array takes the input by command line argument which we can given at the time of compilation. Because of string array every type of values that we will insert in command line will be treated as string object.
The output line
System.out.println("Hello java"); is the printing statement in java. It is similar to the printf() function of C and cout<< command of C++. Since java is true object oriented language, every method must be part of an object. The println() method is a member of the out object, which is a static data member of System class.
We cannot create object of System class because it’s constructor new System() have private access but its static object out have public access. So we can access System class's method by the help of object out. Due to these restriction we write java printing statement like this:
System.out.println("Hello java");
out object will access by class name that is system and println() method will access by out object.
Simple Printing Programs
Example 1Printing information of a person directly without variable support. (Name, Age, Address, Contact Number).
Program
class Person_Information
{
public static void main(String args[])
{
System.out.println("Name\t: Mohammad Amir");
System.out.println("Age\t: 26 years");
System.out.println("Salary\t: 35000");
System.out.println("Gender\t: Male");
}
}
Output
Example 2
Printing information of a person stored in some variables.
Program
class Person_Information
{
public static void main(String args[])
{
String name="Mohammad Amir";
int age=26;
double salary=35000;
String gender="Male";
System.out.println("Name\t: "+name);
System.out.println("Age\t: "+age+" years");
System.out.println("Salary\t: "+salary);
System.out.println("Gender\t: "+gender);
}
}
Output
Example 3
Printing information stored in some variables by printf function instead of println or print function.
Program
class Person_Information
{
public static void main(String args[])
{
String name="Mohammad Amir";
int age=26;
long mobile=123456;
double salary=35000;
float bonus=2563.36f;
String gender="Male";
char MS='M';//MS i.e.Marital Status
System.out.printf("Name\t: %s\n",name);
System.out.printf("Age\t: %d\n",age);
System.out.printf("Mobile\t: %d\n",mobile);
System.out.printf("Salary\t: %f\n",salary);
System.out.printf("Bonus\t: %f\n",bonus);
System.out.printf("Gender\t: %s\n",gender);
System.out.printf("MStatus\t: %c\n",MS);
}
}
Description
In this programe I used a comment statement that is
char MS='M';//MS i.e.Marital Status
Compiler ignores comment part. Comment can be used anywhere in the program for information about functionality of a statement, block, program or to define a note. Comments help the programmer to understand the code and purpose of code in future. Comments make program easy to understand and improve the readability of code.
Single Line Comment: // Single line comment
Multiple Line Comment: /* Multiple
line
comment*/
Documentation Comment: /** Documentation Comment */
Output
System class or java.lange.System class
It is a final class without any public constructor and contain all static members and methods only. Due to final declaration we can not inherit this class. This class contain some pre-built class fields and methods. Some important features supported by this class are like this:
- Standard input streams.
- Standard output streams.
- Error output streams.
- It provide access to externally defined properties and environment variables.
- This class provides means for loading files and libraries.
public static final InputStream in
This is the standard input stream which is already open and available for supplying the input data. This is mainly corresponds to the keyboard inputs or other input sources that are specified by the host environment or a user. The system class uses System.in stream to refere to standard input.
public static final PrintStream out
This is the standard output stream which is already open and available for accepting the output data. This is mainly corresponds to displaying the output or another output destination that is specified by the host environment or a user. The system class uses System.out stream to refere to standard output.
public static final PrintStream err
This is the standard error output stream which is already open and available for accepting the output data. This output stream is used for displaying the error messages or other information that needs the immediate attention of a user. The System class provides references for the standard output by System.err.
Reading Data By User Programs
Example 1: Reading data by BufferedReader class
The class java.io.BufferedReader extends from java.io.Reader class. This class is used to read text from a character-based input stream. Java.io.BufferedReader class provides efficient way to read characters, array of characters and lines. It can be used to read data line by line by readLine() method.
Syntax:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.in is an InputStream which read data from keyboard. Than You create an InputStreamReader which reads bytes from System.in. Then you wrap InputStreamReader in BufferedReader which reads from InputStreamReader.
System.in
It is an InputStream which is typically connected to keyboard input of console programs. It is nothing but an in stream of OS linked to System class. Using System class, we can divert the in stream going from Keyboard to CPU into our program. This is how keyboard reading is achieved in Java.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard. It connects to input stream of keyboard that is System.in. It is works as a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset.
BufferedReader
BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it can get the efficient reading of characters, arrays, etc. It inherits the reader class and makes the code efficient since we can read the data line-by-line with the readline() method.
Program//importing Input Output package in our program
import java.io.*;
class Person_Information
{
public static void main(String args[]) throws IOException
{
//Making object of BufferedReader class
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter Name = ");
//reading string value by readLine method
String name=br.readLine();
System.out.print("Enter Age = ");
//reading integer value by converting to integer by parseInt method
int age=Integer.parseInt(br.readLine());
System.out.print("Enter Mobile Number = ");
//reading long value by converting to long by parseLong method
long mobile=Long.parseLong(br.readLine());
System.out.print("Enter Salary = ");
//reading double value by converting to double by parseDouble method
double salary=Double.parseDouble(br.readLine());
System.out.print("Enter Bonus = ");
//reading float value by converting to float by parseFloat method
float bonus=Float.parseFloat(br.readLine());
System.out.print("Enter Marital Status, Married (true/false) = ");
//reading boolean value by converting to boolean by parseBoolean method
boolean MS=Boolean.parseBoolean(br.readLine());
System.out.print("Enter Gender, M/F = ");
//reading character value by read method and converting to character by type casting (char)
char gender=(char)br.read();
//Printing information read by different methods
System.out.println("\n\nPERSON RECORDS\n");
System.out.println("Name\t: "+name);
System.out.println("Age\t: "+age);
System.out.println("Mobile\t: "+mobile);
System.out.println("Salary\t: "+salary);
System.out.println("Bonus\t: "+bonus);
System.out.println("MStatus\t: "+MS);
System.out.println("Gender\t: "+gender);
}
}
Description
We use two printing methods in this programe which are print() and println(). Description of them are like this:
Java has provided two functions print() and println() which helps us to display an output on the screen. Both of these functions belong to System class. The difference is that print() leave the cursor on the same line after printing whereas println() shift the cursor to the next line after printing.
Output
Example 2: Reading data by DataInputStream class
java.io.DataInputStream class enables us to read Java primitives data (int, float, long etc.) from an InputStream in a machine-independent way or numeric form instead of only raw bytes. We wrap an InputStream in a DataInputStream and then we can read Java primitives with the help of DataInputStream. Due to this reason it is called DataInputStream, because it reads data (numbers) not bytes from input stream.
Syntax:
System.in is an InputStream which read data from keyboard. Than You create a DataInputStream which reads data (numbers) not bytes from System.in stream.
Program//importing Input Output package in our program
import java.io.*;
class Person_Information
{
public static void main(String args[]) throws IOException
{
//Making object of BufferedReader class
DataInputStream in = new DataInputStream(System.in);
System.out.print("\nEnter Name = ");
//reading string value by readLine method
String name=in.readLine();
System.out.print("Enter Age = ");
//reading integer value by converting to integer by parseInt method
int age=Integer.parseInt(in.readLine());
System.out.print("Enter Mobile Number = ");
//reading long value by converting to long by parseLong method
long mobile=Long.parseLong(in.readLine());
System.out.print("Enter Salary = ");
//reading double value by converting to double by parseDouble method
double salary=Double.parseDouble(in.readLine());
System.out.print("Enter Bonus = ");
//reading float value by converting to float by parseFloat method
float bonus=Float.parseFloat(in.readLine());
System.out.print("Enter Marital Status, Married (true/false) = ");
//reading boolean value by converting to boolean by parseBoolean method
boolean MS=Boolean.parseBoolean(in.readLine());
System.out.print("Enter Gender, M/F = ");
//reading character value by read method and converting to character by type casting (char)
char gender=(char)in.read();
//Printing information read by different methods
System.out.println("\n\nPERSON RECORDS\n");
System.out.println("Name\t: "+name);
System.out.println("Age\t: "+age);
System.out.println("Mobile\t: "+mobile);
System.out.println("Salary\t: "+salary);
System.out.println("Bonus\t: "+bonus);
System.out.println("MStatus\t: "+MS);
System.out.println("Gender\t: "+gender);
}
}
Description
Difference between Read() and readLine() functions
Java has provided two functions read() and readLine() which helps us to take input from the user. Both these functions belong to the BufferedReader class. The difference is that read() function read only character whereas readLine() reads a string of characters.
The readLine() method will return a textual line (all text until at line break is found) read from the BufferedReader. If there is no more data to read from the underlying Reader, then the BufferedReader's readLine() method will return null .
The read() method of a Java BufferedReader returns an int which contains the char value of the next character read. If the read() method returns -1, there is no more data to read in the BufferedReader, and it can be closed.
OutputExample 3: Reading Data by Scanner class or java.util.Scanner class
This class is used for obtaining input by user for primitive types like int, double and strings. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions. Convenient methods for parsing primitives are nextInt(), nextFloat(), nextDouble() etc.
To read a string we use nextLine() and to read a single character we use next().charAt(0) function. next() function returns a word and charAt(0) function returns the first character from that word. To use the Scanner class, create an object of the class and pass the predefined object System.in to it, which represents the standard input stream.
Syntax
Scanner sc = new Scaneer(System.in);
System.in is an InputStream which read data from keyboard. Then we pass System.in to Scanner class which reads data from it.
//importing utility package in our program
import java.util.*;
class Person_Information
{
public static void main(String args[])
{
//Making object of Scanner class
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter Name = ");
//reading string value by readLine method
String name=sc.nextLine();
System.out.print("Enter Age = ");
//reading integer value by converting to integer by parseInt method
int age=sc.nextInt();
System.out.print("Enter Mobile Number = ");
//reading long value by converting to long by parseLong method
long mobile=sc.nextLong();
System.out.print("Enter Salary = ");
//reading double value by converting to double by parseDouble method
double salary=sc.nextDouble();
System.out.print("Enter Bonus = ");
//reading float value by converting to float by parseFloat method
float bonus=sc.nextFloat();
System.out.print("Enter Marital Status, Married (true/false) = ");
//reading boolean value by converting to boolean by parseBoolean method
boolean MS=sc.nextBoolean();
System.out.print("Enter Gender, M/F = ");
//reading character value by read method and converting to character by type casting (char)
char gender=sc.next().charAt(0);
//Printing information read by different methods
System.out.println("\n\nPERSON RECORDS\n");
System.out.println("Name\t: "+name);
System.out.println("Age\t: "+age);
System.out.println("Mobile\t: "+mobile);
System.out.println("Salary\t: "+salary);
System.out.println("Bonus\t: "+bonus);
System.out.println("MStatus\t: "+MS);
System.out.println("Gender\t: "+gender);
}
}
Output
Example 4: Reading Data by Command Line Arguments
Values that we pass to a program from outside of the program (from console) is known command line argument. These are supplied as parameters to the main method at the time of invoking it for execution. In java these are received by main method as String Array (String args[]).
Program
class Person_Information
{
public static void main(String args[])
{
//Printing information received by String Array (args)
System.out.println("\nInformation supplied is : \n");
for(String arguments:args)
{
System.out.println(arguments);
}
}
}
Output
import java.util.*;
class Salary_Calculation
{
public static void main(String args[])
{
//making object of scanner class
Scanner sc = new Scanner(System.in);
//reading basicSalary salary
System.out.print("\nEnter Basic Salary = ");
double basicSalary = sc.nextDouble();
//calculating DA and HRA
double DA = basicSalary*40/100;
double HRA = basicSalary*20/100;
double grossSalary = basicSalary+DA+HRA;
//printing result
System.out.println("\nDA = "+DA);
System.out.println("\nHRA = "+HRA);
System.out.println("\nGross Salary is "+grossSalary);
}
}
Output
class CalculateSide
{
public static void main(String args[])
{
//making object of scanner class
Scanner sc = new Scanner(System.in);
//reading values by user
System.out.print("Enter value of a = ");
int a = sc.nextInt();
System.out.print("Enter value of b = ");
int b = sc.nextInt();
System.out.print("Enter value of x = ");
int x = sc.nextInt();
//side calculation by math class functions
double side = Math.sqrt( ( Math.pow(a,2) + Math.pow(b,2) - 2*a*b) * Math.cos(x) );
//printing result
System.out.println("Side is "+side);
}
}
Output
class Person_Information
{
public static void main(String args[])
{
//Printing information received by String Array (args)
System.out.println("\nInformation supplied is : \n");
for(String arguments:args)
{
System.out.println(arguments);
}
}
}
Output
Simple Program
Question
Sameer’s Basic salary is input through the keyboard. His DA is 40% and HRA is 20% of basic salary. Calculate his gross salary.
Programimport java.util.*;
class Salary_Calculation
{
public static void main(String args[])
{
//making object of scanner class
Scanner sc = new Scanner(System.in);
//reading basicSalary salary
System.out.print("\nEnter Basic Salary = ");
double basicSalary = sc.nextDouble();
//calculating DA and HRA
double DA = basicSalary*40/100;
double HRA = basicSalary*20/100;
double grossSalary = basicSalary+DA+HRA;
//printing result
System.out.println("\nDA = "+DA);
System.out.println("\nHRA = "+HRA);
System.out.println("\nGross Salary is "+grossSalary);
}
}
Output
Exercise
- Enter length and width of rectangle and calculate area?
- Enter two numbers and swap them by the help of third variable.
- Enter two numbers and swap them without the help of third variable.
- Enter three subject marks and calculate their total and percentage
- The distance between two cities (in KM.) is input through keyboard and converts it into meter, feet, inches and centimetres.
- Temperature of a city in Fahrenheit degree is input through the keyboard and convert this temperature into centigrade degrees. Celsius=5/9.0*(f-32)
- A shopkeeper offers 10% discount on the printed price of a Digital Camera, however a customer has to pay 6% GST on the remaining amount. Write a program in java to calculate the amount to be paid by the customer taking printed price as input.
Simple Programs with use of Math class functions
Math class is present in java.lang package. This class contain static method so every method we have to use by class name. Most of the method of this class returns double type value. This class contain many usefull functions like pow() to calculate power, sqrt() to calcualte square root, max() to calculate minimum value etc.
Question
Question
Side=√(a2+b2-2ab)
cos(x)
Calculate the value of side by above formula
Program
import java.util.*;class CalculateSide
{
public static void main(String args[])
{
//making object of scanner class
Scanner sc = new Scanner(System.in);
//reading values by user
System.out.print("Enter value of a = ");
int a = sc.nextInt();
System.out.print("Enter value of b = ");
int b = sc.nextInt();
System.out.print("Enter value of x = ");
int x = sc.nextInt();
//side calculation by math class functions
double side = Math.sqrt( ( Math.pow(a,2) + Math.pow(b,2) - 2*a*b) * Math.cos(x) );
//printing result
System.out.println("Side is "+side);
}
}
Output
Exercise
- Ut+1/2ft2
- a3+b4+c5
- 3/4a3-2/7b4
- (0.05-2y3)/(x-y)
- p+q(r+s)4
- ci=p(1+r/100)t ßCompound Interest
- q√3+0.02√r
- b+√(b2-4ac)/2a
- 3/8√(b2-c3)
- √(a2+b2+c2 )
- (Cos x/tan x)+x
- 2-ye2y+4y // 2-y*Math.exp(2*y)+4*y
- |a|+b>=|b|+a //Math.abs(a)+b>=Math.abs(b)+a here abs i.e. absolute value
- Area=Ï€r2+2Ï€rhv
- Result=2m1m2/m1+m2*g
- x+=(y-=(-(4))); (x=2, y=4);
- Area of circle=Ï€r2
- Area of rectangle=length*breadth
- Perimeter of rectangle=2*(length + breadth)
- Circumference of circle = 2Ï€r
- Cuboid volume v = l*b*h
- Cylinder volume v = π r2h
- Cone volume = 1/3Ï€r2*h
Programming Basics
Character Set
Character set is a set of valid characters that a language can recognize. A character represents any letter, digit or any other sign.
Java supports Unicode character set. Which is a large pool of character contains around 65000 characters. Unicode is 16 bits character coding system. Its characters are collected from 24 languages of the world these languages are English, Chinese, Malayalam, roman, Italian etc.
first 128 character in the Unicode character set are identical to the common ASCII character set. We can refer to a particular Unicode character by using the escape sequence \u followed by a four digits hexadecimal number.
Java Tokens
Token is the smallest individual
unit of a program. The compiler recognized the tokens for building up
expression and statements. Java contains five types of tokens.
- Reserve words or key words or special words
- Identifiers
- Literals or Constant
- Separators
- Operators
Reserve words or key words or special words
These are the words that convey a special meaning to the language compiler. These are reserved for special purpose and must not be used as normal identifier names. Java contains around fifty key words. Example:- class, static, if, else, for, while etc. java is a case sensitive language so upper and lower case are treated separately. Example break is the key word while Break is not a key word because its B is capital.
Identifiers
Identifiers are fundamental building blocks of a program and are used generally to give name to different parts of the program viz. variable, objects, classes, functions and array etc. We have to follow some rules while declare identifiers, which are as follow:
- Identifier can have alphabets, digits, underscore and dollar sign characters.
- They must begin with an alphabet but never by a number.
- They must not be a key word or Boolean literal or null literal.
- The can be of any length.
- Java is case sensitive language so upper and lower case will be treated separately.
Literals
These are the fixed data values assigned to variables. These are also known as constant. These can be stored at a location in the memory and can be referenced through memory address. Java allows several kinds of literals.
- Integer literal
- Real literals
- Boolean literals
- Character literals
- String literals
- Null literals
Integer literal
These are whole numbers without any fractional part. For example 1200, 2500, 12542, +2521, -2365, 01362, 0415, 0x12, 0x32 etc. There are three types of integer literals.
Decimal Integer Literals
An Integer literals consisting of a sequence of digits are decimal integer literal. Example 1234, 2011, -90, +250 etc.
Octal Integer Literals
A sequence of digits starting with 0 is octal integer literal. Octal number system does not contain 8 and 9 digit. Example 1 will be written as 01, 7 will be written as 07 and 8 will be 010
Octal Number Table
Decimal
|
Octal
|
Decimal
|
Octal
|
1
|
01
|
17
|
021
|
2
|
02
|
23
|
027
|
----
|
-----
|
----
|
------
|
7
|
07
|
24
|
030
|
8
|
010
|
---
|
-----
|
9
|
011
|
63
|
077
|
10
|
012
|
64
|
0100
|
15
|
017
|
65
|
0101
|
----
|
------
|
66
|
0102
|
16
|
020
|
71
|
0107
|
Hexadecimal Integer Literals
A sequence of decimal numbers preceded by 0x or 0X is hexadecimal integer literal. Hexadecimal number system contain digits from 0-9 and character from A-F. In hexadecimal number system there is no digits from 10 to 15 these numbers are represented by A-F
Hexadecimal Number Table
Decimal
|
Hexadecimal
|
Decimal
|
Hexadecimal
|
0
|
0x0
|
27
|
0x1b
|
1
|
0x1
|
--
|
---
|
2
|
0x2
|
31
|
0x1f
|
9
|
0x9
|
32
|
0x20
|
10
|
0xa
|
33
|
0x21
|
11
|
0xb
|
34
|
0x22
|
12
|
0xc
|
35
|
0x23
|
13
|
0xd
|
41
|
0x29
|
14
|
0xe
|
48
|
0x30
|
15
|
0xf
|
49
|
0x31
|
16
|
0x10
|
50
|
0x32
|
17
|
0x11
|
51
|
0x33
|
18
|
0x12
|
57
|
0x39
|
19
|
0x13
|
144
|
0x90
|
20
|
0x14
|
256
|
0x100
|
--
|
--
|
257
|
0x101
|
25
|
0x19
|
274
|
0x112
|
26
|
0x1a
|
278
|
0x116
|
Real or Floating point literal
These are numbers having fractional parts. These contain one or more decimal digits, one decimal point (.) and optional suffix f or F for float and d or D for double. These may be written in one of the two forms called fractional form or the exponent form.
Fractional Form
Fractional Form
A real literal in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or – sign preceding it. A real literal with no sign is assumed to be positive. Following are the valid real literals in fractional form.
17.5, -13.2, -0.235, -12.0 etc.
Exponent Form
A real literal in exponent form has two parts. A mantissa and an exponent. The mantissa must be either an integer or a proper real literal. The mantissa is followed by a letter E or e the exponent. The exponent must be an integer. The following are the valid real literals in exponent form.
125e5, 1.56E7, 0.123e8, 124E+8, 120e-4, -0.124E-3 etc.
Exponent Form
A real literal in exponent form has two parts. A mantissa and an exponent. The mantissa must be either an integer or a proper real literal. The mantissa is followed by a letter E or e the exponent. The exponent must be an integer. The following are the valid real literals in exponent form.
125e5, 1.56E7, 0.123e8, 124E+8, 120e-4, -0.124E-3 etc.
Boolean Literal
The boolean literal has two values true and false. In Java the value of 1 is assumed as true and the value of 0 is assumed as false.
String Literal
A string literal is a sequence of characters surrounded by double quotes. These characters could be anything like letters, numbers or symbols which are enclosed within two quotation marks. Example of string literals are:
“abc”, “2011”, “+*-/”, “1-jan-2011”, “10/2/201”, “mohamad\amir”, “\sajid”, “iram\’s book” etc.
“abc”, “2011”, “+*-/”, “1-jan-2011”, “10/2/201”, “mohamad\amir”, “\sajid”, “iram\’s book” etc.
null Literal
A null literal represents null reference. A null literal is always of null type. It can be cast to any reference type, but not to any primitive type. It is impossible to declare a variable of this type.
Character Literal
A character literal is one character enclosed in single quotes. In java a character literal is sixteen bits (2 byte) Unicode characters, ranging from 0 to 65535. Character literals in Java are represented like this ( 'P' , '3' , '&' , 'Ï€' ).
Escape Sequence or Escape Character or Escape Code
An escape sequence is represented by a backslash (\) followed by one or more characters and has a special meaning to the java compiler. We use escape sequences to perform some specific task. Many non-graphic character which cannot
be typed directly from keyboard like backspace, tabs, enter, carriage return
etc. can be represented by escape sequences. Java contain 8 escape sequences.
Escape
Sequences
|
Non-graphic
character
|
\n
|
New Line
|
\t
|
Horizontal Tab
|
\b
|
Backspace
|
\r
|
Carriage Return
|
\’
|
Single Quote
|
\”
|
Double Quote
|
\\
|
Back Slash
|
\f
|
Form Feed
|
Program
class EscapeSequences
{
public static void main(String args[])
{
System.out.println("Java\nProgramming"); //for new line character
System.out.println("Java\tProgramming"); //for horizontal tab
System.out.println("Java\bProgramming"); //for back space
System.out.println("Welcome\rJava"); //for carriage return
System.out.println("Java\'Programming"); //for single quote
System.out.println("Java\"Programming"); //for double quote
System.out.println("Java\\Programming"); //for back slash
System.out.println("Java\fProgramming"); //for form feed
}
}
Output
Unicode Escape Sequences or Octal Escape Sequence
Unicode characters can be expressed through Unicode Escape Sequences but we should use this method when we can't represent these characters directly by keyboard. Unicode escape sequences are represented by an octal number preceded by \u. Unicode escapes sequences reduce program clarity and increase the potential for errors. Unicode escapes must be always well formed, even if they appear in comments, else compiler will raise an error. We can use Unicode escape sequence anywhere in our program including identifiers, comments, and string literals etc.
Program
class UnicodeEscapeSequences
class EscapeSequences
{
public static void main(String args[])
{
System.out.println("Java\nProgramming"); //for new line character
System.out.println("Java\tProgramming"); //for horizontal tab
System.out.println("Java\bProgramming"); //for back space
System.out.println("Welcome\rJava"); //for carriage return
System.out.println("Java\'Programming"); //for single quote
System.out.println("Java\"Programming"); //for double quote
System.out.println("Java\\Programming"); //for back slash
System.out.println("Java\fProgramming"); //for form feed
}
}
Output
Unicode Escape Sequences or Octal Escape Sequence
Unicode characters can be expressed through Unicode Escape Sequences but we should use this method when we can't represent these characters directly by keyboard. Unicode escape sequences are represented by an octal number preceded by \u. Unicode escapes sequences reduce program clarity and increase the potential for errors. Unicode escapes must be always well formed, even if they appear in comments, else compiler will raise an error. We can use Unicode escape sequence anywhere in our program including identifiers, comments, and string literals etc.
Unicode
Escape Sequences
|
Non-graphic
character
|
\007
|
Beep sound
|
\u0008
|
Backspace
|
\u0009
|
Horizontal Tab
|
\u005c\u005c
|
Back Slash
|
\u0027
|
Single Quote
|
\u005c\u0022
|
Double Quote
|
\u0000
|
Null Character
|
Program
class UnicodeEscapeSequences
{
public static void main(String args[])
{
System.out.println("Java\u0009Programming");//for horizontal tab
System.out.println("Java\u0008Programming");//for back space
System.out.println("Java\u0027Programming");//for single quote
System.out.println("Java\u005c\u0022Programming");//for double quote
System.out.println("Java\u005c\u005cProgramming");//for back slash
System.out.println("Java\u0000Programming");//for null character
System.out.println("\007");//for beep sound
//Different Number System Value Representation
System.out.println(07);//octal number
System.out.println(0x7);//haxadecimal
System.out.println(7);//decimal number
System.out.println(0xa); //haxadecimal
System.out.println(0xf); //haxadecimal
//Different Number System Value Representation
System.out.println(07);//octal number
System.out.println(0x7);//haxadecimal
System.out.println(7);//decimal number
System.out.println(0xa); //haxadecimal
System.out.println(0xf); //haxadecimal
}
}
Output
Separators or Punctuators
Separators are the symbols used to indicate where groups of code are divided and arranged. They basically define the shape of our code by separating part of code from each other. These sometimes connect or separate one or more tokens or organised a block of code.
( ) (parentheses) for functions
{ } (Braces) for block creation
[ ] (Bracket) for array dimension
; (Semicolon) for end of the statement
, (Comma) for separation of variable
. (Dot or period) for reference
Operators
An operator is a symbol that tells the computer to perform certain mathematical or logical or relational operations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical expression. Operators are of three types.
Unary Operator
Operator which require single operand for their working are known as unary operator. These operators are either on left side or right side of operands. Example + +, - -
Unary operator are of two types. Pre-Increment, Pre-Decrement and Post Increment, Post Decrement.
Example
number=3
pre_increment = ++number
= 4
post_increment = number++
= 3
Question 1
a=4, b=3;
a=a+(a++ * 6 + ++b*5+10);
Solution
a=4+(4*6+4*5+10);
a=4+(24+20+10);
a=4+(44+10);
a=4+54
a=58
Program
class UnaryOperator
{
public static void main(String args[])
{
int a=4, b=3;
a=a(+a++ * 6 + ++b*5+10);
System.out.println(a);
}
}
Output
Program
class UnaryOperator
{
public static void main(String args[])
{
int a=4, b=3;
a=a(+a++ * 6 + ++b*5+10);
System.out.println(a);
}
}
Output
Question 1: Use of Shorthand Operator (*=)
a=12,b=8;
a*=++a/6+b++%3;
a*=++a/6+b++%3;
Exercise
int x=1,y=2,z=3;
- i = ++x + --y;
- i = x++ + --y;
- i = ++x - y-- * 2;
- i = x/2 * 5 - --y;
- r = x - (y++)* (--z);
- r = (5 * ++z) * y - x;
- r = (5 * ++z) % 6;
- f = (++a)* b - a (a=4, b=2)
- c = a -(b++) * (--a) (a=4, b=2)
- c = (a++)* d + a (a=4, d=2)
- a-=++a + a++ +4; (a=8)
- x+=x++ * ++x%2 (x=4)
- a+=b++ *5/a++; (a=48, b=13)
- p+=q++ /p*r++ % (p+q); (p=13, q=8, r=2)
- k/= ++m - n++ /k; (K=5, m=7, n=3)
Binary Operator
Operator which require two operands for their working are known as binary operator. These operators remain sandwiched between of two operands. Example +, -, /, *, %, < , >, =, != etc.
Arithmetic Operator
a=mb*3/4+k/4+8-mb+5/8; (mb=5, k=19)
a=5*3/4+19/4+8-5+5/8;
a=15/4+19/4+8-5+5/8;
a=3+19/4+8-5+5/8;
a=3+4+8-5+5/8;
a=3+4+8-5+0;
a=7+8-5+0;
a=15-5+0;
a=10+0;
a=10;
Truth Table for Logical OR (||) Operator
Logical NOT Operator (!)
Operator which we use for arithmetical operation like addition (+), subtraction (-), multiplication (*), division (/), modulus (%) etc. are called arithmetical operators. These operators needs numeric operands for their working we can not use them for boolean types.
Examplea=mb*3/4+k/4+8-mb+5/8; (mb=5, k=19)
a=5*3/4+19/4+8-5+5/8;
a=15/4+19/4+8-5+5/8;
a=3+19/4+8-5+5/8;
a=3+4+8-5+5/8;
a=3+4+8-5+0;
a=7+8-5+0;
a=15-5+0;
a=10+0;
a=10;
Exercise
- 8+4*6-8/4
- 3*4/2+3-1
- 21/3+6%2
- (5/3)*3+5%3
- 14%3+7%2
- ((x-(y/5)+z)%8)+25 (x=9,y=3,z=7) Note: Innermost bracket will open first
- J= --k+2*k+(l=k, l++) if k is 20
- p=p*++j where j=22, p=3
- a+b-(c+d)*3%e+f/9 (a=8, b=4, c=2, d=1, e=5, f=20)
- a%6-b/2+(c*d-5)/e (a=17, b=5, c=6, d=3, e=5)
These operators are used for comparison of two variables or two values. Comparison can be for less than, greater than, equality, non-equality operations. These operators return boolean value either true or false. These operators are used with integer and char types but not with boolean types. Relation al operators are < (lesser than), > (greater than), = (equals), != (not equals), <= (less than or equals), >= (greater than or equals).
Example
a*b-c/d<e+f
(a=4, b=5, c=6, d=3, e=5,f=10)
(a=4, b=5, c=6, d=3, e=5,f=10)
4*5-6/3<5+10
20-6/3<5+10
20-2<5+10
18<15
False
Exercise
- x>y (x=6,y=3)
- (y+z)>=(x/z) (x=5,y=0,z=2)
- p*q/r == (p+q)-r (p=2, q=8, r=3)
- x-y/z <= x/z+y (x=5, y=9, z=1)
- a-b+c/d==e/f-g+h%k (a=8, b=5, c=8, d=3, e=65, f=10, g=2, h=5, k=2)
- (a+b-c)/d!=(a%b)+c (a=2, b=4, c=6)
- (-y) (y=3)
- (x-y) (x=6,y=1)
- (x) (x=6)
Logical Operator
Logical operators are used to perform logical operation which are “AND”, “OR” and “NOT”. These operators always return boolean values. These operators are used to combine two or more conditions. In logical operator Second condition is not evaluated if the first one is false. These operators are used extensively (on a large scale) to test conditions for making decision.
Logical AND Operator(&&)
This operator returns true when both the conditions under testing are true. If even one of the two conditions return false, the operator returns false.
Syntax
condition_1 && condition_2
Truth Table for Logical AND (&&) Operator
Condition 1
|
AND (&&)
|
Condition 2
|
Result
|
T
|
&&
|
T
|
T
|
F
|
&&
|
T
|
F
|
T
|
&&
|
F
|
F
|
F
|
&&
|
F
|
F
|
Logical OR Operator (||)
This operator returns true when one of the two conditions under testing are true. To make the result false, both condition need to return false.
Syntax
condition_1 || condition_2
Condition 1
|
OR (||)
|
Condition 2
|
Result
|
T
|
||
|
T
|
T
|
F
|
||
|
T
|
T
|
T
|
||
|
F
|
T
|
F
|
||
|
F
|
F
|
It is a unary operator and returns true when condition under testing is not satisfied. Basically, if condition is false, it returns true and when the condition is true, it returns false.
Syntax
!(condition)
Truth Table for Logical NOT (!) Operator
Condition
|
NOT (!)
|
Result
|
T
|
!
|
F
|
F
|
!
|
T
|
Priority of Logical Operator
NOT Ã AND Ã OR
Example
a/20==0.0 && b/2.0!=0.0||c<0.0
(a=11,b=13,c=7)
11/20==0.0 && 13/2.0!=0.0 || 7<0.0
0==0.0 && 6.5!=0.0 || 7<0.0
True && True || False
True || False
True
Bitwise AND (&)
1 | 1 = 1
0 | 1 = 1
1 | 0 = 1
0 | 0 = 0
Example
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
0 ^ 0 = 0
Example
~ 1 = 0
~ 0 = 1
Example
int n =12;
Operator which require three operands for their working are known as ternary operator. These are also called conditional operator because these operators make conditional construct. There is only one conditional operator that is (:?) and it is an alternative to if else.NOT Ã AND Ã OR
Example
a/20==0.0 && b/2.0!=0.0||c<0.0
(a=11,b=13,c=7)
11/20==0.0 && 13/2.0!=0.0 || 7<0.0
0==0.0 && 6.5!=0.0 || 7<0.0
True && True || False
True || False
True
Exercise
1) (a+b)>c && (c+d)>a (a=5, b=7, c=1, d=6)
2) b>15 && c<0 || a>0 (a=7, b=3, c=8)
3) (x>y) && (!y<z) (x=9, y=3, z=5)
4) x||y && z (x=5, y=3, z=1)
5) x<=!y && z (x=9, y=3, z=5)
6) a==c || b>a (a=11,b=13,c=7)
7) a-b || (a-b*c) + d && e-f%3 (a=8, b=3, c=2, d=3, e=2, f=11)
8) b>15 && c<0 ||a>0 (a=3, b=14, c=5)
9) (a/20==0.0 && b/2.0!=0.0)||c<0.0 (a=3, b=14, c=5)
10) (a+b)>c && (c+d)>a (a=3, b=14, c=5, d=9)
11) (x>y) && (!y<z) (x=3, y=7, z=9)
12) x<=!y && z (x=3, y=7, z=9)
13) (y+x) || (z<y) (x=2, y=1, z=4)
13) (y+x) || (z<y) (x=2, y=1, z=4)
Bitwise operator
These operators work on binary values or bits and return numerical result. We can apply these operator on long, int, short, char and byte types. These operator work on a binary equivalent of decimal numbers and perform operations on them bit by bit according to these steps.
- First operands are converted to binary values.
- Next operator is applied to each binary number and the result is calculated.
- Finally result is converted back to decimal number.
This operator compares each binary digit of two integers and gives back 1 if both are 1, otherwise it returns 0. This is similar to the AND (&&) operator with boolean values. When the values of two boolean are true the result of AND (&&) operation is true otherwise false.
Truth Table
1 & 1 = 1
0 & 1 = 0
1 & 0 = 0
0 & 0 = 0
Example
13 = 0 1 1 0
1
&
25 = 1 1 0 0 1
09 = 0 1 0 0 1 (0*24+1*23+0*22+0*21+1*20
= 0+8+0+1 = 9)
Exercise
- 16 & 20
- 19 & 23
- 38 & 45
- 55 & 17
- 11 & 35
This operator compares each binary digit of two integers and gives back 1 if any value is 1, otherwise it returns 0. This is similar to the OR (|) operator with boolean values. When the value of one boolean is true the result of OR (|) operation is true otherwise false.
Truth Table 1 | 1 = 1
0 | 1 = 1
1 | 0 = 1
0 | 0 = 0
Example
13 = 0 1 1 0 1
|
25 = 1 1 0 0 1
29 = 1 1 1 0 1 (1*24+1*23+1*22+0*21+1*20 = 16+8+4+0+1 = 29)
Exercise
- 16 | 20
- 19 | 23
- 38 | 45
- 55 | 17
- 11 | 35
This operator compares each binary digit of two integers and returns 1 if odd number of 1 is found, otherwise it returns 0. It is totally different from AND (&) operator and OR operator (|).
Truth Table 1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
0 ^ 0 = 0
Example
13 = 0 1 1 0 1
^
25 = 1 1 0 0 1
20 = 1 0 1 0 0 (1*24+0*23+1*22+0*21+0*20 = 16+0+4+0+0 = 20)
Exercise
- 16 ^ 20
- 19 ^ 23
- 38 ^ 45
- 55 ^ 17
- 11 ^ 35
Bitwise Not or Bitwise Complement (~)
It inverts bit pattern i.e. it changes each binary digit of the integer, which means all 0 become 1 and all 1 become 0. It is just like logical NOT (!) which converts true to false and false to true. It is unary operator and takes only one integer.
Truth Table ~ 1 = 0
~ 0 = 1
Example
13 = 1 1 0 1
~13 = 0 0 1 0
Exercise
- ~16
- ~19
- ~38
class BitwiseOperators
{
public static void main(String args[])
{
int a=13, b=25;
System.out.println("AND\t" +a +" & "+ b +"=> "+(a&b));
System.out.println("OR\t" +a +" | "+ b +"=> "+(a|b));
System.out.println("EXOR\t"+a +" ^ "+ b +"=> "+(a^b));
}
}
Output
Shift operator
A shift operator performs bit manipulation on data by shifting the bits of its first operand right or left. Each operator shifts the bits of the first operand over by the number of positions indicated by the second operand. The shift occurs in the direction indicated by the operator itself. Shift operators are of three types in java.
Bitwise Left Shift Operator (<<)
Left shift operator shifts the bits towards left a specified number of positions. The symbol for this operator is <<. When we write NUMBER<<n it means, to shift the bits of NUMBER towards left n specified positions.
Example
int n =12;
n<<2
Binary value of 12 = 1100
1
|
1
|
0
|
0
|
after two bit shift from 12
12<<2
1
|
1
|
0
|
0
|
0
|
0
|
1*25+1*24+0*23+0*22+0*21+0*20
= 32+16+0+0+0+0 = 48
after conversion of bitwise value into decimal result will be like this
12<<2 = 48
Bitwise Right Shift Operator (>>) or Signed Right Shift Operator (>>)
Right shift operator shifts the bits towards Right a specified number of positions. The symbol for this operator is >>, When we write NUMBER>>n it means, to shift the bits of NUMBER towards right n specified positions.
Example
int n =12;
n>>2
Binary value of 12 = 1100
1
|
1
|
0
|
0
|
after two bit shift from 12
12>>2
1
|
1
|
1*21+1*20 = 2+1 = 3
after conversion of bitwise value into decimal result will be like this
12>>2 = 3
Bitwise Zero Fill Right Shift Operator (>>>) or Unsigned Right Shift Operator (>>>)
Zero Fill Right shift operator shifts the bits towards Right a specified number of positions. The symbol for this operator is >>>, When we write NUMBER>>>n it means, to shift the bits of NUMBER towards right n specified positions.
When we apply >>> on a positive number, it gives the same output as that of >>. It gives a positive number when we apply >>> on a negative number because MSB (sign bit) is replaced by a 0. So it can never result in a negative number because the sign bit will always be filled with a zero.
Exampleint n =12;
n>>>2
Binary value of 12 = 1100
1
|
1
|
0
|
0
|
after two bit shift from 12
12>>>2
0
|
0
|
0
|
0
|
0
|
0
|
1
|
1
|
1*21+1*20 = 2+1 = 3
after conversion of bitwise value into decimal result will be like this
12>>>2 = 3
For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions by >> operator.
Assume if a = 60 and b = -60; now in binary format, they will be as follows −
a = 0000 0000 0000 0000 0000 0000 0011 1100
b = 1111 1111 1111 1111 1111 1111 1100 0100
In Java, negative numbers are stored as 2's complement.
Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010
The unsigned right shift operator '>>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s.
Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >>> 1 = 0111 1111 1111 1111 1111 1111 1110 0010
Difference between >> and >>> operator
Both >> and >>> are used to shift the bits towards the right. The difference is that the >> preserve the sign bit while the operator >>> does not preserve the sign bit. To preserve the sign bit, you need to add 0 in the MSB (Sign bit).
For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions by >> operator.
Assume if a = 60 and b = -60; now in binary format, they will be as follows −
a = 0000 0000 0000 0000 0000 0000 0011 1100
b = 1111 1111 1111 1111 1111 1111 1100 0100
In Java, negative numbers are stored as 2's complement.
Thus a >> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >> 1 = 1111 1111 1111 1111 1111 1111 1110 0010
The unsigned right shift operator '>>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s.
Thus a >>> 1 = 0000 0000 0000 0000 0000 0000 0001 1110
And b >>> 1 = 0111 1111 1111 1111 1111 1111 1110 0010
Program
class ShiftOperators
{
public static void main(String args[])
{
int a=12;
int b=-12;
System.out.println("Left Shift Operator\t a << 2 -> "+(a<<2));
System.out.println("Right Shift Operator\t a >> 2 -> "+(a>>2));
System.out.println("Zero Fill Right Shift\t a >>> 2 -> "+(a>>>2));
System.out.println("Zero Fill Right Shift\t b >>> 2 -> "+(b>>>2));
}
}
Output
Ternary Operator
Result = Condition ? True : False
Example 1
Write a program to find greater number between two by conditional operator.
Program
import java.util.*;
class GreaterNumberCheck
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading number by user
System.out.print("Enter First Number = ");
int number1 = sc.nextInt();
System.out.print("Enter Second Number = ");
int number2 = sc.nextInt();
//checking for greater number
int greater = number1>number2?number1:number2;
//printing result
System.out.println("Greater Number is "+greater);
}
}
Output
Example 1
Write a program to input age of a person and check whether he can vote or not. If age of a person is greater than 18 years he can vote otherwise can not vote.
Program
import java.util.*;
class VotingTest
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//reading age by user
System.out.print("Enter age of a person = ");
int age =sc.nextInt();
//testing age and printing message
System.out.println(age>=18?"Can Vote":"Can not vote");
}
}
Output
Exercise
- Write a program to enter selling price and cost price of an item and check whether seller has made profit or loss.
- Write a program to enter a number and check whether number is even or odd. Number divisible by 2 is even otherwise odd.
- Write a program to enter a number and check whether number is positive or negative. Number greater than 0 is positive.
- Write a program to enter a year and check whether it is leap year or not. Year divisible by 4 is leap year.
- Write a program to print commission of an employee, If annual salary of an employee is more than 1 lack then his commission will be 10% else commission will be 5% of annual salary.
Nested Conditional operator
One Conditional operator can be nested into another conditional operator in java programming. But we have to keep in mind nesting of conditional operator hinder readability. So we have to do it very carefully.
Syntax
Result = Condition? (condition?True : False ) : (Condition? True : False)
Syntax
Result = Condition? (condition?True : False ) : (Condition? True : False)
Example
Enter three number and find greatest number among them by nested conditional operator.
Program
import java.util.*;
class GreatestNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//Reading three number by user
System.out.println("Enter three numbers ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
//testing greatest number by nested conditional operator
int result = a>b?(a>c?a:c):(b>c?b:c);
//printing result
System.out.println("Result is "+result);
}
}
Output
Enter three number and find greatest number among them by nested conditional operator.
Program
import java.util.*;
class GreatestNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//Reading three number by user
System.out.println("Enter three numbers ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
//testing greatest number by nested conditional operator
int result = a>b?(a>c?a:c):(b>c?b:c);
//printing result
System.out.println("Result is "+result);
}
}
Output
Exercise
- Write a program to enter a number and check number is even or odd and positive or negative. A number which is greater than 0 is positive and number divisible by 2 is even.
- Write a program to enter a year and check year is leap or not and century year or not. A year divisible by 4 is leap year and year divisible 100 is century year.
- Write a program to enter a number and check number is divisible by 2 and 5 or not. Print an appropriate message.
Precedence and Associativity of Operator
Precedence
Operator precedence determines the order in which the operators in an expression are evaluated. When two operators share an operand the operator with the higher precedence goes first. Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has multiple operators. For example, addition and subtraction have lower precedence than multiplication and division.
Precedence rules can be overridden by explicit parentheses. For example, 2 + 3 / 8 is treated as 2 + (3 / 8), whereas 5 / 3 + 2 is treated as (5 / 3) + 2 since division has a higher precedence than addition.
Associativity
If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left).
For example a = b = c = 10 is treated as a = (b = (c = 10)), leaving all three variables with the value 10, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side).
On the other hand, 2 * 3 * 5 is treated as (2 * 3) * 5 since the * operator has left-to-right associativity.
Some operators are not associative: for example, the expressions (a >= b >= c) and --++p are invalid.
Table with precedence and associativity of Java operators
This table shows all Java operators from highest to lowest precedence, along with their associativity.
Operator
|
Precedence
|
Associativity
|
access array element
access object member parentheses |
[]
. () |
left to right
|
Post increment, decrement
|
++ --
|
not associative
|
Pre increment, decrement
unary plus, minus unary logical NOT unary bitwise NOT |
++ --
+ - ! ~ |
right to left
|
object creation
|
new
|
right to left
|
multiplicative
|
* / %
|
left to right
|
additive
|
+ -
|
left to right
|
shift
|
<< >> >>>
|
left to right
|
relational
|
< <= > >=
instanceof |
not associative
|
equality
|
== !=
|
left to right
|
bitwise AND, XOR, OR
|
& ^ |
|
left to right
|
logical AND, OR
|
&& ||
|
left to right
|
ternary
|
?:
|
right to left
|
assignment
|
= += -=
*= /= %= &= ^= |= <<= >>= >>>= |
right to left
|
Example
a+b-(c+d)*3%e+f/9
(a=8, b=4, c=2, d=1, e=5, f=20)
=8+4-(2+1)*3%5+20/9
=8+4-3*3%5+20/9
=8+4-9%5+20/9
=8+4-4+20/9
=8+4-4+2
=12-4+2
=8+2
=10
Exercise
1. 8+4*6-8/4
2. a=mb*3/4+k/4+8-mb+5/8 (mb=5, k=19)
3. ((x-(y/5)+z)%8)+25 (x=9,y=3,z=7)
4. J= --k+2*k+(l=k, l++) if k is 20
5. b>15 && c<0 ||a>0 (a=3,b=14, c=5)
6. x<=!y && z (x=3,y=7,z=9)
7. a-b+c/d==e/f-g+h%k (a=8, b=5, c=8,d=3, e=65, f=10, g=2, h=5, k=2)
8. a-b || (a-b*c) + d && e-f%3 (a=8, b=3, c=2, d=3, e=2, f=11)
2. a=mb*3/4+k/4+8-mb+5/8 (mb=5, k=19)
3. ((x-(y/5)+z)%8)+25 (x=9,y=3,z=7)
4. J= --k+2*k+(l=k, l++) if k is 20
5. b>15 && c<0 ||a>0 (a=3,b=14, c=5)
6. x<=!y && z (x=3,y=7,z=9)
7. a-b+c/d==e/f-g+h%k (a=8, b=5, c=8,d=3, e=65, f=10, g=2, h=5, k=2)
8. a-b || (a-b*c) + d && e-f%3 (a=8, b=3, c=2, d=3, e=2, f=11)
Data Type
Data type specifies the size and values that can be stored in a variable. There are two types of data types in Java programming.
Primitive data types
The fundamental data types that are already present in java language are called primitive type data types. These are the building blocks of data manipulation. These are the most basic data types available in Java Language. The primitive data types include byte, short, int, long, float, double, char and boolean.
Non-primitive data types
Non-primitive data types are called reference types because they hold reference/address of an object or a set of objects. The non-primitive data types include Classes, Interfaces, and Arrays.
The main difference between primitive and non-primitive data types
- Primitive types are predefined (already defined) in Java Language. Non-primitive types are created by the programmer and is not defined by Java Programming. String is the only data type which is Non-Primitive and is already defined.
- The size of a primitive type is different and depends on the data type used, while non-primitive types have all the same size.
- Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
- A primitive type has always a value, while non-primitive types can be null.
Primitive data types
Data Type
|
Size
|
Minimum value
|
Maximum value
|
Type of value
can hold
|
|
Integer: Stores
whole numbers without decimal point
|
|||||
byte
|
1 byte (8-bits)
|
-128
|
127
|
Stores whole numbers
|
|
short
|
2 byte (16-bits)
|
-32768
|
32767
|
Stores whole numbers
|
|
int
|
4 byte (32-bits)
|
-2,147,483,648
|
2,147,483,647
|
Stores whole numbers
|
|
long
|
8 byte (64-bits)
|
-263
|
263-1
|
Stores whole numbers
|
|
Real: Stores
fractional numbers only i.e. numbers with decimal point
|
|||||
float
|
4 bytes (32 bits)
|
3.4 e -38
|
+3.4 e +38
|
Stores fractional numbers with
precision up to 6 digits
|
|
double
|
8 bytes (64 bits)
|
1.7 e -308
|
+1.7 e +308
|
Stores fractional numbers with
precision up to 15 digits
|
|
Character: Stores
single character (alphabet, digit, symbol, ASCII Value) enclosed in single
quote
|
|||||
char
|
2 bytes (16 bits)
|
Single character
|
Stores single character with
single quote.
|
||
Boolean: Stores
logical value true and false
|
|||||
boolean
|
1 byte (8 bits)
|
True or false
|
Can hold only logical data i.e.
true or false.
|
||
Example
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE);
System.out.println(Short.MAX_VALUE);
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Short.MIN_VALUE);
System.out.println(Short.MAX_VALUE);
We can Fine size of a primitive type by SIZE functions of wrapper classes.
Example
System.out.println(Double.SIZE);
System.out.println(Integer.SIZE);
Example
System.out.println(Double.SIZE);
System.out.println(Integer.SIZE);
Type Conversion
The process of conversion one primitive type into another primitive type is called type conversion.There are two types of conversion.
Implicit Type Conversion
When we convert a lower primitive type into higher primitive type then it is known as implicit type conversion. It is automatic type conversion done by java itself without intervention of programmer, so known as automatic type conversion. This conversion is done when different data types are intermixed in an expression, so as not to lose information. In this conversion java compiler converts all operands into the type of the largest operand. It is based on some rules:
- If either operand is of type double, the other is converted to double.
- If either operand is of type float, the other is converted to float.
- If either operand is of type long, the other is converted to long.
In this conversion where primitive types are promoted from lower to higher, so it is also known as type promotion or coercion. It is also known as widening conversion as data type converted from narrow (lower) data type to wide (big) data type. For example conversion from integer to double and from float to double etc.
Explicit Type Conversion or Type Casting
When we convert bigger data type into smaller data type then it is known as explicit type conversion. The explicit type conversion is user defined that forces an expression to be of specific type.
It is known as type casting because it cast (convert) the value to be a specific type by proceeding it with the type name in parentheses. This is useful for incompatible data types where automatic conversion cannot be done.
It is also known as narrowing conversion because data demote from higher type to lower (narrow) type. Programmer have to do it forcefully so it is also called force conversion. For example conversion of double to int and conversion of double to short.
Syntax
(type) expression
Example
class TypeCasting
{
public static void main(String args[])
{
int number=2,result;
//Type Casting from double to int, Math.pow() function return double value
result=(int)Math.pow(number,2);
System.out.println(result);
}
}
Output
Variable
A variable is a named memory location that holds a data value of a particular data type, whose value is manipulated during the program run. It is a combination of vary + able that means its value can very (changed) due to this reason it is called variable.
Variables are typically used to store information which your program needs to do its job. This information can be texts, numbers, results etc. variable is the basic unit of storage in a program.
- variable value can be changed during program execution.
- A variable is a name given to a memory location, So all the operations done on the variable effects that memory location.
- All variables must be declared before use.
data type variable name;
Example
int salary;
double salary, commission;
Declaration and Assignment (Static Initialization)
int age=25;
int age=25, salary=4500, code=1001;
int a=b=c=10;
float salary, bonus;
salary=1000.00;
bonus=500.00;
Dynamic initialization
Class obj = new Class Constructor();
Scope of variables
The program area where a variable is accessible is known as scope of that variable. On the basis of scope variable can be classified into three categories.
Local Variable
A variable declared inside the body of the method is called local variable. This variable is accessible only within that method and the other methods in the class can not use this variable.
Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. These are created when the objects are created and therefore they are associated with their objects. They are in scope as long as their object is in scope. They can take different value for each object.
Static variable or Class Variable or Global Variable
Variables declared inside class with static keyword are known as Static variable. These are belongs to the entire set
of objects that class creates. So these are also called global variable or Class variable. Only one memory location is created for such
variable. Memory allocation for static variable happens only once when the class is loaded in the memory.
Program
class VariableScope
{
int a;//Instance Variable
static int b;//static or global variable
public static void main(String args[])
{
int a=10;//local variable
}
}
Comments
Post a Comment