Document Details

AmusingRetinalite57

Uploaded by AmusingRetinalite57

Amity University

Tags

Core Java object-oriented programming programming language computer science

Summary

This document is an introduction to Core Java from Amity University. It details about Java's core concepts like object-oriented programming, data types, control statements, and inheritance. The file offers study material on the subject. It includes details about various programming concepts and methodologies.

Full Transcript

Core Java Programs Offered n e...

Core Java Programs Offered n e i Post Graduate Programmes (PG) l Master of Business Administration Master of Computer Applications n Master of Commerce (Financial Management / Financial Technology) Core Java O Master of Arts (Journalism and Mass Communication) Master of Arts (Economics) Master of Arts (Public Policy and Governance) Master of Social Work Master of Arts (English) Master of Science (Information Technology) (ODL) Master of Science (Environmental Science) (ODL) i ty Diploma Programmes Post Graduate Diploma (Management) r s e Post Graduate Diploma (Logistics) Post Graduate Diploma (Machine Learning and Artificial Intelligence) Post Graduate Diploma (Data Science) i v Undergraduate Programmes (UG) Bachelor of Business Administration Bachelor of Computer Applications Bachelor of Commerce Bachelor of Arts (Journalism and Mass Communication) U n English / Sociology) Bachelor of Social Work y Bachelor of Arts (General / Political Science / Economics / it Bachelor of Science (Information Technology) (ODL) A m c )DIRECTORATE OF Product code ( DISTANCE & ONLINE EDUCATION AMITY Amity Helpline: 1800-102-3434 (Toll-free), 0120-4614200 For Distance Learning Programmes: [email protected] | www.amity.edu/addoe DIRECTORATE OF For Online Learning programmes: [email protected] | www.amityonline.com DISTANCE & ONLINE EDUCATION (c )A m ity U ni ve Core Java r si ty O nl in e e in © Amity University Press All Rights Reserved nl No parts of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without the prior permission of the publisher. O SLM & Learning Resources Committee ty Chairman : Prof. Abhinash Kumar si Members : Dr. Divya Bansal Dr. Coral J Barboza r Dr. Apurva Chauhan ve Dr. Monica Rose Dr. Winnie Sharma Member Secretary : Ms. Rita Naskar ni U ity m )A (c Published by Amity University Press for exclusive use of Amity Directorate of Distance and Online Education, Amity University, Noida-201313 Contents e Page No. in Module I: Introduction to Java 01 1.1 Contract nl Module II: Java with Object Orientated Features 36 2.1 Introduction to OOP O Module III: Exception Handling Interface and Thread in Java 67 ty 3.1 Throwable Class and Its Subclasses Module IV: Java Packages and GUI 97 si 4.1 Defining Package r Module V: Event Driven Programming and Database Programming using JDBC 120 ve 5.1 Introduction to AWT ni U ity m )A (c (c )A m ity U ni ve r si ty O nl in e Core Java 1 Module - I: Introduction to Java Notes e Course Contents: in Object Object Oriented Programming nl Java Development Kit Byte code O Class, Method, Variable Data types Operators ty Control Statements Loops si Arrays Inheritance Method Overriding Abstract Classes r ve Final classes Command line arguments ni Key Learning Objectives: At the end of this module, you will be able to: U 1. Get familiar with basic concept of Java 2. Learn how to apply the basic concept to solve problem 3. Why Java is called Object Oriented Programming? ity 4. Description of data types 5. Basic features of Java 6. How to use control statements m 7. Concept of various loops 8. Get familiar with Inheritance feature. 9. Concept of method overriding )A 10. Why final classes are used? (c Amity Directorate of Distance & Online Education 2 Core Java Unit - 1.1: Contract Notes e Unit Outcome: in At the end of this unit, you will be able to: Define Object Oriented Programming nl Categories different kinds of data types, variables, control statements, loops. Define class, method, variables O Summarize basic features of Java. Define method overloading Categories inheritance ty Differentiate abstract class and final class 1.1.1 Introduction of Java si Java is a object oriented programming language created by James Gosling in 1991. As, it is mentioned object oriented so we need to know what is object. r Object is nothing but real-world entity that we can touch like pen, pencil, chair, computer, dog etc. Object has state (which represents data) and behavior (which ve represents functionality or method). For example dog has state like its name, color, breed etc and behavior like eating, barking etc. Java runs on a variety of platforms, hence it is known as platform independent. ni Now, the question will come now what is platform. Here, platform means the operating system on which you will run your Java program such as Windows, Mac OS, UNIX etc. Java programming is little bit matured now, near about 23 years old. The target of Java language was to write a program once and run this program on multiple operating U systems. The first publicly available version of Java (Java 1.0) was released in 1995. So, let us know about object first. The developer claimed that the Java programming language is very simple, ity it is portable, very secure, high performed, multi threaded, interpreted, platform independent, dynamic architecturally neural, object oriented and finally, it is robust. Here, I will elaborate key advantages of learning Java Programming: m Simple: Java is easy to learn if you understand the concepts of OOP (Object Oriented Programming). Object Oriented: In Java, everything is considered as an Object. )A Platform Independent: This term means Java is not compiled into platform specific machine. You can write the code once in one platform and can run it in other platforms without writing it several times for different platforms. Secure: Java enables to develop virus-free systems as all the pointers work (c internally and user cannot handle pointer externally. Amity Directorate of Distance & Online Education Core Java 3 Architecture-neutral: Java compiler creates an architecture-neutral object, which Notes e makes the compiled code executable on many processors, with the presence of Java runtime system. in Portable: Java is portable as it gives us opportunity to carry the Java bytecode to any platform. It doesn’t require any implementation. Robust: It uses strong memory management and has automatic garbage nl collection methods etc. That’s why Java is called Robust which means strong. Multi threaded: Multi threaded because it can perform many tasks at the same time. O 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. ty High Performance: Java enables high performance. Distributed: Java is distributed as it helps users to create distributed applications in Java. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are si used for creating distributed applications. Dynamic: Java is considered to be more dynamic as Java programs can carry extensive amount of run-time information which can be used to verify and resolve accesses to objects on run-time. r ve 1.1.2 History of Java First time Java was introduced the 1991, there was a team named as the Green Team from the sun micro system lab, Sun system lab was very famous for developing ni hardware and software. The pioneer of this Green Team was James Gosling and his colleagues Mike Sheridan and Patrick Naughton. U They first time introduce the concept of object oriented programming. They give the name of the programming has Greentalk as it is from the green team. Later, they developed a more improved version of the concept and they gave the name as Oak. In 1995, Gosling introduced the name Java. Java is an island of Indonesia, where ity best coffee of the world is produced and Gosling was very fond of coffee and use to consume coffee while working on this project, that is why he chose the name Java for this programming language. Then gradually Java became very popular and with this popularity in 1996, the m Sun Micro system introduced a full set of programming environment, and they named it as JDK (Java Development Kit). So, this gives you a brief history of the Java and why the name of the programming language is Java. )A 1.1.3 JDK Tools Standard JDK Tools and Utilities Basic Tools: applet viewer, extcheck, jar, java, javac, javadoc, javah, javap, jdb (c Amity Directorate of Distance & Online Education 4 Core Java Tool Name Brief Description Notes e appletview-er Run and debug applets without a web browser. Apt Annotation processing tool. in extcheck Utility to detect Jar conflicts. Jar Create and manage Java Archive (JAR) files. nl The launcher for Java applications. In this release, a single Java launch-er is used both for development and deployment. The old deployment launcher, jre, is no longer provided. O javac The compiler for the Java programming language. javadoc API documentation generator. javah C header and stub generator. Used to write native methods. ty javap Class file disassembler Jdb The Java Debugger. si Security Tools: keytool, jarsigner, policytool, kinit, klist, ktab Tool Name Brief Description keytool r Manage keystores and certificates. ve jarsigner Generate and verify JAR signatures. policytool GUI tool for managing policy files. ni These security tools help you obtain, list, and manage Kerberos tickets. Tool Name Brief Description U Tool for obtaining Kerberos v5 tickets. Equivalent functionality Kinit is available on the Solaris operating system via the kinit tool. Command-line tool to list entries in credential cache and ity Klist key tab. Equivalent functionality is available on the Solaris operating system via the klist tool. Command-line tool to help the user manage entries in the Ktab key ta-ble. Equivalent functionality is available on the Solaris operating system via the kadmin tool. m Internationalization Tools: native2ascii )A Tool Name Brief Description native2ascii Convert text to Unicode Latin-1. (c Amity Directorate of Distance & Online Education Core Java 5 Remote Method Invocation (RMI) Tools: rmic, rmiregistry, rmid, serialver Notes e Tool Name Brief Description in Rmic Generate stubs and skeletons for remote objects. rmiregistry Remote object registry service. Rmid RMI activation system daemon. nl serialver Return class serialVersionUID. Java IDL and RMI-IIOP Tools: tnameserv, idlj, orbd, servertool O Tool Name Brief Description tnameserv Provides access to the naming service. Generates.java files that map an OMG IDL interface and ty Idlj enable an application writ-ten in the Java programming language to use CORBA functionality. Provides support for clients to transparently locate and invoke si persistent objects on servers in the CORBA environment. ORBD is used instead of the Transient Nam-ing Service, tnameserv. ORBD includes both a Transient Naming Service Orbd r and a Per-sistent Naming Service. The orbd tool incorporates ve the functionality of a Server Manager, an Interoperable Naming Service, and a Bootstrap Name Server. When used in conjunction with the servertool, the Server Manager locates, registers, and activates a server when a client wants ni to access the server. Provides ease-of-use interface for the application programmers servertool to register, un-register, startup, and shutdown a server. U Java Deployment Tools: javafxpackager, pack200, unpack200 Utilities for use in conjunction with deployment of java applications and applets on the web. ity Tool Name Brief Description javafxpackager Packages JavaFX applications for deployment. Transforms a JAR file into a compressed pack 200 file using m the Java gzip com-pressor. The compressed packed files are pack200 highly compressed JARs, which can be directly deployed, saving bandwidth and reducing download time. )A unpack200 Transforms a packed file produced by pack200 into a JAR file. Java Web Start Tools: javaws Tool Name Brief Description (c Command line tool for launching Java Web Start and setting javaws various options. Amity Directorate of Distance & Online Education 6 Core Java Java Troubleshooting, Profiling, Monitoring and Management Tools: jcmd, Notes e jconsole, jmc, jvisualvm Tool Name Brief Description in JVM Diagnostic Commands tool - sends diagnostic command Jcmd requests to a running Java Virtual Machine. nl A JMX-compliant graphical tool for monitoring a Java virtual jconsole machine. It can moni-tor both local and remote JVMs. It can also monitor and manage an application. O The Java Mission Control (JMC) client includes tools to monitor and manage your Java application without Jmc introducing the performance overhead normally associat-ed with these types of tools. ty A graphical tool that provides detailed information about the Java technology-based applications (Java applications) while they are running in a Java Virtual Ma-chine. Java VisualVM jvisualvm si provides memory and CPU profiling, heap dump analysis, memory leak detection, access to MBeans, and garbage collection r Java Web Services Tools: schemagen, wsgen, wsimport, xjc ve Tool Name Brief Description schemagen Schema generator for Java Architecture for XML Binding. wsgen Tool to generate JAX-WS portable artifacts. ni wsimport Tool to generate JAX-WS portable artifacts. xjc Binding compiler for Java Architecture for XML Binding. U 1.1.4 Class File Before we discuss about a class file, let us take a very simple example so that we ity can understand how to write a basic Java program.1.1.2 Characteristics : The unique characterisitics of a contract is that. Every contract is an agreemnt, but every agreement is not a contract. FirstProgram.java m public class First Program { public static void main(String[] args){ )A System.out.println(“This is my first Java program”); } } (c Output: This is my first Java program Amity Directorate of Distance & Online Education Core Java 7 After writing a Java program, we will save the program with extension.java and Notes e after that we compile the.java file which will produce.class file. We must remember that a Java source file can have only one public class and it name must match with name of file. For example, if our file name is FirstProgram.java then in that file a public in class should be there whose name should be FirstProgram and after compilation First Program. class file will be produced. nl Steps of compilation In the above program, we can see we have one public class First Program and we will save this program by writing FirstProgram.java and we can compile our file either O in command prompt or in IDE. If we compile the program in command prompt then we have to write javac FirstProgram.java (javac followed by your program name with.java extension) and if there is no error in your program then no message will come and after compilation FirstProgram.class will be produced. Now you can run your program ty by writing java FirstProgram (java followed by program name without extension) in command prompt. On successful running you will get your desired output. si 1.1.5 Java Bytecode Java bytecode is the result of the compilation of a Java program which the Java Virtual Machine (JVM) understands and which is machine independent. On compilation r of a Java program, a byte code has to be produced only once and after that it can run ve on any platform wherever a Java Virtual Machine exists. Bytecode files have a.class extension. In above example, you can see we have used javac which is the compiler. In command prompt, we have to write javac then file name with extension to compile your ni Java program. So, we have to give the name of the file in the same way as the name of the class you have given and it is a case sensitive so, be careful about that. Now, let us compile it. So, as there is no error, no message in the command prompt, this means U that this program has successfully compiled. Once on the successful compilation, you can see in the same directory one file is created, the name of the file is the same as the name of the Java file except the ity extension is.class. So, here you can see the byte code file which has been created is FirstProgram.class. So, once this program is successful on compilation now we are ready to run it, to run this program the command that we said to use it java. So, Java first program FirstProgram and then.class you can use the.class or even if you use the class also no issue so it will run. So, here, for example, the class file name m is FirstProgram. Simply type java and the name of the class file, namely FirstProgram here. So, this is the program that has been executed and as you see this program is basically used only one statement namely System.out.println() and within this println() is )A basically print the statement “This is my first Java program”. 1.1.6 JVM JVM (Java Virtual Machine) is an machine which does not exist physically, we (c can say it is an abstract machine or a specification that provides runtime environment in which java bytecode can be executed. As we already know that Java language is Amity Directorate of Distance & Online Education 8 Core Java platform independent but JVM is platform dependent. JVM calls the main method Notes e present in a java code. JVM is a part of Java Runtime Environment (JRE). in nl O ty The JVM has different tasks. It loads code, verifies code, executing code and it provides runtime environment. As you can see in the picture JVM lies inside JRE (Java Runtime Environment) which provides runtime environment and is the implementation of JVM. It physically exists. It contains a set of libraries and other files that JVM uses at si runtime. We can see in the picture that JRE lies inside JDK (Java Development Kit). JDK r is a software package and you need to download it to develop Java applications and applets. It contains JRE and other development tools. The JDK includes the JRE, ve an archiver (jar), a compiler (javac), an interpreter (java), a documentation generator (javadoc), and few more development tools. 1.1.7 Identifiers ni In programming languages, identifiers are used to identify through symbolic names. In Java, an identifier can be a class name, variable name, method name, package U name, interface name or a label. Identifiers are names of variables, methods, classes, packages and interfaces. In the FirstProgram.java program, FirstProgram, String, args, main and println are all examples of identifiers. ity Example: class IdentifierExample{ void myMethod(){ m System.out.println(“Hello Java”); } )A public static void main(String[] args){ int a = 95; } } (c In the above java code, we have 5 identifiers namely : Amity Directorate of Distance & Online Education Core Java 9 IdentifierExample: class name. Notes e myMethod, main : method name. System, String : predefined class name. in args, a : variable name. 1.1.7.1 Rules for defining Java Identifiers nl To define a valid java identifier you need to follow few rules. If rules are not followed then you will get compile time error. O Alphanumeric characters are only allowed characters which includes ([A-Z], [a-z], [0-9]), ‘$‘(dollar sign) and ‘_’ (underscore). Example: “abc@” is not a valid java identifier as it contain ‘@’ which is a special character. ty Identifiers should not start with digits ([0-9]). Example: “12abc” is not a valid java identifier. si Java identifiers are case-sensitive i.e. myVariable, MyVariable and Myvariable are different from each other. Though no limit is there to specify the length of the identifier but it is always better r if you use an optimum length of 4 to 15 letters only. ve You cannot use Reserved Words as an identifier. Example: “int while = 20;” is an invalid statement as “while” is a reserved word. There are 53 reserved words in Java. ni 1.1.7.2 Examples of valid identifiers Below are listed few valid identifiers. U MyVariable MYVARIABLE myvariable ity a i x m p1 i1 )A _myvariable $myvariable total_salary (c salary123 Amity Directorate of Distance & Online Education 10 Core Java 1.1.7.3 Examples of invalid identifiers Notes e My Variable: as it contains space between My and Variable 123salary: as it begins with a digit in var-5: as hyphen is not an alphanumeric character p+q: as plus sign is not an alphanumeric character nl a&b: as ampersand is not an alphanumeric character 1.1.7.4 Reserved Words O Any programming language reserves some words to represent functionalities defined by that language. These words are called reserved words. ty abstract do if private assert double implements protected boolean else import si public break enum instanceof return byte extends int short case r false interface static ve catch final long strictfp char finally native super class float new switch ni const for null synchronized default goto package U 1.1.8 Data Types Data types of the Java programming language are divided into two categories: primitive types and non-primitive or reference or user defined types. A primitive data ity type means the data types which are predefined and provided to us by the Java programming language. The primitive are the numeric types, boolean type and character type. m The numeric types contain integral types and floating-point types. Integral types contain byte, short, int, long and the floating-point types contain float and double. The non-primitive or reference types are class, interface, array etc. which user )A creates as their own. String literals are represented by String objects. Picture 2 depicts the data types available in Java. (c Amity Directorate of Distance & Online Education Core Java 11 Notes e in nl O 1.1.8.1 Integral Types and Values Integral types have values in the below ranges: ty The byte data type has values ranging from -128 (-27)to 127 (27– 1), inclusive. Default value is 0. For example, byte a = 10 or byte b = -20 For short data type, range from -32768 (216 ) to 32767(216 – 1), inclusive. Default si value is 0. For example; short s = 20000, short r = -6500 For int data type, range from -2147483648 (-231) to 2147483647 to (231– 1), inclusive. Default value is 0. int a = 100000, int b = -200000 r For long data type, range from -9223372036854775808 (-263 ) to ve 9223372036854775807 (263 – 1), inclusive. Default value is 0L. long a = 100000L, long b = -150000L Example: ni int myNum = 5; // Integer (whole number) Wrapper Class: Byte U Minimum value: -128 (-2^7) Maximum value: 127 (2^7 -1) Default value: 0 ity Example: byte a = 10 , byte b = -50; Wrapper Class: Short Minimum value: -32,768 (-2^15) m Maximum value: 32,767 (2^15 -1) Default value: 0. )A Example: short s = 10, short r = -1000; Wrapper Class: Integer Minimum value: (-2^31) (c Maximum value: (2^31 -1) The default value: 0. Amity Directorate of Distance & Online Education 12 Core Java Example: int a = 50000, int b = -20 Notes e Wrapper Class: Long in Minimum value: (-2^63) Maximum value: (2^63 -1) Default value: 0L. nl Example: long a = 100000L, long b = -600000L; 1.1.8.2 Floating-Point Type O There are two floating-point data types which are double and float. The float data type is characterized by single-precision 32-bit and double data type is double- precision 64-bit IEEE 754 floating point values. Precision means how many digits the ty value can have after the decimal point. It is recommended to use a float if you want to save memory area in large arrays of floating point numbers. The float data type stores fractional numbers which is capable to store 6 to 7 decimal digits whereas the double data type stores fractional numbers which is capable to store 15 decimal digits. Default si value of float data type is 0.0f and for double it is 0.0d. The float data type can store fractional numbers ranging from 3.4e−038 to 3.4e+038 and double data type can store fractional numbers ranging from 1.7e−308 to 1.7e+308. r ve Example of float and double: float f1 = 234.5f double d1 = 12.3 ni Wrapper Class: Float Float is mainly used to save memory in large arrays of floating point numbers. U Default value: 0.0f. Example: float f1 = 24.5f; ity 1.1.8.3 Character Type The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (65,535 inclusive).The char data type is used to store characters. m Example: char ex = ‘A’ Wrapper Class: Character )A Minimum value: ‘\u0000’ (or 0). Maximum value: ‘\uffff’ (or 65,535). Default value: null (‘\u0000’). (c Example: char letterA =’a’; Amity Directorate of Distance & Online Education Core Java 13 1.1.8.4 Boolean Type Notes e The boolean data type is used to store two possible values: true and false. This data type specifies one bit of information, but its “size” can’t be defined precisely. in Example: boolean a = false Wrapper Class: Boolean nl This data type is used for simple flags that track true/false conditions. Default value is false. O 1.1.8.5 Reference Types and Values There are few reference types and those are class, interface, type variables, array etc. ty Class: Class is the blue print of what your object is representing. Hence, we can say object is instance of class. Also, we can say class is a group of objects which have common properties i.e. in a single class we can put many similar type objects and si objects are created from this class. It is a logical entity. It can’t be physical but object is physical entity. r A class or interface consists of a type declaration specifier, optionally followed by type arguments. A type declaration specifier may be either a type name, or a class or ve interface type followed by “.” and an identifier. In the latter case, the specifier has the form obj.id, where id should be the name of an accessible member type of obj, or a compile-time error occurs. The specifier denotes that member type. Let us make it more clear with an example. ni Example: Dog.java class Dog { U int age = 5; // state of object or variable void bark(){ // behavior of object or method ity System.out.println(“The dog is barking and its age is” + age); } public static void main(String[] args){ // main method m Dog obj = new Dog(); //creation of object obj.bark(); // calling or accessing the method } )A } In the above example, you can see the first line is written as class class_name, here our class name is Dog. When we will create object we have to write (c class_name object_name = new constructor_calling; Amity Directorate of Distance & Online Education 14 Core Java Here in our example, class_name is Dog, object_name you can write as per your Notes e wish. In this example object_name is obj and with the help of “new” keyword we always create object in Java and then constructor calling (We will later know about constructor). in 1.1.9 Operators In Java language, operators perform some operations and which are nothing but nl symbols. +, -, *, / etc. are all examples of operators. Arithmetic operation, magnitude and tests for equality are common examples of expressions as after operation they return a value and you can assign that result to a variable or you can put the value to O test in other Java statements. Arithmetic operator, assignment operator, increment and decrement operator and logical operator are commonly used operators in Java. 1.1.9.1 Arithmetic Operators ty Java has five operators for basic arithmetic as described in below table. Operator Meaning Example si + Addition 10+12 - Subtraction 20-4 * / r Multiplication Division 8*7 14/2 ve % Modulus 100%8 Each operator takes two operands and one operator. To negate a single operand you can use the subtraction (-) operator. If you are performing integer division, it will ni return an integer value as integers don’t have decimal fractions, thus is any remainder is coming that will be ignored. For example the expression 52/ 7 gives results as 7. The role of the modulus (%) operator is to return the remainder of two numbers. For U example, 31% 9 gives results as 4 because modulus gives the result which is the remainder of your division operation. Note that, the result of most operations involving integer values will produce an ity int or long values, regardless of the original type of the operands. If large values are coming as result then it is of type long; rest are int. Arithmetic operation involving one operand as integer and another as floating point will return a floating-point result. Example: ArithmeticProgram.java m class ArithmeticProgram { public static void main (String[] args) { )A short x = 6; int y = 4; float a = 12.5f; (c float b = 7f; System.out.println(“x is “ + x + “, y is “ + y); Amity Directorate of Distance & Online Education Core Java 15 System.out.println(“x + y = “ + (x + y)); Notes e System.out.println(“x - y = “ + (x - y)); System.out.println(“x / y = “ + (x / y)); in System.out.println(“x % y = “ + (x % y)); nl System.out.println(“a is “ + a + “, b is “ + b; System.out.println(“a / b = “ + (a / b)); O } } ty Output: x is 6, y is 4 x + y = 10 si x-y=2 x/y=1 x%y=2 r ve a is 12.5, b is 7 a / b = 1.78571 ni The System.out.println() method prints a message to the standard output of your system. This method takes a single argument—a string—but you can use + sign to concatenate values into a string, which you’ll learn later on. U We can assign value to variable in the form of expression. If you write x = y = z = 10, you can tell that all three variables now have the value 10. Also, the right side of an assignment expression is always evaluated before the assignment operation takes place. This means that expressions such as x = x + 5 do the right thing i.e. 5 is added ity to the value of x, and then that new value is reassigned to x. This kind of operation is very common hence Java has several operators to do a shorthand version which is borrowed from C and C++. Below table shows these shorthand assignment operators. m 1.1.9.2 Assignment Operators Expression Meaning )A x += y x=x+y x –= y x+x–y x *= y x=x*y x ¸= y x=x¸y (c Amity Directorate of Distance & Online Education 16 Core Java 1.1.9.3 Incrementing and Decrementing Notes e To increase or decrease a value by 1, we use + + and – – operators. For example, x++ increments the value of x by 1 which actually equivalent to x = x + 1 expression. in Similarly, x– – decrements the value of x by 1. These increment and decrement operators can be prefixed i.e. ++ or -- can appear before the value or postfixed i.e. ++ or – – can appear after the value it increments or decrements. nl For simple increment or decrement expressions, which form you use is not overly important but in case of complex assignments which form you use makes a difference because you are assigning the result of an increment or decrement expression. O Let us consider the following two expressions: y = x++; ty y = ++x; These two expressions will produce different results because of the difference between prefix and postfix. The postfix operators (x++ or x--) first return the variable si value, then increment or reduce the value of the variable. The prefix operators (++x or –x) first increment or decrease the value of a variable and then returns value of the variable. r Example of prefix and postfix increment operators: ve class PrePostFixProgram { public static void main (String[] args) { ni int x = 0; int y = 0; U System.out.println(“x and y are “ + x + “ and “ + y ); ity x++; System.out.println(“x++ results in “ + x); ++x; m System.out.println(“++x results in “ + x); System.out.println(“Resetting x back to 0.”); x = 0; )A System.out.println(“——————”); y = x++; System.out.println(“y = x++ (postfix) results in:”); (c System.out.println(“x is “ + x); System.out.println(“y is “ + y); Amity Directorate of Distance & Online Education Core Java 17 System.out.println(“——————”); Notes e y = ++x; System.out.println(“y = ++x (prefix) results in:”); in System.out.println(“x is “ + x); System.out.println(“y is “ + y); nl System.out.println(“——————”); O } ty } x and y are 0 and 0 si x++ results in 1 ++x results in 2 Resetting x back to 0. r ve —————— y = x++ (postfix) results in: ni The postfix operator ++ adds one to its operand / variable and returns the value only after it is assigned to the variable. In other words, the assignment takes place first U and the increment next. x is 1 ity y is 0 —————— y = ++x (prefix) results in: m The prefix operator ++ adds one to its operand / variable and returns the value )A before it is assigned to the variable. In other words, the increment takes place first and the assignment next. x is 2 y is 2 (c —————— Amity Directorate of Distance & Online Education 18 Core Java Java has several expressions for testing equality and magnitude. All of these Notes e expressions return a boolean value (that is, true or false). Below table shows the comparison operators: in 1.1.9.4 Comparison operators Operator Meaning Example nl = Equal x == 3 != Not equal x != 3 < Less than x Greater than x>3 ≤ Less than or equal x ≤3 ty ≥ Greater than or equal x≥3 1.1.9.5 Logical Operators si If there is a chance to get result in boolean values of Expressions (for example, the comparison operators) then it can be combined by using logical operators that represent the logical combinations AND, OR, XOR, and logical NOT. r 1.1.9.5.1 AND expression ve We use either & or && for AND combination. && is known as logical AND operator. In an expression it will return true if both the statements are true. If first condition is false then second condition will not be checked. Second condition will only be checked if the first condition is true. ni & is known as bitwise operator and this operator always checks both conditions whether first condition is true or false. U Example: int a=15; ity int b=5; int c=30; System.out.println(a= Zero fill right shift assignment (x = x >>> y) x&=y AND assignment (x = x & y) si x|=y OR assignment (x + x | y) x^=y NOT assignment (x = x ^ y) 1.1.9.7 Operator Precedence r ve If an expression contains multiple operators then there are a number of rules to decide the order in which the operators will be evaluated. The most important rule is known as operator precedence. Operators which have higher precedence are executed before than the operators with lower precedence. For example, multiplication ni has a higher precedence than subtraction or addition. In the expression 5+2*3, the multiplication will be done before the addition which in turn will produce a result of 14. When operators of equal precedence appear in the same expression, binary operators U except for the assignment operators are evaluated from left to right and assignment operators are evaluated right to left. In general, increment and decrement are evaluated before arithmetic expressions are evaluated, arithmetic expressions are evaluated before comparisons, and comparisons are evaluated before logical expressions. ity Assignment expressions are evaluated last. [], () Parentheses group expressions; dot (.) is used for access to methods and variables within objects and classes. [] is used for arrays. ++ –– ! ~ instance of Returns true or false based on whether the object is an instance of the named class or any of m that class’s superclasses. 1.1.9.8 String Arithmetic )A One special expression in Java is the use of the addition operator (+) which we will use to create and concatenate strings. Example: (c String name = “Tojo”; String color =”white”; Amity Directorate of Distance & Online Education Core Java 21 Int age = 10; Notes e System.out.println(name + “ is “ + color + “ in color whose age is “+ age +”years”); in Output: Tojo is white in color whose age is 10 years nl In this example you can see the output of this line has come in a single line as a string, with the values of the variables (name and color) embedded on it. The concatenation (+) operator, when used with strings and other objects, creates a single string that contains the concatenation of all its operands. If any of the operands in string O concatenation is not a string (age here is not String), it is automatically converted to a string, making it easy to create these sorts of output lines. 1.1.10 Control statements ty The statements inside your source files are generally executed from top to bottom. Control flow statements break up the flow of execution for decision making, looping, si and branching and enable your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if, if-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue) supported by the Java programming language. r ve 1.1.10.1 The if and if-else Statements 1.1.10.1.1 The if Statement The most common control flow statement is “if statement”. It tells a particular ni block of code to execute only if a condition checking produces true result. A car can allow the brakes to decrease its speed only when the car is in motion. One possible implementation of the apply Brake method can be written as: U void applyBrake() { if (isMoving) // we have to apply break when car is moving ity { //if the car is moving then we can decrease its speed speed--; m } } If this test evaluates to true then only we can change the value of speed variable )A by 1 but if result is false that means that the car is not in motion then the control jumps to the end of the if statement. 1.1.10.1.2 The if-else Statement (c The if-else statement provides a secondary path of execution when an “if” clause evaluates to false. You could use an if-else statement in the apply Brake method to take Amity Directorate of Distance & Online Education 22 Core Java some action if the brakes are applied when the car is not in motion. In this case, the Notes e action is to simply print an error message stating that the car has already stopped. void applyBrake() { in if (isMoving) { speed--; nl } else { System.err.println(“The car has already stopped!”); O } } 1.1.10.1.3 The switch Statement ty The Java switch statement executes one statement from multiple conditions. It is like if-else-if kind of statement. The switch statement works with primitive data types like byte, short, int, long. It can work with wrapper class types like Byte, Short, Integer and si Long, it also works with enumerated types. It can also work with String class. In other words, the switch statement tests the equality of a variable against multiple values. Example: SwitchTest.java r ve public class SwitchTest { public static void main(String[] args) { int n=35; ni switch(n){ case 10: System.out.println(“ Value is 7”); U break; case 20: System.out.println(“Value is 21”); break; ity case 30: System.out.println(“Value is 35”); break; default: System.out.println(“Value is not 7, 21 or 35”); m } } )A } In the above example we have used break statement. When a break statement is encountered, flow is immediately terminated and the program control resumes at the next statement. The Java break statement is used to break switch or loop statement. It (c breaks the current flow of the program at specified condition. Amity Directorate of Distance & Online Education Core Java 23 1.1.11 Loops: Notes e In any programming language, we use loops to execute a set of instructions repeatedly when some conditions become true. The control flow goes out of the loop in only when the condition will become false. Here, we are going to discuss three types of loops used in Java. for loop nl while loop do-while loop O 1.1.11.1 The for loop The for loop is a control flow statement that iterates a part of the programs multiple times. ty Example: for(int a =0; a to prepare static component ni java.awt.event => to make static component dynamic To represent events, classes are provided by AWT and to represent listeners, interfaces are provided by AWT. Java has provided pre defined libraries to perform U event handling. A number of listeners are available in Java and for each listener, a number of listener methods are available. GUI component Event ity Button ActionEvent Checkbox ItemEvent RadioButton ItemEvent List ItemEvent m Choice ItemEvent Menu ActionEvent )A ScrollBar AdjustmentEvent Window WindowEvent Mouse MouseEvent Keyboard KeyEvent (c TextField TextEvent TextArea TextEvent Amity Directorate of Distance & Online Education 124 Core Java For button, listener is ActionListener. Buttons will raise one event that is Notes e ActionEvent. To handle this ActionEvent, we will implement ActionListener as it is an interface. In ActionListener, actionPerformed() method is there which we have to use for putting implementation. in Let us take an example, let us think in a form there are two Text fields which will accept data from user and in 3rd field, it will produce the result once user click nl on Button. Once data is put in two fields and you click on button then automatically an event will be raised (ActionEvent) and immediately flow of execution will go to correspondint listener (here ActionListener) and inside the listener, event method will be executed. Hence, in general we can tell that whenever we trigger a GUI component, O an event will be raised. the process of raising an event and the process of delegating or bypassing event to the listener in order to handle. So, the total process of handling event is called Event delegation model or event handling. ty 5.1.4 Event Classes Event is to change the state of an object. The java.awt.event package provides si many event classes and Listener interfaces for event handling. For example dragging mouse of clicking a button etc are events. The java.awt.event package provides many event classes and Listener interfaces for event handling. r Event classes Listener interfaces ve ActionEvent ActionListerner MouseEvent MouseListener MouseWheelEvent MouseWheelListener ni ItemEvent ItemListener KeyEvent KeyListener U ComponentEvent ActionListerner AdjustmentEvent AdjustmentListener WindowEvent WindowListener ity TextEvent TextListener ContainerEvent ContainerListener FocusEvent FocusListener m 5.1.4.1 Methods For registering the component with the Listener, many classes provide the registration methods. For example: )A Button (Creates a push button control) public void addActionListener(ActionListener a){} MenuItem (Creates a menu item.) (c public void addActionListener (ActionListener a){} TextField (Creates a single-line edit control) Amity Directorate of Distance & Online Education Core Java 125 public void addActionListener (ActionListener a){} Notes e public void addTextListener (TextListener a){} TextArea (Creates a multiline edit control) in public void addTextListener (TextListener a){} Checkbox(Creates a check box control) nl public void addItemListener (ItemListener a){} Choice (Creates a pop-up list) public void addItemListener (ItemListener a){} O List ( creates a list from which a user can choose) public void addActionListener (ActionListener a){} public void addItemListener (ItemListener a){} ty 5.1.4.2 Java Event Handling Code We can put the event handling code into one of the following places: si 1. Within class 2. Other class 3. Anonymous class r ve 5.1.5 Sources of Events The Delegation Event Model has the following key participants namely: Source - The source is an object on which event occurs. Source is responsible ni for providing information of the occurred event to it’s handler. Java provide as with classes for source object. Listener - It is also known as event handler.Listener is responsible for generating U response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns. ity The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model, Listener needs to be registered with the source object so that the listener can receive m the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them. 5.1.5.1 Steps to perform Event Handling: )A 1. Create container class and declare a 0-arg constructor, inside the constructor declare a GUI component. Example: class MyFrame extends Frame { (c MyFrame(){ Button b = new Button(“Submit”); Amity Directorate of Distance & Online Education 126 Core Java....... Notes e } } in 2. Select a listener and provide Listener implementation class with the implementation of Listener methods. nl class MyActionListener implements ActionListener { public void actionPerformed (ActionEvent ae){...... O } } ty In general, in GUI applications, we will implement Listener interface in the same container class. class MyFrame extends Frame implements ActionListener { si..... } r 3. Attach Listener to GUI component like public void addxxxListener (xxxListener l) ve Note that, xxxListener may be ActionListener, ItemListener and so on. Example: b.addActionListener (new MyActionListener()); ni 5.1.6 Event Listener Interfaces GUI component Event Listener interfaces U Button ActionEvent ActionListerner Checkbox ItemEvent ItemListener RadioButton ItemEvent ItemListener ity List ItemEvent ItemListener Choice ItemEvent ItemListener Menu ActionEvent ActionListerner ScrollBar AdjustmentEvent AdjustmentListener m Window WindowEvent WindowListener Mouse MouseEvent MouseListener )A Keyboard KeyEvent KeyListener TextField TextEvent TextListener TextArea TextEvent TextListener (c Amity Directorate of Distance & Online Education Core Java 127 5.1.7 Working with Windows Notes e In case of WindowEvent, component is Window, event is WindowEvent and listener is WindowListener. in Working with Frame Windows Most often the type of window we will create be derived from Frame. There are two nl constructors of Frame. 1. Frame ( ) 2. Frame (String title) O The first one will create a standard window which does not contain a title. The second form creates a window with the title specified by title. Here, we cannot specify the dimensions of the window but we have to set the size of the window after it has ty been created. Setting the Window’s Dimensions si The setSize( ) method is used to set the dimensions of the window. Syntax: void setSize(int width, int height) r ve void setSize(Dimension newSize) The new size of the window is specified by width and height. The getSize( ) method is used to obtain the current size of a window. ni Syntax: Dimension getSize( ) U This method returns the current size of the window mentioning the width and height fields of a Dimension object. Hiding and Showing a Window ity After a window has been created, it will not be visible. You have to make it visible and in order to make it visible you have to call setVisible() method and you have to pass “true” as parameter. Syntax: m void setVisible (boolean flag) Setting a Window’s Title )A If you want to set title as per your choice, you can do that by calling setTitle() and you have to pass the desired title as parameter. Syntax: (c void setTitle(String title) Amity Directorate of Distance & Online Education 128 Core Java Closing a Frame Window Notes e To implement window close event, you have to implement windowClosing() method of WindowListener interface and inside windowClosing() you must remove the window in from screen. Default implementation of listener interface is provi

Use Quizgecko on...
Browser
Browser