Java Programming in JAVA (CSE2006) PDF
Document Details
Uploaded by ExtraordinaryTranscendental
VIT Bhopal University
Dr. Hemraj
Tags
Summary
This presentation provides an overview of fundamental programming concepts in Java, including syntax and data types, and showcases the applications of Java in various fields. It likely serves as lecture notes for an undergraduate computer science course at a university in India.
Full Transcript
Programming in JAVA Dr. Hemraj Cryptologist, VIT Bhopal University, Madhya Pradesh, India. Dr. Hemraj CSE2006 – Programming in JAVA JAVA Java is a high Level programming language and i...
Programming in JAVA Dr. Hemraj Cryptologist, VIT Bhopal University, Madhya Pradesh, India. Dr. Hemraj CSE2006 – Programming in JAVA JAVA Java is a high Level programming language and it is also called as a platform. Java is a secured and robust high level object-oriented programming language. Platform: Any software or hardware environment in which a program runs is known as a platform. Java has its own runtime environment (JRE) and API so java is also called as platform. Java follows the concept of Write Once, Run Anywhere. Dr. Hemraj CSE2006 – Programming in JAVA 3 Introduction Java is a very powerful language that has generated a lot of interest in the last years. Java Embedded device The HotJava browser Cloud Dr. Hemraj CSE2006 – Programming in JAVA 2 Introduction It is a general purpose concurrent object oriented language, with a syntax similar to C and C++, but omitting features that are complex and unsafe. C++ Java Backward compatile con C Backward compatibility with previous Java versions Execution efficiency Developer productivity Trusts the programmer Protects the programmer Arbitrary memory access possible Memory access through objects Concise expression Explicit operation Can arbitrarily override types Type safety Procedural or object oriented Object oriented Operator overloading Meaning of operators immutable Dr. Hemraj CSE2006 – Programming in JAVA 3 Introduction The world wide web has popularized the use of Java, because programs can be transparently downloaded with web pages and executed in any computer with a Java capable browser. A Java application is a standalone Java program that can be executed independently of any web browser. A Java applet is a program designed to be executed under a Java capable browser. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Web Applications: Java powers web applications through frameworks like Spring and Struts. Popular platforms like LinkedIn and Amazon use Java for their backend systems. Mobile Applications: Java is the primary language for developing Android apps, making it a dominant player in the mobile app development space. Enterprise Applications: Java EE (Enterprise Edition) is used by large corporations for building scalable, distributed enterprise applications like ERP systems. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Desktop GUI Applications: Java provides frameworks like JavaFX and Swing for building cross-platform desktop applications with graphical user interfaces. Scientific Applications: Java is used in scientific computing due to its robustness and ability to handle complex calculations and simulations. Big Data Technologies: Java is integral to big data technologies like Apache Hadoop and Apache Spark, which are used for large-scale data processing. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Financial Services: Many banks and financial institutions rely on Java for creating secure, high-performance trading and banking systems. Cloud Computing: Java plays a key role in cloud platforms, including Amazon Web Services (AWS), Google Cloud, and Azure, enabling enterprise cloud- based applications. IoT Applications: Java's versatility makes it suitable for Internet of Things (IoT) applications, from smart homes to industrial automation systems. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Gaming Applications: Java is used in game development, including popular online games like Minecraft, due to its portability and stability. Web Servers and Application Servers: Java is the backbone of many web and application servers, such as Apache Tomcat, JBoss, and WebLogic. E-commerce Platforms: Java is widely used in the development of online shopping systems like eBay and payment gateways. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Content Management Systems (CMS): Java powers various CMS platforms such as Alfresco and Magnolia for enterprise content management. Artificial Intelligence: Java is used in AI projects, including machine learning libraries like Deeplearning4j for building neural networks and performing deep learning. Healthcare Applications: Java is employed in building healthcare information systems (HIS) and patient record management systems. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Blockchain Applications: Java is used in building blockchain solutions due to its security features, making it ideal for developing smart contracts and cryptocurrency platforms. Mobile Payment Systems: Java is used in secure mobile payment platforms, particularly in mobile banking applications and online wallets. Stock Market Applications: Financial platforms that handle stock trading and analysis, like Murex, use Java for processing huge amounts of financial data. Dr. Hemraj CSE2006 – Programming in JAVA 4 Application of JAVA Networking Applications: Java powers networking tools like OpenNMS and JMX for managing network resources and monitoring performance. Simulation Systems: Java is used in creating simulation software for various industries, such as aviation, healthcare, and manufacturing, for real-time systems and training. Dr. Hemraj CSE2006 – Programming in JAVA 4 Features of Java Object Oriented – Java implements basic concepts of Object oriented programming System (OOPS) ie Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation. In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. Simple – Java fallows the basic Syntax of C,C++. If you understand the basic concept of OOPS then it is easy to master in java. Dr. Hemraj CSE2006 – Programming in JAVA Features of Java Secure – With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Dr. Hemraj CSE2006 – Programming in JAVA Features of Java Multithreaded − With Java's multithreaded feature In java we can write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light- weight process. High Performance − With the use of Just-In-Time compilers, Java enables high performance. Distributed − Java is designed for the distributed environment of the internet. Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Dr. Hemraj CSE2006 – Programming in JAVA Object Oriented Programming System(OOPS) Object means a real word entity such as pen, chair, table etc. Object- Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts. ✓ Object ✓ Class ✓ Inheritance ✓ Polymorphism ✓ Abstraction ✓ Encapsulation If any language follows the OOPS concepts that language we call it as object oriented language. Dr. Hemraj CSE2006 – Programming in JAVA Procedure to write simple java Program To write a java program First we have install the JDK. To create a simple java program, you need to create a class that contains main method. Let's understand the requirement first. ✓ Install the JDK and install it. ✓ set path of the jdk ✓ Use any editor (notepad++, gedit, atomeditor, visual studio code, etc) ✓ create the java program ✓ compile and run the java program ✓ Download java from: https://www.oracle.com/java/technologies/downloads/#jdk18- windows https://download.oracle.com/java/22/latest/jdk-22_windows- x64_bin.exe Dr. Hemraj CSE2006 – Programming in JAVA Setting Up the Path for Windows Assuming you have installed Java in c:\Program Files\java\jdk directory − ✓ Right-click on 'My Computer' and select 'Properties'. ✓ Click the 'Environment variables' button under the 'Advanced' tab. ✓ Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'. For LINUX: open bashrc: export PATH = /path/to/java:$PATH' Dr. Hemraj CSE2006 – Programming in JAVA Setting Up the Path for Windows setx /n JAVA_HOME "C:\Program files\Java\Jdk..." echo %JAVA_HOME% now for path edit environment variables add new %JAVA_HOME%\bin Dr. Hemraj CSE2006 – Programming in JAVA The Java platform Java programs are compiled to Java byte-codes, a kind of machine independent representation. The program is then executed by an interpreter called the Java Virtual Machine (JVM). Test.java Test.class Interpreter (JVM) Compiler Dr. Hemraj CSE2006 – Programming in JAVA 5 The Java platform The compiled code is independent of the architecture of the computer. The price to pay is a slower execution. Test.java Test.class Interpreter (JVM) Interpreter (JVM) Compiler Interpreter (JVM) Dr. Hemraj CSE2006 – Programming in JAVA 6 A first example public class HelloVit { public static void main(String[] args) { System.out.println("Hello VIT"); // display output } } > javac HelloVit.java > dir HelloVit.class HelloVit.java > java HelloVit Hello VIT Dr. Hemraj CSE2006 – Programming in JAVA 7 Fundamental types Java provides ten fundamental types: – integers: byte, short, int and long – floating point: float and double. – characters: char. – boolean – void – String Dr. Hemraj CSE2006 – Programming in JAVA 10 Variables The variables are declared specifying its type and name, and initialized in the point of declaration, or later with the assignment expression: int x; double f = 0.33; char c = ’a’; String s = "VIT"; x = 55; Dr. Hemraj CSE2006 – Programming in JAVA 11 Literals The integer values can be written in decimal, hexadecimal, octal and long forms: int x = 34; // decimal value int y = 0x3ef; // hexadecimal int z = 0772; // octal long m = 240395922L; // long The floating point values are of type double by default: double d = 6.28; // 6.28 is a double value float f = 6.28F; // 6.28F is a float value Dr. Hemraj CSE2006 – Programming in JAVA 12 Literals The character values are specified with the standard C notation, with extensions for Unicode values: char c = ’a’; // character lowercase a char d = ’\n’; // newline char e = ’\u2122’ // unicode character (TM) The boolean values are true and false: boolean ready = true; // boolean value true boolean late = false; // boolean value false Dr. Hemraj CSE2006 – Programming in JAVA 13 Constants Constants are declared with the word final in front. The specification of the initial value is compulsory: final double pi = 3.1415; // constant PI final int maxSize = 100; // integer constant final char lastLetter = ’z’; // last lowercase letter final String word = "Hello"; // a constant string Dr. Hemraj CSE2006 – Programming in JAVA 14 Expressions Java provides a rich set of expressions: – Arithmetic – Bit level – Relational – Logical – Strings related Dr. Hemraj CSE2006 – Programming in JAVA 15 Arithmetic expressions Java provides the usual set of arithmetic operators: – addition (+) – subtraction (-) – division (/) – multiplication (*) – modulus (%) Dr. Hemraj CSE2006 – Programming in JAVA 16 Arithmetic operators class Arithmetic { public static void main(String[] args) { int x = 12; int y = 2 * x; System.out.println(y); int z = (y - x) % 5; System.out.println(z); final float pi = 3.1415F; float f = pi / 0.62F; System.out.println(f); } } $ java Arithmetic 24 2 5.0669355 Dr. Hemraj CSE2006 – Programming in JAVA 17 Arithmetic operators Shorthand operators are provided: class ShortHand { public static void main(String[] args) { int x = 12; x += 5; // x = x + 5 System.out.println(x); x *= 2; // x = x * 2 System.out.println(x); } } $ java ShortHand 17 34 Dr. Hemraj CSE2006 – Programming in JAVA 18 Arithmetic operators Pre and post operators are also provided: class Increment { public static void main(String[] args) { int x = 12,y = 12; System.out.println(x++); // printed and then incremented System.out.println(x); System.out.println(++y); // incremented and then printed System.out.println(y); } } $ java Increment 12 13 13 13 Dr. Hemraj CSE2006 – Programming in JAVA 19 Relational expressions Java provides the following relational operators: – equivalent (==) – not equivalent (!=) – less than () – less than or equal (=) Important: relational expressions always return a boolean value. Dr. Hemraj CSE2006 – Programming in JAVA 20 Relational Expressions class Boolean { public static void main(String[] args) { int x = 12,y = 33; System.out.println(x < y); System.out.println(x != y - 21); boolean test = x >= 10; System.out.println(test); } } $ java Boolean true false true Dr. Hemraj CSE2006 – Programming in JAVA 21 Bit level operators Java provides the following operators: – and (&) – or (|) – not(˜) – shift left () – shift right with zero extension (>>>). Important: char, short and byte arguments are promoted to int before and the result is an int. Dr. Hemraj CSE2006 – Programming in JAVA 22 BITWISE OPERATORS OPERATORS MEANING & Bitwise AND | Bitwise OR ^ Bitwise XOR ! Bitwise NOT ~ Bitwise complement > Bitwise Right shift >>> Bitwise Zero fill right shift = Bitwise Right shift assignment >>>= Bitwise Zero fill right shift assignment Dr. Hemraj CSE2006 – Programming in JAVA 22 Bit level operators class Bits { public static void main(String[] args) { int x = 0x16; int y = 0x33; System.out.println(x & y);// System.out.println(x | y);// System.out.println(x̃); x &= 0xf; System.out.println(x); short s = 7; System.out.println(s̃); } } Dr. Hemraj CSE2006 – Programming in JAVA 23 Bit level operators class Bits2 { public static void main(String[] args) { int x = 0x16; System.out.println(x >= 4; System.out.println(y); x = 9; System.out.println(x >> 3);// System.out.println(x >>>3);// x = -9; System.out.println(x >> 3);// System.out.println(x >>>3);// } } Dr. Hemraj CSE2006 – Programming in JAVA 24 Zero Fill Right Shift Operator This operator shifts all bits towards the right by a certain number of specified bits. The difference between Right Shift and Zero fill Right Shift is Right Shift preserves the sign bit (i.e. if a = -8, then a >> 2 will be a negative number) whereas Zero fill Right Shift doesn’t consider the sign bit (i.e. if a = -8, then a >>> 2 will be a positive number). You may wonder, how does zero fill right shift operator work when the number is negative? The answer is, if N is the number of bits to be right shifted, then excess bits are shifted off N places to the right and are discarded, while zero bits are shifted in N places from the left and are kept. The sign bit becomes 0, so the result is always positive. Dr. Hemraj CSE2006 – Programming in JAVA 24 Zero Fill Right Shift Operator Syntax Number >>> (no of places to be shifted). For Example − We are going to perform a Zero fill Right shift on 1011 (11) by 1 bit. Step 1 − Before Right Shift 1-0-1-1 Step 2 − After Right Shift 0-1-0-1-1 The rightmost bit is the discarded bit, whereas the leftmost bit is the replacement bit. So, the new number is 0101 (5). Dr. Hemraj CSE2006 – Programming in JAVA 24 Zero Fill Right Shift Operator public class ZeroFillRightShiftOperator { public static void main(String[] args) { int a = 11; int b = -5; int result_1 = a >>> 1; System.out.println(" Zero Fill Right Shift of 11 by 1 digit is = " + result_1); int result_2 = b >>> 2; System.out.println(" Zero Fill Right Shift of -5 by 2 digits is = " + result_2); } } Dr. Hemraj CSE2006 – Programming in JAVA 24 Logical operators Java provides the following operators: – and (&&) – or (||) – not(!) Important: The logical operators can only be applied to boolean expressions and return a boolean value. Dr. Hemraj CSE2006 – Programming in JAVA 25 Logical operators class Logical { public static void main(String[] args) { int x = 12,y = 33; double d = 2.45,e = 4.54; System.out.println(x < y && d < e); System.out.println(!(x < y)); boolean test = ’a’ > ’z’; System.out.println(test || d - 2.1 > 0); } } $ java Logical true false true Dr. Hemraj CSE2006 – Programming in JAVA 26 String operators Java provides many operators for Strings: – Concatenation (+) – many more... Important: If the expression begins with a string and uses the + operator, then the next argument is converted to a string. Important: Strings cannot be compared with == and !=. Dr. Hemraj CSE2006 – Programming in JAVA 27 String operators class Strings { public static void main(String[] args) { String s1 = "Hello" + " World!"; System.out.println(s1); int i = 35,j = 44; System.out.println("The value of i is " + i + " and the value of j is " + j); } } $ java Strings Hello World! The value of i is 35 and the value of j is 44 Dr. Hemraj CSE2006 – Programming in JAVA 28 String operators class Strings2 { public static void main(String[] args) { String s1 = "Hello"; String s2 = "Hello"; System.out.println(s1.equals(s2)); System.out.println(s1.equals("Hi")); } } $ java Strings2 true false Dr. Hemraj CSE2006 – Programming in JAVA 29 Casting Java performs a automatic type conversion in the values when there is no risk for data to be lost. class TestWide { public static void main(String[] args) { int a = ’x’; // ’x’ is a character long b = 34; // 34 is an int float c = 1002; // 1002 is an int double d = 3.45F; // 3.45F is a float } } Dr. Hemraj CSE2006 – Programming in JAVA 30 Casting In order to specify conversions where data can be lost it is necessary to use the cast operator. class TestNarrow { public static void main(String[] args) { long a = 34; int b = (int)a; // a is a long double d = 3.45; float f = (float)d; // d is a double } } Dr. Hemraj CSE2006 – Programming in JAVA 31 Control structures Java provides the same set of control structures than C. Important: the value used in the conditional expressions must be a boolean. Dr. Hemraj CSE2006 – Programming in JAVA 32 Control structures (if) class If { public static void main(String[] args) { char c = ’x’; if ((c >= ’a’ && c = ’A’ && c = ’0’ && c