Skip to main content
Open navigation menu
Close suggestions
Search
Search
en
Change Language, English
Upload
Sign in
Sign in
83%
(6)
83% found this document useful (6 votes)
9K views
292 pages
Core Java
Uploaded by
BABU LAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Save
83%
17%
Share
Report
83%
(6)
83% found this document useful (6 votes)
9K views
292 pages
Core Java
Uploaded by
BABU LAL
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Save
83%
17%
Share
Report
Page view
Download
NEW SYLLABUS CBCS PATTERN Core Java Dr. Ms. Manisha Bharambe Mrs. Manisha Suryawanshi Kamil Ajmal Khan OMIBAL! eatin5 gpruncn Si 4 Boon oF Core Java For B.B.A.(C.A) : Semester - V [Course Code CA-503 : Credits-03] SES As Per New Syllabus, Effective from June 2021 Dr. Ms. Manisha Bharambe [Link]. (Comp. Sci.), [Link], Ph.D (Comp. Sci.) \ice Principal and BCA Coordinator MES Abasaheb Garviare College, Pune 4 Mrs. Manisha Suryawanshi [Link]., MPhil. (CS), M-B.A. (HR) Asst. Prof., Placement Co-ordinator Modern College of Arts, Science and Commerce (Autonomous), Pune 5 Mr. Kamil Ajmal Khan Mise. Computer Science Asst. Prof. Computer Science Department ‘Abeda Inamdar Senior College, Pune Price = 360.00 NIRALI DOME N4959]CORE JAVA ISBN 978-93-5451-305-3 First Edition + September 2022 e Authors The tet of this publication, of any part thereat should not be reproduce or transmitted in any form oF stomd in any ‘compute storage system or device for dstrbution including photocopy, recarng, taping or information retrieval sytem or repraductd on any clic tape, perforated media or ther information storage device etc. without the writen permission of ‘uthas wth whorn the rights ae reserved Breach ofthis canton fable for lege! action, Every effort has bean made to avoid eros or omissions in tis publication. In site ofthis erers may have creo n. Any mistake, evr or dscrepancy So nated and shall be brought to cur netic shall be taken care af in the nest edition I s notified ‘that neither the publisher na the authors or slr shall be responsible for any damage or loss of action to any one of any kind, in any mane, theretrom. The reader must cass check all the fats end contents with ariginal Goverment natfeation or publications Published sy : Polyplate Printed By : NIRALI PRAKASHAN ‘YOGIRAJ PRINTERS AND BINDERS ‘Abhyudaya Pragati, 1312, Shiva Nagar, ‘Survey No, 10/14, Ghule Industial Estate (Off JIM, Foe, Pune — 411005 Nanded Gaon Road Tel - (020 25512336/37/39 Nanded, Pune- 411081 Email: nkalipune@pragationiinecom Seren keine PUNE Nirali Prakeshan Nirali Prakashan (For orders outside Pune) (For orders within Pune) [Link], 28/27, Dhayari Nate Road, Near Asian College 119, Bushwar Peth Jogeshwari Mandi Lare Pune 411081, Maharashtra Pune 411002, Maharashtra “Tel (020) 24680204; Mobile: 9557703143, Tel: (020) 2445 2044; Mobile: 9657703145 Email: bookorder@pragationinecom Email: niraitocal@[Link] MUMBAI Nirali Prakeshan Rasdhara Co-op. Hig. Society Ltd, 0’ Wing Ground Floor, 385 SVP. Road ‘Grgaum, Mumbai 400004, Maharastera Mobile: 7945821020, Tel: (022) 2385 6339 /2386 9976 Enail:riralimumbai@pragationline com Mercere DELHI BENGALURU NAGPUR Nirali Prakashan Nirali Prakashan Nirali Prakashan Room No.2 Ground Floor __| NeitriGraund Fiver, Jaya Apartments, | Above Maratha Mend, Shop No.3 4575/15 Omar Tower, Agarwal Road | No. 99, 6" Cross 6” Main, Fist Floor, Rani Jhansi Seuare, Dara Ganj, New Del 110002 | Meleswaram, Bengalurs 560008 | Sitabuldi Nagpur 440012 (WAH) Mobie:9555778814/9818561840 | Kamataka: Mob 9686821074 Tel: 0712) 254.7128 Email: dehi@niraibookscom | Email: bengaluru@niraibeckscom | Email: nagpur@niaibeoks com KOLHAPUR JALGAON SOLAPUR Nirali Prakashan Nirali Prakashan Nirali Prakashan New Mahadve Road, ede Plaza, | 34, [Link] Market, Navi eth, | R-258/2, venti Naga, Neat Golden {Floor Opp DBI Bank Jalgaon 425001. Maharestre ‘Gate, Pune Naka Chowk Kolhapur 416 012 Maharashtra Tel: 0257) 222 0395, Solapur 413001, Maharastra Mob : 9850046155 Mob : 94234 91860 Mobile 9890818687 Email: kolhapur@nicalbookscom | Emall:jalgeon@niralinockscom | Email: solapur@niralivockscom A ce eee eeePreface... We take an opportunity to present this book entitled as “Core Java" to the students of Fifth Semester - B.B.A.(C.A). The object of this book is to present the subject matter ina most concise and simple manner. The book is written strictly according to the New Syllabus (CBCS Pattern). The book covers theory of Java Fundamentals, Classes, Objects and Methods, Inheritance, Package and Collection, File and Exception Handling, Applet, AWT, Event and Swing Programming. The book has its own unique features. It brings out the subject in a very simple and lucid manner for easy and comprehensive understanding of the basic concepts, its intricacies, procedures and practices. This book will help the readers to have a broader view on Core Jaya. The language used in this book is easy and vill help students to improve their vocabulary of Technical terms and understand the matter ina better and happier way. A special words of thank to Shri. Dineshbhai Furia, Mr. Jignesh Furia for showing full faith in us to write this text book. We also thank to Mr. Akbar Shaikh of M/s Nirali Prakashan for their excellent co-operation, We also thank Mr. Akbar Shaikh, Ms. Chaitali Takale, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat. Although every care has been taken to check mistakes and misprints, any errors, ‘omission and suggestions from teachers and students for the improvement of this text book shall be most welcome, Authors.Syllabus ... 1. 3. Java Fundamentals [Lectures 8] 1 12 13 14 15 16 17 18 Introduction to Java Basics of Java: Data Types, Variable, Expression, Operators, Constant Structure of Java Program Execution Process of Java Program JDK Tools Command Line Arguments Array and String 17.1 Single Array and Multidimensional Array 17.2. String, String Butfer Built In Packages and Classes 18.1 [Link]: Scanner, Date, Math etc 182 javalang Classes, Objects and Methods [Lectures 8] 21 22 23 24 Class and Object Object Reference Constructor: Constructor Overloading Method: Method Overloading, Recursion, Passing and Returning Object Form Method 25 Nev Operator, this and static keyword, finalize Method 26 Nested Class, Inner Class and Anonymous Inner Class Inheritance, Package and Collection Lectures 10] 3.1 Overview of Inheritance 3.2. Inheritance in Constructor 33 Inheriting Data Members and Methods 34 Multilevel Inheritance - Method Overriding Handle Multilevel Constructors 35 Use of Super and Final Keyword. 3.6 Interface 3.7 Creation and Implementation of an Interface, Interface Reference 38 Interface Inheritance 39 Dynamic Method Dispatch 3.10 Abstract Class 3.11 Comparison between Abstract Class and Interface 3.12 Access Control 3.13. Packages 3.13.1 Packages Concept 3.132 Creating User Defined Packages 3.13.3 Java Built Inpackages 3.134 Import Statement, Static Import314 Collection 3.14.1 Collection Framework. 3.142 Interfaces: Collection, List, Set 3.143 Navigation: Enumeration, Iterator, ListIterator 3.144 Classes: Linkedlist, ArrayList, Vector, HashSet, File and Exception Handling [Lectures 8] Exception 41 Exception and Error 42 Use of try, catch, throw, throws and finally 43 Built in Exception 44 Custom exception 45 Throwable Class. File Handling 46 Overview of Different Stream (Byte Stream, Character stream) 47 Readers and Writers class 43 File Class 49 File Input Stream, File Output Stream 410 Input Stream Reader and Output Strearn Writer Class ALL FileReader and FileWrler Class 412 Buffered Reader Class Applet, AWT, Event and Swing Programming [Lectures 14] Applet 51 Introduction 52 Types Applet 53. Applet Lifecycle 5.3.1 Creating Applet 53.2 Applet Tag 54 Applet Classes 541 Color 54.2 Graphics 543 Font AWT 55 Components and container used in AWT 56 Layout Managers 57 Listeners and Adapter Classes 52 Event Delegation Model Swing 59. Introduction to Swing Component and Container Classes 5.10 Exploring Swing Controls - JLabel and Image Icon, JText Field, The Swing Buttons JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane, JList, JTable, JComboBox, Swing Menus, Dialogs, IFileOpen, JColorChooser -Contents ... 4. Java Fundamentals 2. Classes, Objects and Methods 3. Inheritance, Package and Collection and Exception Handling 5. Applet, AWT, Event and Swing Programming Bibliography 41 - 1.50 2A = 2.32 34 - 3.72 44 - 4.40 5A - 5.88 BA-BAJava Fundamentals Learning Objectives... ‘To understand Basic Concepts of Java. To learn Structure of Java To study JDK Tools. To study Command Line Arguments, To learn about Array and String. To study Built In Packages and Classes. asa m B® wrropucine java ‘+ Java is a class-based, object-oriented, simple programming language. Java makes writing, compiling, and debugging programming easy. It helps to create reusable code and modular programs. + Java is used for Mobile applications, Desktop applications, Web applications, Web servers and Application servers, Games, Database connection, etc. + Java works on different platforms like Windows, Mac, Linux, Raspberry Pi, etc. ‘+ Java is related to C++, whichis a direct descendant of C. Much of the character of Java is inherited from these twro languages. From C, Java derives its syntax. Many of Java's object-oriented features were influenced by C++. + Itisa general-purpose programming language, intended to let application developers write once, run anywhere, Meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM). + Java enables computer programmers to write computer instructions using English based commands, instead of having to write in numeric codes. + Like English language, Java has a set of rules (syntax) that determine how the instructions are written. Once, a program has been written, the high-level instructions are translated into numeric codes that computers can understand and execute, (ayCore Java [BBA(CA): Sem. VI 42 Java Fundamentals cE History of Java Java was developed at Sun Microsystems (which has since been acquired by Oracle) in 1991, by a team of James Gosling, Patrick Naughton, Chris Wrath, Ed Frank and Mike Sheridan as its members. The language was initially called Oak. It was later termed as, Java, * Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lind holm were key contributors to the maturing of the original prototype + Java is a general-purpose, Object-Oriented Programming (OOP) language. James Gosling is called the father of Java Programming. ‘+ Java is an Object-Oriented Programming language means Java enables us not only to organize our program code into logical unit called objects but also to take advantage of encapsulation, inheritance, polymorphism and soon. + As of March 2021, the latest version is Java 16, with Java 11, a currently supported long-term support (LTS) version, released on September 25, 2018. Oracle released the last zero-cost public update for the legacy version Java 8 LTS in January 2019 for commercial use, although itwill otherwise still support Java 8 with public updates for personal use indefinitely. Other vendors have begun to offer zero-cost builds of OpenjDK 8 and 11 that are still receiving security and other upgrades. + Oracle (and others) highly recommend uninstalling outdated versions of Java because of serious risks due to unresolved security issues. Since Java 9, 10, 12, 13, 14, and 15 are no longer supported, Oracle advises its users to immediately transition to the latest version (currently Java 16) or an LTS release. * An application is a type of software that allows user to perform specific task. Sun Microsystems Inc. has divided Java into following parts 1. Java SE (Java Standard Edition): It contains basic core Java classes and used to develop standard applets and applications. 2. J2EE (Java Enterprise Edition): It contains classes that are beyond Java SE and used to providing business solutions on a network. 3. J2ME (lava Micro Edition): Java ME is for developers who develop code for portable devices like a PDA, a cellular phone and so on. FRE] Features of Java + Following are list of buzzwords: 1, Simple: Java is a simple language. There are various concepts that makes the Java as a simple language. Java is designed to be easy to learn. Programs in Java are easy to write and debug because Java does not use the pointers, preprocessor header files, operator overloading ete. 2. Secure: Java is aimed tobe used in networked or distributed environments. Java does not allocate direct pointer to memory, this makes it impossible to accidentally reference memory that belongs to other program.Core Java [BBA(CA): Sem. VI 43 Java Fundamentals 3. 4. 10. 11. Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Java code is portable. It was an important design goal of Java that it be portable so that as new architectures (due to hardware, operating system, or both) are developed, the Java environment could be ported to them. Object-oriented: Java is a truly object oriented language. Almost everything in java is an object. Java has a wide variety of classes. These classes are organized in various packages. We can use them in our programs while implementing inheritance. The object model in java is simple and easy to extend. Robust: Java is a robust language because it provides many safeguards to ensure reliable code. Java does not allow pointer which avoids security problem. There is no concept of reference variable. This eliminates the possibility of overwriting memory and corrupting data, Automatic garbage collection eliminates memory leaks. Multithreaded: Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multi-process synchronization that enables you to construct smoothly running interactive systems. Architecture-neutral: A central issue for the Java designers was that of code longevity and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. Their goal was "write once; run anywhere, anytime, forever.” To a great extent, this goal wes accomplished. Interpreted: As described earlier, Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. ‘Most previous attempts at cross-platform solutions have done so at the expense of performance. High Performance: The Java bytecode was carefully designed so that it would be easy to translate directly into native machine co¢e for very high performance by using a just-in-time compiler. Distributed: Java facilitates the building of distributed application by a collection of classes for use in networked applications. Java is designed for the distributed environment of the Internet, Dynamic: Java language is capable of dynamically linking in new class libraries, methods and objects. Because Java is interpreted, Java is an extremely dynamic language, at runtime, the Java environment can extends itself by linking in classes that may be located on remote servers on a network, for example, the Internet.Core Java [BBA(CA): Sem. VI a Java Fundamentals BASICS OF JAVA - DATA TYPES, VARIABLE, EXPRESSION, OPERATORS, CONSTANT Data Types + A computer has to process various types of data. Data type is a term that refers to the kind of data used in a program. Every programming language comes with a set of data types ready to use. * Java is a strongly typed language and this means that every variable and every expression has a data type known at compile time. 1. The Primitive Types: + Various primitive data types are listed below: (i) byte: © Byte data type is an &-bit signed two's complement integer. © Rangeis~128 to127. © Default valueis 0. © Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int. © Example: byte a = 100, byteb =-50 (ii) short: © Short data type is a 45-bit signed two's complement integer. © Minimum value is -32,768 and maximum value is 32,767. © Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int. © Default valueis 0. © Example: shorts = 10000, short (ii) int: © int data type is a 32-bit signed two's complement integer. © Range is - 2,147,483,648.. to 2,147,483,647. © intis generally used as the default data type for integral values unless there is aconcern about memory. © The default value is 0 © Example: int a = 100000, intb = -200000 (iv) long: © long data type is a 64-bit signed two's complement integer. © Range is -9,223,372,036,854,775,808... to 9,223,372,036,854,775,807. © This type is used when a wider range than int is needed. © Default values OL. © Example: long a= 1000001, int b 20000 2000001.Core Java [BBA(CA): Sem. VI 4s Java Fundamentals (v) float: © float data type is a single-precision 32-bit IEEE 754 floating point. © float is mainly used to save memory in large arrays of floating point numbers. © default value is 0.0f. © float data type is never used for precise valuessuch as currency. © Example: float f1=234.5f (vi) double: © double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data type for decimal values, generally the default choice. © Double data type should never be used for precise values such as currency. © Default valueis 0.04. © Example: double di = 123.4 (vii) boolean: © boolean data type represents one bit of information. There are only two possible values: true and false. This data type is used for simple flags that track true/false conditions. © Default value is false © Example: boolean one = true (viii) cha © char data types a single 16-bit unicode character. © Minimum value is '\u0000' (or 0). © Maximum value is \uffff (or 65,535 inclusive), © Char data type is used to store any character. © Example: char lettera, 2, Reference Data Types: ‘+ Reference data types are made by the logical grouping of primitive data types. ‘+ These are called reference data types because they contain the address of a value rather than the value itself. + _Arrays, classes, enum etc., are the example of reference data type. Variables + Variables are the identifier of the memory location, which used to save data temporarily for later use in the program. During execution of a program, values can bestored in a variable, and the stored value can be changed. + While naming Java variables we have following naming rules. 1. Variable names are case-sensitive. 2. Variable name can be an unlimited-length sequence of Unicode letters and digits.Core Java [BBA(CA): Sem. VI 16 Java Fundamentals 3. Variable name must be underscore character jin with either a letter or the dollar sign "6", or the ‘No white space is permitted in variable names. Variable name must not be a keyword or reserved word. Do not begin with a digit, 7,_Aname can be of any realistic length. aoe Program 1.1: Program for variables. public class AddTwoNunbers t public static void main(String args{]) { int nund = 50; int num2 = 155 int sum; sum = numi + numa; [Link]("Sum of Numbers: “+sun); } } Output: Sun of Numbers: 65 Expression ‘+ Expressions are essential building blocks of any Java program, usually created to produce a new value, although sometimes an expression assigns a value to a variable. ‘+ Anexpression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language that evaluates to a single value. Expression evaluation in Java is based upon the following concepts: 1. Type conversion: It has two types based on how the conversion is performed: (i) Implicit conversion: It is also known as automatic conversion. This type of conversion is performed automatically by Java due to performance reasons. Implicit conversion is not performed at all times. For example, Java will automatically convert a value of byte into int type in expressions since they are both compatible and int is larger than byte type. (ii) Explicit conversion: It is also known as Type Casting. There may be situations where you want to convert a value having a type of size less than the destination type size. In such cases Java will not help you. You have do it on your own explicitly. That is why this type of conversion is known as explicit conversion or casting as the programmer does this manually.Core Java [BBA(CA): Sem. VI a7 Java Fundamentals Example: int 85 byte b = (int) as //integer value to be converted into a byte type ‘Type promotion rules of Java for expressions are listed below: © Allchar, short and byte values are automatically promoted to int type. © If at least one operand in an expression is a long type, then the entire expression will be promoted to long. © If at least one operand in an expression is a float type, then the entire expression will be promoted to float. © If at least one operand in an expression is a double type, then the entire expression willbe promoted to double. 2. Operator Precedence: Operator precedence determines the order in which the operators in an expression are evaluated. Table 1.1: Operator Precedence Operators Associativity equality left toright bitwise AND & left to right bitwise exclusiveOR | * left to right bitwise inclusiveOR | | left to right Program 1.2: Program for operator precedence. class Precedence t public static void main(String] ares) { int a 18, b= 5, result = a-t+c~44b; [Link](result); 1, result; } Output: 2 ‘+ The operator precedence of prefix + is higher than that of - subtraction operator. 3. Associativity of Operators in Java: If an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, orright toleft). Example: (i) dzasbte Since + operator is left associative therefore a+b will solve first and then the result will be added to c.Core Java [BBA(CA): Sem. VI 1s Java Fundamentals (il) d=arb*e Since exponent operator is right associative therefore bc will soved first and then a* result of b*c FEZ] operators ‘+ Operators in Java can be classified into 6 types: 1. Unary operators: + Unary plus operator; indicates positive value, = Unary minus operator; negates an expression. ++ Increment operator; increments a value by 1. -- Decrement operator; decrements a value by 1. 1 Logical complement operator; inverts the value of a Boolean. Program 1.3: Program for unary operator. public class Unary { public static vold main(string argst]) { Ant 2920; System. out .printIn(a++); system. [Link](++a) ; [Link](a--)} [Link]. printIn(--a); Output: 28 2 2 26 2, Arithmetic operators: + Additive operator (also used for String concatenation) - Subtraction operator * Multiplication operator Division operator Remainder operator RsCore Java [BBA(CA): Sem. VI 19 Java Fundamentals Program 1.4: Program for Arithmetic operator. public class Arithmetic { public static void main(String args) { int int System. [Link](a+b) ; System. out .printIn(a-b) ; System. out .printin(a"b) ; System. out .print1n(a/b) ; 3 + output: 30 10 200 2 3. Bitwise and Bit Shift Operators ~~ Unary bitwise complement << Signed eft shift >> Signed right shift >>> Unsigned right shift & — Bitwise AND * Bitwise exclusive OR |__ Bitwise inclusive OR Program 1.5: Program for Bitwise and Bit Shift Operator. public class Bitwise { public static void main(String args[]) t int c=53 System. out print1n(20<<2); [Link] .print1n(26>>2); System. out .printIn(acb&acc); y output: 86 5{Core Java [BBA(CA): Sem. V1 110 Java Fundamentals 4, Logical operator: The logical 68 operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true. logical AND aa logical OR Il Program 1.6: Program for Logical Operator. public class Logical { public static void main(String arge[]) t int a int 6: int [Link] .printIn(acb&aa
Greater than >= Greater than or equal to < Less than Less than or equal to Program 1.8: Program for equality and relational Operator. public class Euglity { public static void main(StringL] args) { int x = 105 [Link](" == y")3 4F(% Ie y) [Link]("x != y")3 iF(x > y) [Link]("x > y")3 if < y) [Link]("x < y")3 SF(x < y) [Link]("% <= y")3 y } xey 7. Assignment Operator: Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.Core Java [BBA(CA): Sem. VI a2 Java Fundamentals Table 1.2: Assignment Operator, Usage and Effect Usage Program 1.9: Program for assignment Operator. public class Assignment { public static void main(string[] args) { int a=10; int b=205 ated; //anatd (291014) b-n43//o=b-4 (b-20-4) [Link] .printIn(a); [Link] printin(b)5 t } Output: 4 16 EX] constant + Avalue which is fixed and does not change during the execution of a program is, called Constants in java, In other words, Java constants are fixed (known as immutable) data values that cannot be changed. Java supports various types of constants.Core Java [BBA(CA): Sem. VI 13 Java Fundamentals Java Consianis fp Numeric Constants Non-numeric Constants Integer Real ‘Character String Constants Constante Constants Constants Fig. 11: Classification of Java Constants L_ Integer Constants: + An integer constant is a sequence of digits without a decimal point. For example, 10 and -200 are integer constants. There are three types of integer constants. They are as follows: © Decimal integer: For exemple: 24, -55, 0 a Octal integer: Example: 0123,024 9 Hexadecimal integer: Example: 0x23, ox5B 2. Real Constants: + Real constants consist of a sequence of digits with fractional parts or decimal points. These constants are also called floating-point constants. The valid examples of real constants are 2.3, 0.0034, -0.75, 56.7, etc. 3. Character Constants: ‘+ A single character constant (or simply character constant) is a single character enclosed within a pair of single quote. The example of single-character constants are: Sy," ete 4, String Constants: + A string constant is a sequence of characters within a pair of double-quotes. The characters can be alphabets, special characters, digits, and blank spaces. The valid examples of string constants are: "Hello Java", "192. Backslash Character Constants: + Java provides some special backslash character constants that are used in output methods. For example, the symbol 'n' which stands for newline character. + There are various types of backslash character constants that are supported by java. The list is given in the belowtable.Core Java [BBA(CA): Sem. VI 14 Java Fundamentals Table 1.3: Backslash Character Constant Constants ‘Meaning ‘Nb! back space Mr form feed ‘\n" new line carriage return ‘Nt horizontal tab vu | single quote | double quote \ backslash Types of Comments ‘+ Comments are non-executable statements and are ignored by the Java compiler. The comments increases the readability of the programs. ‘+ Comments are an integral part of any program. They help the person reading the code (often you) better understand the intent and functionality of the program. + Java language provides three styles of comments as given below: 1 Line Comments: © It start with two forward slashes (//) and continue to the end of the current line. Line comments do not require an ending symbol. © Java's single line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. Example: //This is Single Line Comment 2. Block Comments: Java's multi-line or slash-star or traditional comment is a piece of text enclosed in slash-star (/*) and star-slash (*/). Java's multi-line comments are useful when the comment text does not fit into one line; therefore needs to span across lines. Example: /*This is Multi Line Comment */ 3. Javadoc Comments: 2 Javadoc comments are used to document the new classes you create as a programmer i. provide information about the class for users of the class toread. © Java documentation comments is given by /**.n.u."/. Example: /** Welcome to Wirali Prakashan */Core Java [BBA(CA): Sem. VI 145 Java Fundamentals Program 1.10; Program for Java comment. This is a Documentation Connent. + public class CommentsDemoExample { public static void main(String args{]) { /* This is a Multi-line Comment */ [Link]("Hello World");// This is a Single Live Comment. t yea STRUCTURE OF JAVA PROGRAM Java Program Structure: * Java program may contain many classes, of which main( is defined in only one class. * Classes in Java program contain data members and methods, that operate on the data members of the class. Methods in Java program may contain datatype declarations and executable statements. + Towrite a Java program, we first define classes and then put them together. Documentation Section Suggested Package Statements Optional Import Statements Optional Interface Statements Optional Class Definitions Optional ‘Main method class Essential Fig. 1.2: Structure of Java Program ‘+ AJava program structure contains following sections 1. Documentation Section: This section is a set of comment lines giving the name of the program, the author and the other details, which the programmer would like torefer. 2. Package Statement: In Java files, the first statement allowed is a package statement, This statement declares a package name and informs the compiler that the classes defined here belong to this package. For example: package employee:Core Java [BBA(CA): Sem. VI 116 Java Fundamentals 3. 5. First Java Program: 1 Navan Import Statement: Similar to #include statementin C. For example, import [Link]; Import statement instructs the interpreter to load the test class contained in package employee. Using import statement; we can access to classes that part of, other named packages. Interface Statement: An interface is like class but includes group of methods declaration. Interfaces are used when we want to implement multiple inheritance feature. Class Definition: Java program may contain many/multiple class definition. Classes are primary feature of Java program. The classes in Java are used to map real-world problems. Main Method Class: Java stand-alone program requires main method as starting point and this is essential part of program main() method in Java program creates object of various classes and on reaching, end of the main the program terminate and the control passes back to the operating system. public class MyProgran { public static void main(String[] args) { [Link]("My First Java Progran"); 3 } Output: My First Java Program Explanation: + Thebasic unit of a Java program is a class. A class called "AyProgran" is defined via the keyword "class" in Lines 2-7. The braces { encloses the body of the class. public class MyProgran { } + In Java, the name of the source file must be the same as the name of the class with a mandatory file extension of "java". Hence, this file must be saved as “[Link] -ase-sensitive. public static void main(String[] args) {Core Java [BBA(CA): Sem. VI 447 Java Fundamentals + Lines 3-6 defines the so-called main() method, which is the entry point for program execution, Again, the braces {.....} encloses the body of the method, which contains programming statements. + In Line 5, the programming statement [Link]("My First Java Program") is used to print the string "My First Java Program" to the display console, A string is surrounded by a pair of double quotes and contain texts. The text will be printed as it is, without the double quotes. A programming statement ends with a semi-colon () Res EXECUTION PROCESS OF JAVA PROGRAM + Bample: public class MyFirstJavaProgram { /* This is my first java program. * This will print ‘Hello World’ as the output */ public static void main(String [Jargs) { ‘[Link]("Hello World"); // prints Hello World + + Let's look at how to compile, and run the program. Compiling the Program: + To compile the above program, execute the compiler, javac specifying the name of the source file on the command line. This is shown below: C:\> javac MyFirstJavaProgram. java + Javac compiler creates a file named ‘[Link]' which contains the byte code version of the program. It is an intermediate representation of the program. Executing the Program: + Toactually run the program you must use the Java application launcher called ‘java’. This is shown below: :\> java MyFirstJavaProgram Output: C:\> Javac MyFirsthelloProgram. java C:\> java MyFirsthelloProgram Hello WorldCore Java [BBA(CA): Sem. VI 118 Java Fundamentals rl JDK TOOLS The JDK is a software development environment which is used to develop java applications and applets. ‘+ JDK (ava Development Kit) provides environment to develop and run java applications. * Java Development Kit has a collection of tools for Java Development. JDK contains JRE along with various development tools like Java libraries, Java source compilers, Java debuggers, bundling and deployment tools. JRE is part of JDK but can be used independently to run any byte code (compiled java program). It can be called as JVM implementation. ‘+ The JDK comes with a set of tools that are used for developing and running Java program. It includes: 1. Javac: It isa Java compiler. 2. Java: Itis a java interpreter. 3. Javah: tis for java C header files. 4, Jab: Itis Java debugger. 5. AppletViewer: It is used for viewing the applet. 6. Javap: Java disassembler, which convert byte code into program description. 7. Javadoc: It is used for creating HTML document. ia COMMAND LINE ARGUMENTS ‘Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command line arguments to main(). + Acommand line argument is the information that directly follows the program name onthe command line when it is executed. + AJava application can accept any number of arguments from the command line. This, allows the user to specify configuration information when the application is launched, + Toaccess the command line arguments inside a Java program is quite easy - they are stored as strings in a string array passed to the args parameter of main(). The first command line argument is stored at args[0], the second at args[1], and soon. + The following program displays all of the command line arguments that it is called with: public class ConandLine { public static void main(String args[]) t for(int 1 = @} [Link]; i++) { [Link](“args[" + i + "J: "+ args[i]); } }Core Java [BBA(CA): Sem. VI 119 Java Fundamentals ‘Try executing this program as shown here: Sava ConmandLine this is a command line 20@ -100 This will produce the following output: args[@]: this args[1]: is args[2]: a args(3]: command args[4]: Line args[5]: 268 args[6]: -100 Example: The following Program illustrate that how to take input as two numbers from ‘the user and display the addition with two input methods: BufferedReader and Command Line arguments. import [Link].*; import [Link]; class demo public static void main(String arg[]) throws Exception { [Link] .print1n(” methods") 5 //input using BufferedReader dition of two numbers using three input int x,y5 BufferedReader b=new BufferedReader(new InputStreanReader ([Link]))5 [Link](“enter two numbers"); [Link]([Link]()); [Link]([Link]()); [Link] println("sum is=" +(x4y))5 // Input using Connand line arguments int [Link](arg[@]); [Link](arg[1])5 int sum sumi=a+ds [Link](sumt) ;Core Java [BBA(CA): Sem. VI 120 Java Fundamentals + When we accepting input from console we need to BufferedReader and scanner class. + BufferedReader improves performance by buffering input. The BufferedReader class does have a method called readline that does return aline of text as type by the user. ‘+ InJava, the [Link] Scanner or Scanner class is one of them which allows the user to read values of various typesin java. + Anarray is a group of similar type variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. ‘+ A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information, + Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. ‘+ Array is a contiguous fixed-length structure for storing multiple values of the same type. Array in Java is index based, first element of the array is stored at 0 index. Fist ndex dene, o] 1 2 3 4 5 6 7 \8 Se —indoes | ray tenth is 10 ig. 13: Arrays Single-Dimensional (1D) Array + Anarray is a sequence of variables of the same data type. Array having only one subscript variable is called One-Dimensional array. + Itis also called as Single-Dimensional Array or Linear Array. + Aone-dimensional array is, essentially, a list of similar type variables, To create an array, you first must create an array variable of the desired type. * Todeclare an array, you specify the name of the array and the data type, as you would for any other variable, Adding an empty set of brackets ([ ]) indicates that the variable is an array, + The general form/syntax ofa one-dimensional array declaration is given below: datatype array_name [];Core Java [BBA(CA): Sem. VI 21 Java Fundamentals + Here, type declares the base type of the array. The base type determines the data type of each element that comprises the array. Thus, the base type for the array determines what type of data the array will hold. + For example, the following declares an array named month_days with the type "array ofint": int month_days{13 Instantiating Arrays: + Aswe mentioned earlier, Java arrays are objects, so to allocate memory for an array, you need to instantiate the array using the new keyword. Here, is the syntax for instantiating an array: array_name = new datatype[size]; Where, size is an expression that evaluates to an integer and specifies the number of elements in the array. For example: month_days = new int(12]; Assigning Initial Values to Arrays: + Java allows you to instantiate an array by assigning initial values when the array is declared. To do this, you specify the initial values using a comma-separated list within curly braces as given below: datatype array_nane[] = {value@, valuel, value2, ... valueN}; ‘Where, valueN is an expression that evaluates to the data type of the array and is the value to assign to the element at index N. + Note that, we do not use the new keyword and we do not specify a size for the array, the number of elements in the array is determined by the number of values in the initialization list. + Forexample, following statement declares and instantiates an array of Numbers: int nine = 95 int[ ] Numbers = {2, 4, 3, 8, one, one + 2, 13, 14, 17, 18} * Because 10 values are given in the initialization list, this array has 10 elements, Notice that the values can bean expression, for example, one and one + 2. Program 1.11: Program for one-dimensional (1D) array. import [Link]. class arraydeno t public static void main(String args{]) { int a[]={2,4,6,3,1}5 [Link]..printIn(” [Link]("Elements in array a:" + [Link]); lunber of elements in array a: "+[Link]);Core Java [BBA(CA): Sem. VI 422 Java Fundamentals for(int 8034 <[Link]+) [Link] (a[i] + "\t"); 3 + output: Number of elements in array a: 5 Elements in array a: 2 46 3 1 Program 1.12: Program to print Odd and Even Numbers from an Array. public class Exoddevenarray t public static void main(String args[]) t int arr[]=(10,23,54,61,32,22}3 //Declaration of Array [Link]("Even Array Elements:"); for(int 10; [Link];i++) { if(are [1 ]82: i [Link](arr[4]) 5 } + [Link] printIn("Odd Array Elements: for(int 10; {<[Link]++) { if(arr[i]%2!=0) { System. out .printIn(arr[i]); } } + } output: Even Array Elements: 10 54 32 2 Odd Array Elements: 23 6Core Java [BBA(CA): Sem. VI 123 Java Fundamentals Multi-Dimensional (2D) Array + InJava, multi-dimensional arrays are actually arrays of arrays. These arrays look and act like regular multi-dimensional arrays. * Todeclare a multi-dimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two- dimensional array variable called twoD. int twoD[][] = new int[4][5]; Right index determines column | | 4 oo} (001 toe] (ore) 1) myo) eae) eel} eo [ tia) Loft index: determines row eo) aca) wel) ea | et) a] 3a) eel] eel | pI) int two [] [] = new int (4 15]; Fig. 1.4: 2D Array Declaration ‘+ Todeclare a multi-dimensional array, we use the same syntax as for an array, except that we include an empty set of brackets for each dimension. + Here is the general syntax for declaring a Two-Dimensional (2D) array: datatype array Nane[] [3 + Here is the general syntax for declaring a Three-Dimensional (3D) array: datatype array_nane [] [] [13 Instantiating Multi-dimensional Arrays: + Just like instantiating 1D arrays, you instantiate a multi-dimensional array using the new keyword. Here, is the syntax for instantiating a 2D array: array_name = new datatype [expl][exp2]; ‘Where, expl and exp2 are expressions that evaluate to integers and specity, respectively, the number of rows and the number of columns in the array. ‘+ Above statement allocates memory for the array. The number of elements in a two- dimensional array is equal to the sum of the number of elements in each row, + When all the rows have the same number of colurnns, the number of elements in the array is equal to the number of rows multiplied by the number of columns.Core Java [BBA(CA): Sem. VI 124 Java Fundamentals Program 1.13; Program for Two-Dimensional (2D) array. class TwoDArray { public static void main(String args[]) { Ant twoD[][]= new int[4][5]5 int i, i, k= 5 for(imd; ica; i+) for(j-@3 553 J++) { ‘twod[4] [5] = ks kets } For( { For(j=05 553 j++) [Link] (twoD[4][J] + [Link](); 3 cds dee) + output: e@1234 56789 te 11 12 13 14 15 16 17 18 19 Program 1.14; Program to read and display 2D Array. class Example2d t public static void main(String[] args) { int] arr ={ (42,3) (45,6347, 8,93 for (int i= 0; i ¢ 3; in) { for (int j = @; 4 < 35 i+) t [Link]("arr["+i+ "][" + J+ "] =" arrlillj))s + + [Link](“Array Elements:Core Java (BBA(CA): Sem. VI 125 Java Fundamentals for (int i= 0; ic 3; irr) { for (int j = 0; j < 33 j++) i [Link](" "+ arr[i][i])5 + [Link](); + Output: arr[9][9] arr[9][2] arr[9][2] arr[1][9] = arr[4}[1] = arr[1][2] = arr[2}[0] are[2][2] arr[2][2] = 9 Array Elements: 123 456 739 Program 1.15: Program Demonstrate a three-dimensional array. class ThreeDMatrix { public static void main(String args[]) t Ant threeD[I[1E] = new ant{3}(4][513 ke53 k++) threeD[i][5][k] = i * 5 * ksCore Java [BBA(CA): Sem. VI 126 Java Fundamentals for(in; ic3; ire) { For(j=05 $<4s j++) { For(keo3 kes; k++) [Link] .print(threeD[4][J][k] +" [Link] .println(); > [Link](); 3 3 } Output: e0000 e000 e0000 e0000 Program 1.16: Program addition of two matrices class Testarray { public static void main(String args[]) { //creating two matrices int af][]=((1,3,4),(3,4,5)}5 int b[][]=((1,3,4},(3,4,5}}5 Jicreating another matrix to store the sun of two matrices Ant ¢[][]=new int [2][3]; //adding and printing addition of Two matrices for(int 1=01<2;i++) { For (int 3-055<3;5++) t [4] (5]=a[i](5]+e(3] 0515 ‘[Link] .print(c[i][]+" + [Link] .printin()3//new LineCore Java [BBA(CA): Sem. VI 427 Java Fundamentals Program 1.17: Program for sorting elements in array. import [Link]; class SortIntArrayExample t public static void main(String[] args) { J/create an int array Ant[] i1 = new ant(}{3,2,5,4,1}5 Jiprint original int array [Link]("Original Array: "); for(int index=0; index < [Link] ; index++) + 4i[index]); [Link](" [Link](i1)5 H[print sorted int array [Link]("Sorted int array: ")3 for(int index-@; index < id-length ; indexs+) [Link] print(" "+ i1[index]); int[] 42 = new ant{]{5,2,3,1,4}5 [Link](i2,1,4)5 JIprint sorted int array [Link] ("Partially Sorted int array for(int index=9; index < [Link] ; index++) + i2[index]) ; [Link](* + Output: Original Array: 3.2541 Sorted int array: 12345 Partially Sorted int array: 51234 Program 1.18: Program to reverse elements in array. import java-util.*; class Reversearray { public static void main(String args[]) { // Create [Link] object for taking input Scanner senew Scanner (System. in);ore Java (BBA(CA): Sem. VI 128 Java Fundamentals // Take [Link] elements and store it inn [Link]("Enter the [Link] elenents int _n=[Link]()3 1] Create array of size n int af]=new int{n]; // Read clenents into the array [Link]("Enter the elements into the array:"); for(int 4=05i
"); n=[Link]([Link]());Core Java [BBA(CA): Sem. VI 143 Java Fundamentals for (is0;icnjier) { [Link]("Enter the "sit" Number of the Array p[i]= Integer. parsernt([Link]()); } For(j=053<10;3++) { int fla FCPS t continue; + else t + if (Flag { primefk]=r[3]5 key y } [Link]("\nPrime Nunbers are"); For(1-jickji++) { [Link]. print (prime[i]+" } > } Output: Enter the Number of Elenents :=> a Enter the @ Number of the Array : 3Core Java [BBA(CA): Sem. VI Enter the 1 Number of the Array : 2 Enter the 2 Number of the Array 4 Java Fundamentals Prime Numbers are 3 2 Program 1.25: Java program to count vowels, consonants, digits, and spaces of given word. a5) public class Main { public static void main(String[] args) 1 string line = "This website is aw3son3."5 int vonels = @, conscnants = @, digit: line = [Link](); for (int i = 0; 4 < [Link](); 14) { char ch = [Link](i); // check if character is any of a, e, i, 0, u if (ch == 'a" [| ch TL ch Ich { s4vowels; 3 // check if character is in between a to z else if ((ch >= ‘a’ && ch <= 'z")) { +4consonants; } // check if character is in between @ to 9 else if (ch >= '@' && ch <= '9") { @, spaces sHdigits; + // check if character is a white space else if (ch ==" ') { +4spaces;Core Java [BBA(CA): Sem. VI 145 Java Fundamentals [Link]("Vowels: " + vowels); [Link]("Consonants: " + consonants) ; [Link]("Digits: " + digits); [Link]("khite spaces: " + spaces); } Output: Vowels: 7 Consonants: 11 Digits: 2 nite spaces: 3 Program 1.26: Write a java program to accept n names of cities from users and display them in descending order. EH import java-util.*; class City t //eeclaration of array string af]; int 3 city() { Scanner senew Scanner([Link]); [Link]("Enter how many city you want to enter + enextInt()5 Iiredeclartion of array asnew String[n]; 1/70 accept values for(int 1=0;1
8) { temp=a[i]5 alil-a[J]s alJ]=temp; + + + [Link]("Sorted Cities are "); for(int i-@sicnsitt) { [Link](a[il+" ")3 //7o create object public class Testcity { public static void main(String args{]) { Output: Enter Enter Enter Enter Enter Enter City ob; how many city {ist} element: {ist} element: {as1} element: {4+1} element: {4s1} element: Sorted Cities are en City ()5 obj .display(); you want to enter : 5 Pune satera Kolhapur Nagpur Pampr Kolhapur Nagpur Pimpri Pune SataraCore Java [BBA(CA): Sem. VI 147 Java Fundamentals Erte > > James Gosling is called Father of Java Programming. Java is an Object Oriented Programming language means Java enables us not only to organize our program code into logical unit called objects but also to take advantage of encapsulation, inheritance and polymorphism and so on. Various features of java includes Simple, Secure, Portable, Object-oriented, Robust, Multithreaded, Architecture-neutral, Interpreted, High Performance, Distributed, Dynamic. Java defines eight primitive types of data: byte, short, int, long, char, float, double, and Boolean. An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. Array is a data structure where we store similar elements. We can store only fixed set of elements in a Java array. Types of array-1D array, 2D array. A one-dimensional array having only one subscript. In Java 2D array is a matrix of rows and columns. Java Math class provides several methods to worlon math calculations like minQ, max(), avg0, sin0, cos0, tan(), round), ceil, floor(, abs( ete. Scanner is a class in [Link] package used for obtaining the input of the primitive types like int, double, etc. and strings. A package is a collection of classes and interfaces. Peeters Oey 1 Which of these is necessary to specify at time of array initialization? (a) Row (®) Column (©) Both Row and Column (A) None of the mentioned Which of these classes is not included in [Link]? (@) Byte (&) Integer (©) array (@ Class Which of these is a super class of wrappers Double 6 Integer? (@) Long () Digits (©) Float (@) Number Which of the following package stores all the simple data types in java? (@) lang () java (©) util (@) [Link] Which one of the following will declare an array and initialize it with five numbers? (@) Array a=new Array(5); () int (Ja = (23,22,21,20,19}; (©) inta {] = new int{s}; (@) int (5) array;Core Java [BBA(CA): Sem. VI 1.48 Java Fundamentals 6 Which Scanner class method is used to read integer value from the user? (a) next) (0) nextinteger) (©) nextint) (@) readint() 7. Whatis the output of this program? class increment { public static void main(String args[]) t int g = 33 [Link](++g * 8); } + (@) 25 (&) 24 (©) 32 (@ 33 8, Which is the correct syntax to declare Scanner class object? (@) Scanner objectName= Scanner(); (&) Scanner objectName= new Scanner(); (©) Scanner objectName= Scanner([Link]); (@) Scanner objectName= new Scanner([Link]); 9. How to format date from one form to another? (2) SimpleDateFormat (&) DateFormat (©) SimpleFormat (@) DateConverter 10, Howr to format date from one form to another? (2) SimpleDateFormat (&) DateFormat (©) SimpleFormat (@) DateConverter Answers 1@ | 2© | 3@ | 4@ | 5 | 6@ | 7 | 8@ | 9) | 10a) Paredes Q1 Answer the following questions in short. 1. Whatis Java? Why Java is platform-neutral language? Explain the secure feature of Java. Why Java is called portable? ‘How to compile Java program? How to run Java program? ov aeyeCore Java [BBA(CA): Sem. VI 149 Java Fundamentals Ql Answer the following Questions. PReraueene Explain atleast five features of Java. Why Java needs compiler and interpreter? What is a variable? What rules can be applied to have a valid variable name? Explain primitive data types in detail. Explain reference or non-primitive data types. Whats array? ‘How a comment is added in java program? What are the types of array? Explain [Link] package. 10, Explain [Link] package. 11, Explain scanner, math, date class in java. 12, Predict the output: Class Test Public static void main (string [ ] args) ‘ int [] x= (4, 2,3, 4}5 int ly =x5 x = new int [2]; for (int i = @; i < [Link]; i ++) System. out. println (y [i])3 a 2 3 4 QiIl Define the terms. 1 ayaen Array string Package Variable Constant ‘Type castingCore Java [BBA(CA): Sem. VI 150 Java Fundamentals Pouce [Winter 2038| 1. Describe any two features of Java programming language. a Ans. Referto Section 1.1.2. 2. What are differences between String and StringBuffer class? Ans. Refer to Section 17.22. 3. "Import statement is not essential in java." True/False. Justify. Ans. Refer to Section 1.3. 4. Explain Array in Java. How does it differ from C++? Ans. Refer to Section 17.1. 5. Write a Java program to accept 'n' numbers through command line and store all prime numbers into an array and display elements of array. Ans. Refer to Program 1.24. 6. Write a Java Program that displays the number of non-vowels in the given word. Ans. Refer to Program 1.25. ‘Summer 2019] 1. Does the order of public static void matter in main method. Ans. Refer to Section 13. 2. Write a java program to accept n names of cities from users and display them in descending order. Ans. Refer to Program 1.26.2 Classes, Objects and Methods Learning Objectives.. To understand Basic Concepts of Objects and Classes. {Ml To study Constructors and Methods. H To learn Nested Classes, Inner Class, Anonymous Inner Class in Java. '| To learn New Operator, this and static keyword, finalize() method. Fa cuss anp onject + In Object Oriented Programming (OOP) technique, we design a program using objects and classes. Object is the physical as well as logical entity whereas class is the logical entity only. + Java is not fully object oriented programming language because it makes use of eight data types such as boolean, int, char, double, long, short, float and byte which are not object. EBB] overview of classes + Classes in Java provide a convenient method for packing together a group of logically related data items and functions that work on them. + In Java language, the data items are called fields and the functions are called methods. Calling a specific method in an object is described as sending the object of message, + A dass can be defined as, "a template/blueprint that describes the behaviors that object of its type support’ ‘+ Acass is declared by use of the class keyword. The classes that have been used up to this point are actually very limited examples of its complete form. eaCore Java [BBA(CA): Sem. VI 22 Classes, Objects and Methods + Asimplified general form/syntax of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; ‘type instance-variableN; ‘type methodnamel (paraneter-list) { /1 body of method } ‘type methodname2(parameter-List) { + ‘type methodnameN(parameter-List) { + } + Example of Class: Class Employee { 11 body of method 11 body of method int Emp1D; float salary; Program 2.1: Program for class. public class JavaClassexemple t public static void main(String[] arg) t for (int i= 05 ics itt) ‘ [Link]("Number is: “+1); } } } Output: Nunber is: @ Number is: 1 Nunber is: 2 Nunber is: 3Core Java [BBA(CA): Sem. VI 23 Classes, Objects and Methods ERE) overview of objects ‘Ateal-world entity that has state and behavior is known as an Object. These real-world objects share two characteristics i. state and behavior. Example: A cat has states - color, name, etc. as well as behaviors like walking and eating. In simple words, object is an instance of a class, Fig. 2.1 shows a real world example of class and objects. Fig, 2.1 shows class Car has objects like Audi, Nissan, Volvo. class objects Audi Nissan Volvo Example of Class and Object Declaring Objects: ‘When you create a class, you are creating a new data type. You can use this type to declare objects of that type. However, obtaining objects of a class is a two-step process. () Declaration: (i) instantiation (Creating Objects) © We have to specify what type (ie. class) the object will be. A variable declaration with a variable name with an object type. 9 Syntax: objectnane; Where, classname is the name of the already defined class and the objectname is a valid identifier. 2 Objects are created using the ‘new’ keyword. This ‘new’ keyword creates an object of the specified class and returns the reference of that object. > The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object. 9 Syntax: = new classname([arguments]) 5 > Letus create an object for the Box class. Box mybox = new Box(); > This statement combines the two steps just described. It can be rewritten like this to show each step more clearly: Box mybox; // declare reference to object mybox = new Box(); // allocate a Box objectCore Java [BBA(CA): Sem. VI 24 Classes, Objects and Methods Statement Effect Box mybox; null mybox. ‘mybox = new Box(); —}—|_ win mybox Height Depth Box object Fig. 2.2: Object Instantitation (iii) Accessing Class Members: «The dot operator () or member selection operator is used to access the instance variables of the class. ‘© We cannot access the instance variables outside of the class without referring to the object. © Member access follows the following syntax: [Link] Here, the objectname is the name of the object and variablename is name of the instance variable. So, the instance variables of the class Employee can be accessed as, Employee.£_id=1234; Employee. salary=300005 Program 2.2: Program for declaration and instantiation of object. class Myobject { public void getMessage() t [Link].print1n("Object Created and Functioned Called"); + public static void main(string args{]) { MyObject x = new MyObject(); //x is declared and initialized with an instance of MyObject [Link](); + Output: Object Created and Functioned CalledCore Java [BBA(CA): Sem. VI 25 Classes, Objects and Methods Difference between Class and Object: ‘+ There are many differences between object and class. A list of differences between, object and class are given below: Table 2.1: Difference between Class and Object | [Link]. Class Object 1. _| Class is a blueprint or template from | Objectis an instance of a class. which objects are created. 2. | Classisa group of similar objects. | Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc. 3.__| Class is a logical entity. Objects a physical entity. 4,__| Class is declared using class Keyword | Object is created through new like class Student{ ... } keyword like, Student si=new Student (); 5. _ | Classis declared once. Object is created many times as per requirement 6. _ | Class doesn't allocated memory when | Object allocates memory when it is itis created. created. 122) OBJECT REFERENCE The objects are constructed and allocated in memory independently from the declarations of variables. Specifically: 1. Objects denoted by a literal (such as literals of type String, e.g., "foo", are allocated in memory at compilation time. 2. Allother objects must be constructed and allocated through an explicit statement. ‘+ Avariable whose type is a class contains a reference to an object of the class (ie,, the adress of the memory location where the object is allocated). ‘+ A variable is a reference to a memory location in which an object is stored. To represent variables and their values we use the following graphical notation. jao", etc.) oot 001 Classi ' Classi last vart [oott vari sring x 1011 x [Pheto™ 010 In Intvar2 [_25 My[bas var2 [25 ets an Typed vara. 7] pot vars? ‘Sting hello —el reTTTTT] Fig. 2.3: Reference to object of variable
You might also like
Object Oriented Programming Using Core Java Nirali
PDF
100% (2)
Object Oriented Programming Using Core Java Nirali
114 pages
Object-Oriented Programming in Java
PDF
100% (3)
Object-Oriented Programming in Java
465 pages
Core Java for BBA Semester V
PDF
No ratings yet
Core Java for BBA Semester V
292 pages
Dot Net Framework Textbook for BBA Students
PDF
100% (2)
Dot Net Framework Textbook for BBA Students
305 pages
Advance PHP for BBA Semester IV
PDF
100% (3)
Advance PHP for BBA Semester IV
201 pages
Advanced: Java Programming
PDF
0% (1)
Advanced: Java Programming
181 pages
Web Technologies - I Textbook for B.Sc.
PDF
100% (1)
Web Technologies - I Textbook for B.Sc.
301 pages
Operating System for BBA (CA) Students
PDF
50% (2)
Operating System for BBA (CA) Students
223 pages
OOP Concepts in Java: A Comprehensive Guide
PDF
0% (1)
OOP Concepts in Java: A Comprehensive Guide
96 pages
T.Y.B.B.A. (C.A.) Lab Workbook
PDF
100% (1)
T.Y.B.B.A. (C.A.) Lab Workbook
257 pages
Recent Trends in IT
PDF
No ratings yet
Recent Trends in IT
135 pages
N3886 Android Programming BCA Science Sem 6
PDF
100% (2)
N3886 Android Programming BCA Science Sem 6
11 pages
Python Programming for Diploma Students
PDF
No ratings yet
Python Programming for Diploma Students
189 pages
Advanced Java for T.Y.B.B.A. Students
PDF
No ratings yet
Advanced Java for T.Y.B.B.A. Students
273 pages
Types of Operating Systems Explained
PDF
No ratings yet
Types of Operating Systems Explained
31 pages
Recent Trends in IT for BBA Students
PDF
No ratings yet
Recent Trends in IT for BBA Students
137 pages
Sem 6 BBA(CA) Practical Exam Guide
PDF
100% (3)
Sem 6 BBA(CA) Practical Exam Guide
30 pages
Compiler Construction Textbook Overview
PDF
100% (1)
Compiler Construction Textbook Overview
305 pages
Introduction to Cyber Crime and Security
PDF
No ratings yet
Introduction to Cyber Crime and Security
99 pages
Java Programming Assignments Overview
PDF
No ratings yet
Java Programming Assignments Overview
251 pages
Networking for BBA Students
PDF
100% (2)
Networking for BBA Students
285 pages
DST Nirali Publication
PDF
0% (1)
DST Nirali Publication
85 pages
Software Testing for BBA Students
PDF
100% (1)
Software Testing for BBA Students
16 pages
Introduction to HTML, HTTP, and PHP
PDF
No ratings yet
Introduction to HTML, HTTP, and PHP
90 pages
TYBBA(CA) Sem 5 Practical Exam Guide
PDF
No ratings yet
TYBBA(CA) Sem 5 Practical Exam Guide
30 pages
Operating Systems I: T.Y.B.Sc. Guide
PDF
100% (1)
Operating Systems I: T.Y.B.Sc. Guide
259 pages
Introduction to Web Technologies
PDF
No ratings yet
Introduction to Web Technologies
115 pages
Ajp Book Tech
PDF
No ratings yet
Ajp Book Tech
320 pages
OOSE PYQs
PDF
No ratings yet
OOSE PYQs
6 pages
MSBTE Java Programming Notes
PDF
100% (1)
MSBTE Java Programming Notes
166 pages
Introduction to Java OOP Concepts
PDF
No ratings yet
Introduction to Java OOP Concepts
34 pages
Dot Net
PDF
No ratings yet
Dot Net
303 pages
Visibility Modes in OOSE Explained
PDF
100% (1)
Visibility Modes in OOSE Explained
26 pages
Java Programs for Applets and Sockets
PDF
No ratings yet
Java Programs for Applets and Sockets
49 pages
OOSE Concepts and Principles Explained
PDF
No ratings yet
OOSE Concepts and Principles Explained
49 pages
TYBSc Computer Science Books by Nirali
PDF
No ratings yet
TYBSc Computer Science Books by Nirali
4 pages
CS 369 Java II Practical Workbook
PDF
No ratings yet
CS 369 Java II Practical Workbook
82 pages
Wireless Communication & IoT Overview
PDF
No ratings yet
Wireless Communication & IoT Overview
139 pages
VB.Net and C#.Net Program Examples
PDF
No ratings yet
VB.Net and C#.Net Program Examples
37 pages
Software Testing Tool
PDF
100% (2)
Software Testing Tool
129 pages
Cyber Security Exam Paper - Sem 5
PDF
No ratings yet
Cyber Security Exam Paper - Sem 5
10 pages
Cyber Security Textbook for BBA CA
PDF
No ratings yet
Cyber Security Textbook for BBA CA
110 pages
Introduction to Software Testing
PDF
No ratings yet
Introduction to Software Testing
62 pages
S.Y.B.Sc. Computer Science Syllabus 2020-21
PDF
No ratings yet
S.Y.B.Sc. Computer Science Syllabus 2020-21
46 pages
SYBSC (CS) 3rd Semester
PDF
No ratings yet
SYBSC (CS) 3rd Semester
12 pages
Operating System (Nirali Publication)
PDF
71% (7)
Operating System (Nirali Publication)
90 pages
Java Solved Question Paper 2nd
PDF
50% (2)
Java Solved Question Paper 2nd
14 pages
DST Nirali Publication
PDF
100% (1)
DST Nirali Publication
85 pages
SKMBT C22021032313190
PDF
100% (4)
SKMBT C22021032313190
236 pages
Fundamentals of Data Structures: Technical
PDF
100% (1)
Fundamentals of Data Structures: Technical
404 pages
Wireless Communication and IoT
PDF
50% (4)
Wireless Communication and IoT
99 pages
Groups and Coding Theory Overview
PDF
100% (1)
Groups and Coding Theory Overview
201 pages
Nirali Soft Engg &tool
PDF
100% (1)
Nirali Soft Engg &tool
86 pages
CS8392 - Oops Ebook
PDF
No ratings yet
CS8392 - Oops Ebook
476 pages
Important Questions for CN-II SPPU
PDF
No ratings yet
Important Questions for CN-II SPPU
13 pages
OOP TechKnowledge
PDF
100% (1)
OOP TechKnowledge
186 pages
Java Practical Slip Solutions
PDF
100% (1)
Java Practical Slip Solutions
42 pages
Core Java
PDF
No ratings yet
Core Java
290 pages
Simple Techniques to Learn Java
PDF
No ratings yet
Simple Techniques to Learn Java
148 pages
Akinola Java Book
PDF
100% (1)
Akinola Java Book
345 pages