0% found this document useful (0 votes)
343 views324 pages

Hari Krishna Volume 1a PDF

Uploaded by

Vinay Vinay
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
0% found this document useful (0 votes)
343 views324 pages

Hari Krishna Volume 1a PDF

Uploaded by

Vinay Vinay
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
You are on page 1/ 324
CoreJava with SOSP anc JVM Architecture Volume-1A Sls NC NARESH: Opp. Satyam Theatre, technolog Ss Ameerpet, Hyderabad - 500 016, E-mail:info@nareshit.com www.nareshit.com Ph: 23TACERS 23734842 Cell: 9000994007, 9000994008 n ISO 9001 : 2008 Certified Company — CoreJava with SCJP and JVM Architecture By Mr. Hari Krishna Shei Cgjanan Chapter 1 Introduction to Java In this chapter, You will learn \ Work doing in Software Industry & Software Engineer Skills \ Why Java is introduced? Java features Complete Java concepts Java learning road map Types of applications Types of internet applications Gmail Project Architecture How Java achieved platform independency? Java Versions and Editions o Java software installation and setting environment variables o Basic Java programming elerhents © Essential Statements of Java program © Java program compilation and execution procedure © Common Interview questions on Java programming © Difference between print and println methods o SUN Microsystems’s Promise o Coding standards and naming conventions o Java platform Architecture By the end of this chapter- you will understand complete Java architecture, Java projects design and development architectures and also aware of basic rules in developing, compiling and executing Java programs with Compiler and JVM activities. Interview Que: By the end of this chapter you answer all below interview questions On Software Industry * What are you doing th Software Industry? +" Whats the difference between project and product? «Types of companies bases.on projects and products * When do we call a project is maintenance project?, * Types of teams in software companies = What are the words used in project development and maintenance. + Types of logics developed in projects? » Software Engineer Skills * Give project architecture to show each technology role in project development, + Interview process and types of questions asked in interview * Importance of doing Java certification SCIP/OCIP and learning JVM architecture * Complete Java as per SUN and as per Software industry + Java Concepts and technologies to develop projects * Java and its technologies Learning Roadmap # A short story on Android, Java SE Tree diagram. On Java Language, Java software and Java Programming = WhyJAVA language is developed? * Definition of Java, and who invented Java? "Java features «Java history = Introduction to OAK and why OAK renamed to JAVA, "| What is the abbreviation of lava? * Common terminology used in programming languages = What is a platform, PD and PID? » What isa stand-alone and internet application? «Types of Internet applications "What are the technologies invented by SUN to develop internet applic: * Gmail server architecture to understand types of internet applications * Common logics developed in projects for automatic business = What is a design pattern? Different types of design patterns used in project design and develop for automating business. " M-V-C’Architectures and their advantages = Why MVC architecture name is MVC, why not CVM or CM? "Importance of Corelava & Where Corelava concepts used in above architectures "What is the main feature of a programming language to develop internet application? * Why C, C++ do not support platform independency? How Java achieved Platform independency? ns? CoreJava Yaa) SCJ im and sera NST aa eS oe com www. :23746666, 23734842 Cell: 9 9940 07, soooee4008 om, ISO 9001 : 2008 Certified Compa CoreJava with SCJP and JVM Architecture By Mr. Hari Krishna Index Volume -1: Java Language and OOPS Ahapter #01: Introduction to Java & OOPS Lhapter #02: Comments, Identifiers, Keywords Lhapter #03: Working with EditPlus Software Chapter #04: DataTypes & Literals Chapter #05: Chapter #06: Chapter #07: Chapter #08: Bhapter #09: Ahapter #10: Ahapter #11 shapter #12 “chapter #13: Wrapper Classes with Autoboxing & unboxing Exception Handling Packages e Accessibility Modifiers Methods and Types of methods Variables and Types of Variables JVM Architecture » Static Members & their control flow Non-Static Members & their control flow Chapter #14: Final Variables and their rules Phapter #15: Classes and Types of classes Chapter #16: Inner classes Chapter #17 Design Patterns Chapter #18: OOPS Fundamentals and Principles Chapter #19: Types of objects & Garbage Collection Chapter #20: Arrays and Var-arg types Chapter #21 Working with jar Chapter #22: Operators Chapter #23 Control Statements Volume -2: Java API and Project Chapter #24: Chapter #25 Chapter #26: Chapter #27 Chapter #28: Chapter #29 Chapter #30: Chapter #31 Chapter #32 Chapter #33 Chapter #34 Chapter #35 : API & API Documentation : Fundamental Classes ~ Object, Class >: Multithreading with JVM Architecture : String Handling 10 Streams (File 10) }: Networking (Socket Programming) Collections and Generics Regular Expressions Reflection API : Annotations |: AWT, Swings, Applet : Formatting text and date (java.text package) Chapter 1 Introduction to Java > In this chapter, You will learn Work doing in Software Industry & Software Engineer Skills \ Why Java is introduced? Java features Complete Java concepts Java learning road map Types of applications Types of internet applications Gmail Project Architecture How Java achieved platform independency? Java Versions and Editions Java software installation and setting environment variables Basic Java programming elements Essential Statements of Java program Java program compilation and execution procedure Common Interview questions on Java programming Difference between print and printIn methods SUN Microsystems’s Promise Coding standards and naming conventions Java platform Architecture Zo ° ° ° ° ° ° ° ° ° ° ° ° ° ° ° ° ° ° > By the end of this chapter- you will understand complete Java architecture, Java projects design and development architectures and _ also aware of basic rules in developing, compiling and executing Java programs with Compiler and IVM activities, By the end of this chapter you answer all below interview questions On Software Industry (On Java Language, Java software and Java Programming Interview Questions ‘What are you doing in Software Industry? What is the difference between project and product? Types of companies bases an projects and products When do we call a project is maintenance project? Types of teams in software companies ‘What are the words used in project development and maintenance. Types of logics developed in projects? Software Engineer Skits Give project architecture to show each technology role in project development Interview process and types of questions asked in interview Importance of doing Java certification SCIP/OCIP and learning JVM architecture Complete Java as per SUN and as per Software industry Java Concepts and technotogies to develop projects Java and its technologies Learning Roadmap A short story on Android, Java SE Tree diagram. Why JAVA language is developed? Definition of lava, and who invented Java? Java features Java history Introduction to OAK and why OAK renamed to JAVA. What is the abbreviation of Java? Common terminology used in programming languages What is a platform, PD and PID? What isa stand-alone and internet application? Types of Internet applications What are the technofogies invented by SUN to develop internet applications? Gmail server architecture to understand types of internet applications Common logics developed in projects for automatic business What is a design pattern? Different types of design patterns used in project design and develop for automating business, M-V-C Architectures and their advantages Why MVC architecture name is MVC, why not CVM or VCM? Importance of Corelava & Where CoreJava concepts used in above architectures What is the main feature of a programming language to develop internet application? Why C, C+ do not support platform independency? How Java achieved Platform independency? Java's Slogan Types of Java Softwares What is the difference between JDK, JRE and JVM? Different environments existed in real time projects development What is Java Plug-in? JAVA Versions and Editions i Java Software (IDK and JRE) installation and its folder Hierarchy Which edition features are installed if we install JDK/JRE? Definition of JDK and JRE or What is JDK and JRE? What is environment variable? Understanding the need of environment variables Setting Java environment using JAVA_HOME, Path and Classpath environment variables Types of applications developed using JAVA SE and EE. How can we connect Java and .Net applications in a single project? Basic JAVA programming elements for developing above projects architectures What is the difference between class and interface? Why enum? Essential statements of a Java Application Simple java program development, Compilation and execution. ‘When Java source file name and class name must be same: Java Programming interview questions ‘Why JVM executes only main method why not user defined methods? Can we define main method in all classes of a single Java file? Can we call main method, if so what is the syntax to call main method? ‘What does happen if we pass -ve number in main method call? Difference between print and println methods. ‘SUN Microsystems's Promise Coding standards and naming conventions Java platform architecture What Can Java Technology Do? How Will Java Technology Change My Life? Why pointers are eliminated from Java? What is JIT compiler? Differences between C++ and Java ‘Leam Java with Compiler and JVM Architectures Introduction to Java Introduction to java Talk about Java technology seems to be everywhere, but what exactly is it? The following sections explain how Java technology is both a programming language and a platform, and provide an overview of what this technology can do for you. Why Java? Java programming language mainly designed to develop internet applications by providing platform independency. C, C++ programming languages supports developing only stand-alone application, it can only be executed in current system, cannot be executed from remote system via network call Definition of Java Java is a very simple, high-level, secured, multithreaded, platform independent, object- oriented programming language: It was developed by James Gosling in SUN Microsystems in 1990's for developing internet applications, Its first version is released in January 23, 1996. It is descendent of C, C++ programming languages. Its syntax is similar to C and C++, but it omits many of the features that make C and C++ complex, confusing and unsafe. So, in Java we cannot see the most horrible topics such as pointers, structure, union, operator overloading, multiple inheritance and many more. Java Features To support internet application development Java programming has below features The Java programming language can be characterized by all of the following buzzwords: Simple > Object oriented Secure > Multithreaded Robust High performance Portable > Distributed Architecture neutral Dynamic Java Definition based on its features Javais just a simple, secure, robust, portable, object-oriented, interpreted, byte coded, architectural-neutral (platform Independent), garbage collected, multithreaded programming language with strongly typed exception handling mechanisms for writing distributed, dynafnically extensible programs What is the abbreviation of Java? There is no abbreviation for Java. The Development Team of Java has just chosen this name. The name Java specifically doesn't have any meaning rather it refers to the hot, aromatic drink COFFEE. This is the reaseg Java programming language icon is coffee cup. —— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 1 Leam Java with Compiler and JVM Architectures | introduction to tava Le: Who developed Java? Pla James Gosling, PhD (born May 19, 1955 near Calgary, Alberta, Canada) along with other itl engineer scientists discovered Java at SUN Microsystems. He is.a famous software developer, apy best known as the father of the Java programming language. tox pla Terminology used in programming languages all > Source code giv Developer written program; it is written according to the programming fanguage i syntax, Jav > Compiled code Compiler generated program that is converted from source code © Compiler i> Itisa translation program that converts source code into machine language at once . - © Interpreter j * tis also.a translation program that converts source code into machine language but toy line by line. 1 > + Executable code 0S understandable readily executable program(.exe files) > > Compilation Itis a process of translating source code into compiled code. > > Execution - itis a process of running compiled code to get output. > Java technology > Unlike other high level programming languages, Java technology is both platform and > programming language. Platform is a hardware or software environment in which programs : > are executed. Java has its own softwere based platform called JVM — Java Virtual Machine - to execute Java programs. Like C or C++ programs, Java programs are not directly executed by OS. » What isa platform? Wh ‘A platform is a hardware or software environment in which a program runs. The ‘or instance, computer platform is (Operating System + Hardware Devices) son What is meant by platform dependent and platform independent application? Tye Platform Dependent : Bas An application that is compiled in one operating system, ift is not run in different operating system then that application is called platform dependent application. The programming language that is used to develop this application is called platform dependent programming language. C, C++ programming languages are platform dependent programming languages, because these languages program compiled code does not run in different OS. Detailed explanation on this point is given next pages Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000894007 | Page 2 Learn Java with Compiler and JVM Architectures Platform independent 1f the application's compiled code is able to run in different operating system then that application is called platform independent application. The programming language that is used to develop this application is called platform independent programming language. Javais, platform independent programming language, because Java program compiled code can run in all Operating Systems. Detailed explanation on how Java achieved platform independency is given in next pages. Java History > The Java platform was initially developed to address the problems of building software for networked consumer electronic devices. it was designed to support multiple host architectures and to allow secute delivery of software components To meet these requirements, compiled code had to survive transport across networks, ‘operate on any client OS, and assure the client that it was safe to run. > Before Java Language, the software for these consumer electronic devices such as washing machines, microwave ovens and micro controllers was developed by C, C+ These languages are platform dependent > Sowe require a platform independent language that could be used to create software to be embedded in various consumer electronic devices. > Inanattempt to find such a solution, in SUN Microsystems a team headed with a scientist James Gosling began work on gortable, platform independent language that could be used to produce code that would support any technology at any time. v wv > Initially they named that language as OAK, it’s a tree name. > twas all happened in the middle of 1991 and the late 1992 } Inthe mean time of enhancing this OAK language to make more efficient language > The World Wide Web was emerging into the market. > In www so many verities of CPUs under different environments will be connected > Sohere also we require a portable and platform independent language & The only solution for this problem is OAK. > So this OAK language was modified or enhanced to fulfill the requirements of internet programming and wes renamed to "JAVA" > It was happened in 1995. Why the name OAK renamed to Java? They were unable to register this programming language with name-OAK, because already some other product is registered with the same name. So they renamed to Java Types of applications Based the way of execution of programs, all available applications are divided into 2 types 1. Stand-alone applications An application that can only be executed in focal system with jocal calls called, stand-alone application 2. Internet applications An application that can be executed in local system with focal call and also from remote computer via network call (request) is called internet application rt Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007| Page 3 | introduction to tava rr ———$—$— — Learn Java with Compiler and JVM Architectures | introduction to Java Lea Below diagram shows Stand-alone and internet applications wh Remote System Server Sytem semorkeaty| Stand-alone| ; [Pee |e oeaton i init bl | tev enc ‘Remote System Server System : i cor Program Types of internet applications ~~ let ‘We have two types of internet applications 1.Web Supportive Application _- executed in client computer Gm 2, Web Application - executed in server computer let Web Supportive Application ‘An application that resides in server system and that is downloaded and executed in client computer via network call is called web supportive application. i } i i Below diagram shows its execution control flow sien Serge } rent i Web Supportive i 1} ® | . cred | g | Web Application ‘An application that resides in server system and that is executed directly in server system via network call and sending response (output) back to client is called web application Below diagram shows web application execution control flow (Cea Syste Server Sytem Trower OAs | wer Progra] SG spptcation erected ‘ Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746¢66, 9000994007 | Page 4 Leam Java with Compiler and JVM Architectures ‘What are the technologies invented by SUN to develop above two types of applications? Applets - to develop web supportive applications Servlet and1sP__- to develop web applications Initially HTMLis invented to support developing web supportive applications. We can say in Java, Applet is the replacement of HTML. So using Applet we develop GU! to take input from end user and to generate Reports to show output to end user. Condusion: > Applet is executed in client system browser > Servlet is executed in server system. Let us understand above application with real time project Gmail. Gmail server architecture to understand above two applications Let us try to understand the operations you are doing to check your malls in gmail account 1. First you will open browser, then you enter gmail server address “gmail.com” in the address bar. 2, Soon you press “Enter” key on keyboard; you will observe gmail login page is appeared. Is that logic page HTML code available in your computer? Or is it downloaded from gmail server? It is downloaded from gmail server then your browser renders that html code and displays it to you. Now tell me HTML technology develops what type of application? Web supportive Application. 3. Now, as per next step you will enter your gmail account username and password, and yyou will click Signin button. if the given username and password is correct you will get your inbox mails, else you will get an error page saying that @sername or password is incorrect 4, Think what happened in background? Browser sends the given username and password to gmail server. Gmail server reads these values and passes those values to an application running at server side. Itis nothing but Servlet, means Web Application 5. Then servlet passes those values to Database Interaction Application, JOBC program. 6. Now, JOBC Program executes SELECT query on DB LOGIN table to check whether user exists with given values or not. if user exists DB returns userid. The query would be SELECT userid FROM login WHERE uname=givenUsername AND pwd=givenPassowrd; 7. Using this returned userid, DBC Program executes another SELECT query on INBOX: table to get all mails related to this user. DB sends all mails related to this user to JDBC application. The query would be SELECT mails FROM inbox WHERE userid=retumedUserid; 8. Then JDBC application sends those mails to Servlet. 9. Now the Servlet sends those mails to JSP to format the mails with help of HTML hyperlinks. 10. Using these mails, JSP generates HTML code dynamically and sends that HTML code to Servlet. 11. Servlet sends those mails which are formatted in HTML code to the browser 12. Finally, the browser displays those mails to user. EEE — ee 1s, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007| Page S Introduction to Java Leam Java with Compiler and JVM Architectures Below diagram shows all above 12 steps execution 6 D mien cctsioaian ° ! Sioa | am \ | [Les] |< fe maT j t x 1 t J | LTT 4 {Softy f | sabicn 2 Asal sentation | a | appli Conclusions from the above diagram 1, Every real world web project contains below three applications 1. Web supportive application 2. Web application 3. Database interaction application ey AHUReNR 2, In Java we develop above applications by using + HTML/Applet- to develop web supportive application, * Servlet and JSP- to develop web application. Java * JDBC and EJB to develop Database Interaction Application. SUN dom 3. In NET we develop above applications by using = HTML - to develop web supportive ae © ASP.NET -to web applications : * ADO.NET — - to develop Database Interaction Application. : 4, Web supportive application (HTML/Applet) is used * for collecting input from end-user by providing GUI then to pass it to web application Java * for displaying output to end-user by providing Report Java . Java 5. Web application (Servlet and JSP technologies) is used for 1. Processing request and ? We: 2. Preparing response. "Servlet role is processing request means Com > Reading input from network that is sent by end-user via HTML forms, then Asa > Executing Business Logic by using this input then ie. > Finally generating output and sending it to JSP "JSP role is preparing response means a. Generating dynamic HTML by using the output given by Servlet, SUN b. Sending the result HTML back to Servlet "Then serviet sends this response to browser to display this output to end-user. ‘ ee =_ Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666,9000994007! Page 6 ee Java with Compiler and JVM Architectures introduction to Java 6. Database Interaction Application (JOBC/EJB technologies) is used for performing CRUD operations on DB. C-Create R-Read U- Update D- Delete Software Engineer Skills: ‘Asa being a software engineer you must work in developing all above three types of applications. So you must acquire all below skills 1. Programming Language 2, GUI Preparation Language 3, Scripting Language 4, Database 5. Server Operating System 6. Problem Solving Skills 7. Presentation Skills 8, Communication Skills Java concepts and technologies to develop all above three applications in projects SUN Microsystems divided Java concepts into three categories to support all three types of domains mobile, desktop and internet applications. In Java a category is called as Edition, So we can say Java concepts are divided in to 3 editions (Micro Edition) {Standard Edition } (Enterprise Edition ) 1. Java ME 2. Java SE 3. Java EE Complete Java: SUN Complete Java "Java SE "Java EE Java ME concepts are used for developing Mobile Applications Java SE concepts are used for developing Desktop and Window based applications Java EE concepts are used for developing Internet and Enterprise applications We are here to learn only Java SE and Java EE Asa Java learner we must know one important point i.e.; we have two divisions of Complete Java 1. Complete Java as per SUN 2. Complete Java as per Software industry 0B Terminology Insert Select Update Delete - Java / NET - HTML, C5S - Java Script, VB Script - Oracle, SQL Servier - Unix commands and Shell scripting - CRT and C with DS - MS Office - English : 040-23746666, 9000994007| Page 7 Learn Java with Compiler and JVM Architectures Leart Software Industry Complete Java Pr To learn Java quickly and easily we divide Java concepts into 4 divisions naa 1. Corelava ma 2. Advanced Java : i ofco 3. J2EE 4, Frameworks ae Frameworks are not part of Java SE or Java EE they are developed by third party companies by Java using Java EE technologies. Framework softwares are not developed by SUN/Ora¢le. | Java Framework softwares are reusable projects used for developing new projects saP/. area |, Naresh i Technologies Complete Java Corelava with SCIP and JVM Architecture | Software Industry Complete [ava Concepts Division or foe] 2. Advanced lava with SCWCD j eae 3. REE | 4. XML, Webservices 114 5. iS H || 6 Frameworks 1 | a. Struts fees | b. Spring with Hibernate || 7. HTML, CSS, Java Seript Java |] & Ses avery rs css z 9. Java Project Development Supporting tools Java SE and Java EE concepts 10. Academic and tive projects Java is both language and technology. fo a * Java SE has both "Java EE has only © Java language concepts and © Technologies o Technologies Java SE Language Concepts | 1. Datatypes, Operators, Control Statements 10. Networking (Socket Programming) | 2. OOPS 11. Collections Framework } | 3. JVM Architecture 12. Regular Expressions j 4. Garbage Collection 13. Reflection API 1 5._ String Handling 14, Annotations Corea) ji 6. Wrapper Classes 45. Inner Classes — 1 ee 7. Exception Handling 16. AWT, Swings, Applet 7 4 8. Multithreading 22. Working with Jar | Whe 9, 10Streams (File 10) 18. Date, time and text format 5 Platy i irces Java SE technologies Java EE technologies | Why Bece Why . EIB plat 4, WebServices byt ISF inde ‘Naresh i Technologies, Ameerpet, Hyderabad; Ph: 040-23746666, 9000994007 | retools Lear Java with Compiler and JVM Architectures Introduction to Java Ashort story on Android ; ‘Android is an open-source software stack for mobile devices which has Operating System, middleware and some key applications. "Android" invented by Open Handset Alliance (a group of companies), and is bought by Google in 2005 to develop their mobile “Arsenal” Android is developed by using Java SE concepts, not by using Java ME. Java SE Tree Diagram Java SE is the root of all software industry technologies including Testing tool (Selenium), SAP/ABAP, Oracle Application forms. You can easily work on any domain based projects if you are a lava developer as all technologies concepts are similar to Java, Heo eee Tnaoeies cance — a matt [va [onde Tie frou an v he Medco out a n> annoy cures totic CF CwthDS HM ack Cran ond Ada What is the main feature of a programming language to develop internet application? Platform independency because an internet application must run in all Operating Systems ircespective of where it is compiled. Why C, C++ programming languages cannot support internet application development? Because they are platform dependent. Why G G+ programming languages were developed as platform dependent, why not as platform independent? By the time C/ C++ programming languages were developed there was no internet. Platform independency feature is only required for developing internet applications. —————— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007| Page 9 Learn Java with Compiler and IVM Architectures | nvoduetion todos Lean Why C, CH program compiled code cannot execute in all operating systems? In these programming languages the compiled code is Machine Language which is understandable only by the current OS. Thus this compiled code cannot be executed in different Operating System. Due to this reason these languages ate considered as platform dependent programming languages. Below diagram shows platform dependency of Cand C++. Wha oe [abec} af Seni | ato] pat far LL afaienin} 96) mov 1 Linke J time seca co] } 4 bs | bee Wieden Abel} —bWiiows|_ | raver 1X0 i ¥ Compe aa Tinker |p —>BBsese PO) * um in| > [abe cum os, Hsien} boom) i | sine Concludes code 1, C, C++ compiler is OS dependent: As you noticed, in the above diagram compiler Mac generates OS specific Machine Language. inth j hurr 2. G Cr softwares are also platform dependent: because compiler is a part of C, C++ | com software. Hence C, C++ vendors develop compiler specific to OS, and maintains C, C++ | softwares separately one per every OS. i boii nde 3. So to develop C, C++ programs, we must install C or C++ softwares specific to OS. } pt Isit true that C, C++ cannot support internet application? i Partially YES, they can support internet application development. If client OS is same as Server i 0S then the C program is downloaded and executed, else it cannot be executed. i But still C, C++ programming languages are.not a good choice for developing internet j applications, because we cannot always guarantee that the client OS is the same as server 0S, | Ho also we cannot force the client to have OS same as the server OS. If we force we will lose Jave business. Below diagram shows, C, C++ can support internet applications development com partially, lang > und ; i a Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 10 Leam Java with Compiler and JVM Architectures { Introduction to Java (weebia) In above diagram, ¢ program does not run in windows because it was compiled for Linux. ‘What is the solution fer achieving platform independency? Very simple, generate ML for client OS. So to generate ML for client OS, ML generation must be moved from compilation phase to execution phase, because client OS is known only at the time of execution. Since we moved ML generation from compilation phase to execution phase, what type of code should compiler generate, and after downloading how that code can be translated to ‘Machine language of that client current OS? In this approach compiler should generate some code that should not be understandable by thuman being let us say “encrypted code” and should have another translator software to convert this encrypted code into machine language of the current client OS. Server system en sytem clentSystem Tar ipo f—~ Bytecodes is an intermediate format that can only be understandable by VM > JVM -lava Virtual Machine is a software that executes Java bytecodes by converting bytecodes into machine language of the current operating system's understandable format. How did Java Achieve Platform independency to support internet application development? Java achieved platform independency by moving Machine language generation from compilation phase to execution phase by introducing bytecodes and JVM ~ bytecode is a native language of JVM and JVM is translated software that converts bytecodes into current client OS understandable machine language for executing java bytecodes. ———————— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 11 Learn Java with Compiler and JVM Architectures Linteost ‘What are the Java file’s extensions? in java we have only two extension files > “ava” extension file it called source code which is developed by developer > “class” extension file it is called compiled code contains bytecode which is generated by compiler from source code. Like in Cor C+, in Java we do not have executable file means " exe” extension files. More over In Java, the compiled code is not machine language; instead it is an intermediate code, named as “bytecodes" stored in a new file with an extension ".class”. This code is generated by lava compiler and is only understandable by JVM. | | Java program development, compilation and execution procedure } In the Java programming fanguage, all source code is first written in plain text files ending with j the “,java'" extension. Those source files are then compiled into “.class” files by the javac } compiler. A ".class” file does not contain code that is native to your processor; it instead | contains bytecodes — the native language of the Java Virtua! Machine, The java launcher tool then runs your application with an instance of the Java Virtual Machine. | 3 | Below diagram shows Java program compilation and execution (copied from Oracle tutorial) sh f= = co 9100102, } = US + con MyProgran. java MyProgram. class | 1 Java program execution process as internet application | : User downloads *.class” file from server system and executes with the JVM installed in that, fog client computer as shown the below diagram. a fo (un) 1 enesytem eg System i. ios EE exer | | (sh) Laowicadaa seca i € | Now Java, is pl Java Because the Java VM is available on many different operating systems, the same .class files are bott capable of running on Microsoft Windows, Linux, Solaris, or Mac OS. Whe Java's Slogan “Write Once, Run Anywhere (WORA)" JVM Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 12 Leam Java with Compiler and JVM Architectures Below diagram shows Java's Platform independency block diagram, it also shows implementing above slogan ava TY sous (ects [windows aM — fo [ Soteris | Led VM generates Windows ML OS produces. | L__ op ‘1M generates | Linux jl [obprodia Lor [2m generates Solaris ML ee [Be Conclusions 1. Compiler is responsible to convert lava source code into bytecode and storing these bytecodes in a separate file with extension ".class"” JVM is responsible to execute these bytecodes. JVM executes those bytecodas by converting them into the ML of current OS. \n lava we do not have a file with machine language; also in Java we do not have executable files (.exe files). We have only 2 files java and .class Java class bytecodes run in all OS, icrespective of the OS in which the Java program is compiled. Because the Java VM is available on many different operating systems Java compiler is OS independent, because it takes Java source code and generates Java bytecode, both input and output files are Java related files. JVM is OS dependent, because it takes Java bytecodes and generates OS dependent ML. So Java software is platform dependent, Since JVM platform dependent we must have different Java software for every OS separately. Hence Java software is OS dependent. Now answer my question, is Java Platform Dependent or Independent? Java program is platform independent but Java software is plattorm dependent, because JVM is platform dependent and is available for every OS separately. Java software becomes platform dependent and Java program becomes platform independent both because of SVM implementation. Who develop JVM, OS vendor or SUN? JVM is developed by SUN separately for every 0S, not by 0S vendar. — Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 13 JDK and JRE are called principie products of | Java software: Difference between JDK, JRE and JVM VM isa subset of JRE, and JRE is the subset of JDK. When we install JDK, JRE is also installed automatically. JRE software is available as a separate pack, so we can install JRE alone. > JDK has both compiler and JVM, So using JDK we can develop, compile and execute new java applications and also we can modify, compile and execute already developed applications. > IRE has only JVM. Hence using JRE we can only execute already developed applications. Diagram JRE Compiler + Cont) Naresh i Technologies, Ameerpet, Hyderabad, Ph: 640-23746666, 9000994007 | Page 14 Learn Java with Compiler and JVM Architectures Introduction to lava Learn 1s JVM available for all Operating Systems? Differ Yes, JVM is available for every OS separately. | 1 Is JVM installed automatically with OS? 2 No, itis not installed with OS. We must install it in our computer explicitly | What are the Developer and client responsibilities? 3 * Developer is responsible of developing, compiling and executing the Java application, so in developer system we must install both Compiler & JVM. Java\ * Whereas client is responsible of only executing that Java application, hence in client faa somputer just installing VM is sufficient. ee computer just installing cies | aver Based on the above points we can say that Java software is divided into 2 parts as below i devel 1 Alsoi Types of Java Softwares the ci lava Software is divided into two types ; 1, JDK —Java Development Kit oe 2, JRE — Java Runtime Environment 7 pel 4 ' Learn Jave with Compiler and SVM Architectures Introduction to Java Different environments existed in real time projects development 1. Development environment ~ Here developers will work to develop new programs (class). Hence we should install JOK in development environment. 2. Testing environment ~ Here testes will work to test the project, means they just execute the project. Hence JRE installation is enough. 3. Production environment ~ Here end-users will work to use the project, means they just execute the project to complete their transactions. Hence JRE installation is enough. Java Versions and Editions Java Versions Aversion is a number that is used to identify the current features and enhancements developed in that software's current release. Every software is developed with versions. ‘Also in software companies all projects and products are developed with versions. n most of the cases the version number is starts with "1.0" > Aproject is software that is developed specific to one customer. > Aproduct is also a software but is developed common for all companies, we can say it is a readymade software. Below are the sample products with their version numbers. Java Software Windows Software Oracle software Java 1.0 Windows 98 Oracle 81 Java 1.1 Windows 2000 Oracle 91 Java 2 platform Windows 2003 Oracle i0g [>12 Windas xP Oracle XE [>13 Windows Vista Oracle 11g lo. Windows 7 Java 5.0 Windows 8 Java 6.0 Java 7.0 Java 8.0 | Major and Minor versions Java has two types of versions 1, Major version ~ it is the main version of the software contains new features & enhancements of current release of that software 2. Minor version ~ it is the sub version of the major version contain bug fixes > Java software is released with major version, if there are any new features or enhancements are added. > Java software is released with minor version, if there are only bug fixes. > Java latest Major version is Java 7 (jdk 1.7) > Java latest Minor version is Java 7 is (jdk 1.7.0_06). a ‘echnologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 15° d Learn Java with Compiler and JVM Architectures Below diagram gives major and minor versions format idk 1.7.0 } — jdk 1.7.9_01 idk 1.7.0_02 idk 1.7.0_03 jk 1.7.0_04 jdk 1.7.0_05 idk 1.7.0_06 _ Q) Can we execute Java program using lower version JVM than compiler version? ‘A) We cannot use lower version JVM, it leads to error Unsupported Major_Minor exception. major version +—— minor versions Rule: JRE version must always -ompiler version, Java E Edition is a category. All Java features are categorized into three editions They are 1. Java 2 platform Micro Edition -J2ME 2. Java 2 platform Standard Edition - J2SE 3. Java 2 platform Enterprise Edition - J2EE jons Q) What is the significance of the number 2 in above names? Nothing, it just represents editions were introduced in Java 2 version. Q) Why Java concepts are divided into editions? In Java 2 Version SUN introduced new features and concepts to support web and enterprise applications. So SUN thougnt that it is better to divide Java concepts into three categories for easy maintenance and for easy distribution. ‘Q) What features or concepts we have in above three editions? ® J2WME has concepts to develop software for consumer electronic devices means embedded systems, like mobile. It is popular for developing Mobile gamming applications. > J2SE has concepts to develop software for Desktop based applications, nothing but the applications previously developed using C, C+. > J2EE has concepts to develop software for Web and Enterprise applications. These applications are also called as high scale applications they are like banking and insurance based applications In Java 5, edition names are changed. SUN removed 2 fram edition names, because itis not relevant to current version number Java 5. Below are the new names for all three editions: 1. Java platform Micro Edition Java ME 2. Java platform Standard Edition —- Java SE 3. Java platform Enterprise Edition - Java EE Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9900994007 | Page 16 Java Not: Java Folk Step Java The | Belo Nar Learn Java with Compiter and JVM Architectures Below diagram shows all java versions, code name, released date and editions. Java Name iple Products | Code Name | Released Date Editions Java 1.0 jdk 1.0, jre 1.0 ‘Oak January 23,1996 | Noeditions Java 11 jdk 1.4, jre 1.1 Oak [February 19,1997 | No Editions | Tava 2 platform 1.2 | j2sdk 12, j2sre1.2 | Playground | December 8, 1998 | J2ME ‘J2SE - - _ sage [ava 2 platform 1.3 | jsdk 13, j2sre 1.3 | Kestrel May 8, 2000 PME J2SE Java 2 platform 1.4 | j2sdk 1.4, j2sre 1.4 | Merlin. February 6, 2002 [Jdk 15, jre1.5 Tiger ‘September 30, 2004 Idk 16, jrel 6 Mustang | December 13, 2006 [idk 17, jre1.7 Dolphin July 28, 2011 Note: Code name is the Java software internal project name used in SUN Microsystems. Java Software (JDK) installation and its folder Hierarchy Follow below steps to install tava software - JDK Step #1: Download latest version Java software from oracle.com Java is an open source software available for free download at Oracle home site (oracle.com). The path for downloading Oracle.com -> Downlodids -> Popular Downloads -> Java for Developers Below window is opened = saan mms ~ Learn Java with Compiler and JVM Architectures Below window is opened Fan. CREPE | + cept canes Agrsmest —Decine Lice Arooent { Freda Fie Beiciaton | Fae Site] Taner eee Lrocst Gross uae 08 Click windows Java software exe file link to download Java software for Windows 3 Soansés 7580 88 For windows 64 bit processor Follow below procedure to install Java > Double click on exe file, it shows below welcome page. Click Next _ ==) For windows 32 bit processor | After downloading Java software ' > In the next window it shows jdk installation folder path as shown below "C:\Program Files\ava\jdk2.7.0_09°, click on Change button -> change above path to "Cjdket.7.0_09" => click Ok-> click Next | Sea See. | | The space in the folder "Program Files" cause problems while compiling and executing java program from Editplus software. a Learn Java with Compiler and JVM Architectures Introduction to fava > Click Next, OK installation is started, and shows below window > After JOK installation, it shows below window to install public JRE. Click Next a [Gown se) Lees No need io change folder path for Cormega bas. Public JRE installation. It is used for - 4 executing Applets by Browser, > ss bar as shown below - final window, click Finish. eae Click Close button to Tews 7 finish installation. ao = java \ Se , Java software installation is completed. It is installed at “C:\jdk1.7.0_09” This folder path is called “Java software installed directory” or “JAVA_HOME”” Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 19 Leam Java with Compiler and JVM Architectures | Introduction to Java ‘What is JAVA_HOME means? The Java software installed directory is called JAVA_HOME. We also follow this naming convention for other softwares. For instance Oracle installed directory is called ORACLE_HOME, Tomcat installed directory is called CATALINA HOME, etc.. Why this naming convention is followed? This naming conversion is followed in software industry for finding software installed folder path easily. Actually in companies, in server system softwares are installed by IT team and those are used by Development team. These naming conventions fill the gap between these two team members. How? After installing software, IT team stores that software home directory path using an environment variable as shown below, so that development team no need to contact every oo ‘time to know where the Java, Oracle and Tomcat softwares are installed. How Java > JAVA_HOME for Java software, two > ORACLE_HOME for Oracle Software, > CATALINA_HOME for Tomcat software. Whe | itis Then development team uses the same environment variable to find software installed path, wel Check “Environment variables” topic for more details. | dele i ; dire: Whe ; The {Toc 1 wor ; | com i only t jarexe is Sos og No, i Ware rncoleane Types of files available in software : Every Software has below two types of files i 1. Binary files - are command files by default stored in a folder called “bin” i 2. Library files - are program files by default stored in a folder called “lib” i > Binary files are command files, means they have commands to be executed in 1 sequence, Java binary files have commands to compile and execute Java program. Eo ttyc > Library files are program files, means they have logic that is used to develop another 4 inst applications. Java library files are used in developing new Java applications and'applets. fold Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 20 Java Leam Java with Compiler and JVM Architectures | introduction to Java Below diagram shows binary and library files extensions Windows library files binary files ——— “Java library files —— Linux / Solaris NET ary files library files Now let us understand how can we use Java software to develop new Java application? How can we compile and execute Java program and from where? Java programs are compiled and executed using Java binary files javac and java. We call these two binary files as “tools” in short form. These two tools are used from command prompt. ‘Where Java files must be stored, in Java software installed folder or in some other directory? Itis not recommended to store Java source files in Java software installed directory, because if ‘we uninstall current Java software for installing next version, all our Java source files are also deleted. So for security reasons it is always recommended to store Java source files in another directory not in Java software installed directory. The directory in which the Java source files are stored is called Present Working Directory. To compile and execute lava source files we must use javac and java tools from the present working directory at command prompt. So the first thing you should do after opening ‘command prompt is changing current directory path to Present Working Directory path, then only your Java source files are identified for compilation and execution by javac and java tools. Q) Is javac and java tools are available from outside Java software installed directory? No, these files are not available from other folders. To check this point follow below procedure > Open command prompt (click start-> run -> type cmd and then press Enter key) > By default the folder path shown is current logged in user home directory path, for instance say C:\users\HariKrishna. > Type javacand press Enter | cavsers\warincishna>javac CSE GR ea ts ae \users\Warixrishna> If You observe the above error it means javac tool is not available outside of Java software installed directory. To solve this problem and to access all Java tools throughout OS from all folders we must update environment variables a |—Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 21 Learn Java with Compiler and JVM Architectures introduction to leva, So, the point to be remembered is: Just by installing software its binary and library files are not available from other directories automatically. We must update environment variables with that software binary and library files path. Understanding environment variables The variables created in OS to store software's binary and library files are called environment variables. For Java and Java related softwares we should use below two environment variables to store the software binary and library files, they are 4. Path - Used by 0S to identify binary files 2, Classpath = Used by Compiler and JVM to identify Java library files Path is a mediator between developer and OS to inform softwares binary files path Classpath is a mediator between developer and (Compiler, JVM) to inform the library files path those are used in our source code. * Path environment variable is inbuilt available in Windows 0S. So we must just update it with our software Path value in windows. But in Linux and Solaris OS we must create. * JAVA_HOME and Classpath variables are not by default available they must be created by developer because they are related to only Java and Java related softwares. Two ways to update environment variables We have two ways to set environment variables 1. Temporary settings 2. Permanent settings ‘Temporary settings Updating environment variables from command prompt is called temporary settings; because those settings are only available for that command prompt till itis closed. Once we close it, all settings are gone. DOs commands to do temporary settings + "Ser" + ~for creating new environment variable + "%%" —_~ for retrieving existed value are ~ for separating path values + “echo” for retrieving and print. value Syntax to create/update environment varaibles SET =% Below is the Java Path and Classpath values Setting Java binary files path SET Path=C:\jdk1.7.0_09\bin;9%Path% Setting Java library files path SET Ciasspath=,;C:\jdk1.7.0_09\\ib\tools jar;C:\idk,7.0_09\jre\lib\rt jar;96Classpath% ——— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 22 Learn 4 | ; ; | Obser mand Work from excer Belov et “jan oper het c:\' Usat hei As yc execi The! prom comi Soir pron Pern Ifwe after The Nar Leam Java with Compiler and JVM Architectures introduction to Java Observe that at beginning of Classpath environment variable | have placed ".” operator. itis mandatory to place “.” operator in Classpath environment variable it represents Present Working Directory. if we do not place .” operator in Classpath JVM cannot execute classes from present working directory and it terminates java program execution by throwing exception “java.lang.NoClassDefFoundError” Below diagram shows updating Path and Classpath environment variables at command users\Harikrishna>javac Fjavac’ is not recognized as_an internal or external command, feberable program or batch file. c:\Users\Harikrishna> Some SAN lec\users\narixrishna>javac , jusage: javac where possible options include: “9 Generate al] debugging info =g:none Generate no_debugging info -g:{lines,vars,source} Generate only some debugging info Generate no warnings Output messages about what the compiler Output source locations where deprecate As you can observe, now javac is identifying from another folder. So, now you can compile and execute Java programs in this command prompt ‘The limitation in this approach the current settings are available only for this command prompt. These settings are not work for another command prompt. More over if we close this command grompt all settings are lost. Soin this approach we must set all these settings again and again for every new command prompt instance. To solve this problem we rust store these settings permanently. Permanent settings If we set above Java settings permanently they are available from all command prompts even after system restart. The procedure is 1. Right click on "My Computer" -> Click on "Properties", | Sa Below window is opened Naresh i Technologies, Ameerpet, Hyderabad, Ph: 04023746666, 9000994007 | Page 23 Lear Java with Compiler and VM Architectures Introduction to !ava# eann Je > Celaya wd Sey + pen i 5.1 nee ‘View basic information about your computer 3 Device Manager Windewt eftion } 3 teem am | oy System protector Copyright € 2009 Misocat Corpraion, Alsights reserved. q ooo 2. Click on "Advanced System Settings" hyper link, below window is opend 4 [Feewwtrstsoees, ivan aenizaowe sce ‘ } | oom 4 | a 4 3. Click on “Environment Variables" button, below window is opened 3 i q 1 | 4 | | « Now cre i 6.1 { 4 i Zo | Click New window I Then the below window is opened a i New User Variable i lod Uibdoeting ‘arise name: | eo. | | vette ; j i Enter below values as shown below Variable name: Path Variable value: C:\jdk1.7.0_09\bin nee eee Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 24 Narest ‘0 J0v2 4 eam Java with Compiler and JVM Architectures Introduction to lava 5, Finally click on Ok button. New User Variable | Veriable name: Path erable vee: CiidkL.7.0_09bin Now create Classpath variable 6. Click again New button and enter values as below Variable name: Classpath Variable value: .;C:\jdk1.7.0_09\jre\lib\rt.jar;C:\jdk1.7.0_09\lib\tools.jar 7. Click Ok button then Classpath variable is also added to list as shown Point to be remembered Classpath environment variable must has “" operator, else Java programs are not executed by JVM. Program execution is terminated with exception “java.lang.NoClassDetFoundError” Click Ok, and also click Ok on other CoWirdonsyclend2emd ene windows till all wintows are closed. We completed Java software installation and Environment variables setup Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 25 Learn Java with Compiler and JVM Architectures introduction to fava Now let us cross check Java path settings Open new command prompt -> type javac command -> press Enter key on keyboard, Toset" You should get the message shown below. eee {ese cnsensgpenszentine 7 Setting “9 Generate al] debugging info ~g:none Generate no. debugging info -9:{lines,vars,source} Generate only some debugging info -nowarn Generate no warnings Tempo! -verbose __ Output messages about what the com Atshell Sexpor Sexport Classpa g/jre/\i! Ifabove message does not appear, you have dane some wrong setting. ross check the Path value at command prompt using echo command as shown below c:\users\Harikrishnarecho pathy 2\windows\syetena2ic: windows; \windows\systena2\when:c: \windows\systen32\wind | owsPowershel\v1.0\;C:\Program’Files\Lemovo\Bluetooth Software\ ;C: \apache-toncat Permat =6.0.26\bin;C:\Progran Files\editPlus 2, aNCLSBEAOENL In Linu; [e:\users\Harikrishna> Cross check your Path value with one shown in the above screen. It must be placed as commented in the above diagram. Point to be remembered on Oracle path In Advanced Java course you will install Oracle software for developing JDBC applications. Oracle software Path is automatically updated in environment variables section. Make sure itis placed after Java software path value. Else you will experience an exception “java.lang. UnsupportedVersionError” for java programs execution, because oracle software also contains Java software which is lesser version than your using. Instailing Java software in Linux / Solaris 1. Download "bin' format jdk software from oracle.com that is given specific to Linux or Solaris Open shell prompt 3. Change current directory path to software copied folder path a. /home/users/HarikrisnaScd /home/softwares/java b. /home/softwares/javas Execute bin file a. /home/sotwares/java$ jdk1.7.0_09.bin <-| Java software is installed here in "java" folder So the JAVA_HOME will be "/home/softwares/java/jdk1.7.0_09" Lear Java with Compiler and IVM Architectures Introduction to Java setting environment variables To set "Path" and "Classpath" environment variables in Linux and Solaris we must use below commands ‘Window commands Linux / Solaris commands ‘SET export xePath% $path echo %Path% echo $Path Temporary settings ‘At sheli prompt run below commands Sexport Path=/home/sotwares/java/jdk1.7.0_09/bin:$Path Sexport Classpath=.;/home/softwares/java/jdk1.7.0_09/lib/tools jar:/home/sbftwares/java/jdk1.7.0_0 9fjre/lib/rtjar:$Classpath Permanent settings In Linux: © Open user home directory Find a file called ".bash_profile” Open it. (Right click on that file -> click "Edit"] Save above two export commands in this file Permanent settings are over. In Solaris: * Open user home directory «Finda file called "profile" # Open it. [Right click on that file -> click "Edit"] Save above two export commands in this file + | Permanent settings are over. Which edition concepts are installed from JDK or JRE software installations? Only Java SE concepts are installed, Also to install Java EE concepts, in addition to JDK we must also install server softwares like - Tomcat, Weblogic, Glassfish, etc. Java Reference Books Theory books iL. Core Java with OCJP and JVM Architecture By Hari Krishna 2. SCIP 1.6 By Kathy Sierra 3. Effective Java By Josh Bloch Inside JVM By Bill Venners ._ Java Cookbook Solutions and Examples for Java Dévelopers By ian Darwin Thinking in Java By Bruce Eckel Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 27 Learn Java with Compiler and JVM Architectures Introduction to Java Lear J Programming books Java Ba 1. Java Programming By Hari Krishna InJava 2. Written test questions in Java programming by Yashavant Kanetkar 3. Test Killer (SCIP Dump) 4, Develop al! C programs in Java Online reference 1. oracle.com 2. javastuff.in 3. javapapers.com 4, mindprod.com 5, javaspecialsts.eu 6. roseindia.net 7. javaranch.com 8. serverside.com 9. jguru.com 10. java-questions.com AA. stackoverflow.com, 12. tutorialspoint.com, 13. Mylavaltub.com, 14. javamex.com 15, Projecttopics.info Now we are ready to learn programming in Java. To develop Java program we must learn below important points. What are the different types of Applications we can develop by using Java SE and E£? Using Java SE and Java EE we can develop 8 types of applications, they are The point to be Q)wt ca noticed here is as fA) inte per SUN we do not} 3< cla: 7have Core Java and Standalone Application (Corelava) Websupportive Application (Applets) Database interaction Application (JDBC) és So, int Integrated Applicat (xan) our industry export for learning Java Distributed Application (roa) comfortably. create Fore Web Application (Serviets/ sSP5} In this diagram youg QW! \ SF can observe; the ff It war Enterprise Application (E18) applications list you items learn as part of CJ, Interoparable Application (Webservices) Adv Java and J2EE§) Befor courses. intro — Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 28 Nare Java Lean Java with Compiler and JVM Architectures Introduction to fava Java Basic Programming Elements In Java we have 6 basic programming elements to develap all above 8 types of applications. [aie] : ions 1. package: It is a Java folder used to group related classes, interfaces and enums also used to separate new classes from existed classes if both have same name. 2. class All these three are Java files used to group Java data and logic. 3. interface enum was introduced in Java 5 4. enum 5,, variable: It is anamed memory location used to store Java data, such as numbers, characters, strings etc 6 method: Its a sub block of a class used to implement logic of an object operations. Rule: logic should be placed only inside a method, cannot be placed at class level directly. be J a) Whatis the difference between class, interface and enum? iss 1 A) interface is a fully unimplemented class, itis used for defining set object operations, where to Noll as class isa fully implemented class, itis used for implementing an object operations wa a Ee xd i 52 interface does not allow methods with logic where as class allows methods with logic. expoi : ; Java For example: Bank is the object created as interface in Java and HDFCBank, ICICIBank are created as classes with bank operations withdraw, deposit implementations. aim yor Q Why enum? the J ' was introduced in lava 5 version to create set of named constants for creating menu kind of list yom items stich as Restaurant, Bar menu. of Cl ° : AJ2Bi§ Before Java 5 this menu is created by using class, ‘since it is creating some problems SUN Introduced enum with new syntaxes and rules. —— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 29 Learn Java with Compiler and JVM Architectures Q) What is the mandatory basic programming element? class is mandatory, because it allows us to define methods with logic. Q) Why does a Java program start with a class? . Because of below two reasons every Java program starts with a class 1. The real world object can be represented only using class. 2. We can define methods with logic only using class. Essential statements of Java program To develop, compile, execute and print output on monitor (console) every Java program must has below 3 statements 1. class block: because only class allows us to defirie method with logic. 2. main method: because it s initial point of class logic execution. 3. System.out.printin: because in Java all kinds of data is printed by using this statement. To print Hi using above statements the program would be look like: class FirstProgram. { public static void main(Stringf] args) { System.out-printin( Softwares required for developing Java program 1. IDK - for compiling and executing 2. Editor software - for typing and saving, Known editor softwares are notepad, Editplus, Textpad, Notepad++, Eclinse, NetBeans. Command prompt - for executing javac, and java commands Procedure to develop Java program Step #1; Create a folder to store all your programs, This folder is called the “presentWorkingDirectory”. Assuming the folder path as (D:\Naresi IT\HariKrishna\01Basics) : — zs 2S) edn Sas = Agta 0eK0) 4 4 Ret Genet Leam Java with Compiler and JVM Aschitectures | wnicoduction to Java | Step #2: Open notepad (start -> run -> notepad) and type below code TY Untled- Netepoa { | System.out.printhn("Hi' ; } Step #3: Save this file in 01Basics folder with name Example.java, Note: java file name can be user defined name. Itis not always mandatory to save Java file name with same class name. (f class is declared as “public” then only it is mandatory to save the file with class name. Let us try with different java file name. public static void main(String] args) | Exampleava - Notepad Format View Help Edit class FirstProgram 1 | | | public static void main(String[] args) | ht System.out.println("Hi"); Folder structure - [mse * Feutntay sStweh> tl soa aca toa bak Fc jeampejn || Srna jf Otens Program development is completed, now let us compile and execute Naresh i Technologies, Ameerpet, Hyderabad,Ph: 040-23746666, 9000994007 | Page 31 ‘Learn Java with Compiler and JVM Architectures Compilation and execution Step #4: Compilation 1. Open command prompt 2. Change Drive and then directory to current working directory to 01Basics folder 3._Then use javac tool to compile Example java file, as shown below Bi Citeieioninentne a AMiccosoft Windows (version 6.1-76007 |conyright (c) 2009 Microsoft Corporation. All rights reserved. :\ed “D:\NareshIT\Har ikrishna\CoreJavatoc3P\01Bas ics" pve "0: b:\wareshit arte iehnacorezavatosn oxsesicavae EapTe Tm] 0: \WareshrT Wark ishna\coresavagoc3P\O1Bases>. fron Compiler has generated “class” file successfully for the class FirstProgram in O1Basics folder Q) Guess what is the “.class” file name? Itis name is FirstProgram.class, not Example.class Note: Compiler generates “.class” file with the class name not java file name. Check 01Basics folder for “.class” file name seston een) 40% het a Hain 2 CoraBOOr les Serene oo Step #5: Execution Use java tool to execute FirstProgram class bytecodes file, as shown below Wt evcoveizemine [are Windows [Version 6-1. 7600; = ‘opyright (c) 2009 Microsoft Corporation.’ 17 rights reserved. \users\Harikrishna>b: | ae 4, b: t\>cd “D: \NareshIT\Harikrishna\CoreJava&ocIP\OlBasics™ Pon erneren Example. java Learn Java with Compiler and JVM Architectures Compiler activity It takes Java file name as its input and generates bytecodes fer all classes defined in that java file and stores each class bytecodes in a separate ".class" file with name same as class name. JVM activity: tt fakes class name as its input and searches for a .class file with the given class name. Ifit found it reads and loads that .class file bytecodes into JVM, then starts that class logic execution by calling “main" method. Q) Is main method mandatory for compilation dr execution? only required for execution not for compilation. If class does not have main method program compiled fine, but cannot be executed. It leads to suntime error or exception “Exception in thread "main' java.lang.NoSuchMethodError: main’ From Java 7 onwards we do not get above exception we get a message. That message is Error: Main method not found in class FirstProgram, please define the main method as public static void main(Stringl] args) Q) What does the compiler do if the given java file is not found? tt throws CE: javac: file not found: Q} What does JVM do if the given class's .class file is not found? It throws RE: java larig.NoClassDefFoundError; From Java 7 onwards in this case we do not get exception we get a message. That message is Error: Could not find or load main class & D:\NareshIT\Harikris| favac 4p fora list of possible options | D:\areshIT\Harikrishna\CoreJavag0CJP\01Basics>java_ A by: Java. Tang.ClassNotroundexception: A at_ java.net, URLClassLoader$1. run(URLClassLoader. java:202) tion and Runtime errors: The errors thrown by compiler at the time of compilation are called compile time errors. These errors are raised due to syntax mistakes, like spelling mistakes, wrong usage of keywords, missing ";" at end of statements, etc The errors thrown by JVM at the time of execution are called runtime errors or exceptions These errors are raised due to logical mistakes, like executing class without main method, dividing integer number with ZERO, accessing array values with wrong index, etc... —_—_— Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | ;Page 33 ‘Leam Java with Compiler and JVM Architectures Testing: To get command over compilation and execution process, execute below test cases In the above program Case #01: remove ";” at end of Sopin statement, then compile the program compiler throws below compile time error (Wesrinmtenice 4 expected 1B \NareshIT\Harikrishna\CoreJava&0CJP\01Basics>javac Example, java ex system. out.printin("Hi") a ample. java:5 {As you can notice, compiler is clearly showing the committed mistake It displays - > The error we committed Java is very easy, right? > Line number eee > The place where we should keep “,” to resolve this error. Case #02: Remove class name, then compile Case #03: Rernove method name, then compile Case #04: Change S to s in Sopln, then compile Case #05: Change args to hari, then compile and execute Case #06: Remove String] args, then compile and execute Case #07: Remove void, then compile Case #08: Remove static, then compile Case #09: Remove public, then compile Case #10: Remove main method definition completely, then compile and execute Case #11: Finally remove class definition completely, then compile and execute Before executing this case remove “class” from OtBasics folder, then try. Find out valid main method declarations from the below list ‘The program should compile and execute without errors when we use below main methods 01. public static void main(String{] args) 09. public static void mian(String[) args) 02, public static void main(String [Jargs) 03. public static void main(String args(]) 04. public static void main({}String args) 05. public static void main(String[] hari) 06. static public void main(Stringf] args) 07. public static void main(String... args) 08, public static int main(String{] args) 10. publie static void main(String[5] args) 11. public static void main(int{] args) 12. public static void main(String args) 13. public static void main() 14. static void main(String{] args) 15. public void main(String{] args) 16, void main(String[} args) Learn Java with Compiler and JVM Architectures | otroduetion to lava Below | have give list interview questions on basic java programming, Q) Can we create empty Java file, can we compile and execute it? Yes, but after compilation we do not have .class file. So we cannot execute. Example, java >javac Example java Q) Can we create empty ciass, can we compile and execute it? Yes we can create and compile empty class. Compiler generates .class file with that class name. We cannot execute this class as it does not have main method. {t leads to exception Example. java class At >javac Example java [> Aclass } >java A | Exception ... Q) Isit mandatory that java file name and class name should be same? No, not always- file name can be user defined name. Q) When should the Java file name and class name be the same? If class is declared as public, file name should be the same as the public class name, else its, name can be user defined. Example. Java Example,java class At public class A{ CE: class A is public, should be } a } DX | declared in a file named A java Q) Ina single Java file how many classes can we define? We can define more than one class. The rule is, class names shauld be different. Q) Ifa java file has multiple classes what is the java file name? public class name. if there is no public class, java file name can be user defined Q) In a java file, how many public classes can we define? Only one. We can define one public class and multiple non-public classes. Example, Java Example,java Ajava Ajava class Af public class A{ | public class A{ publicclass At | Poof) & YT th class BY class Bf class BE public class B{ ) } ) ) x Naresh i Technologies, Ameerpet, Hyderabad, Ph: 040-23746666, 9000994007 | Page 35

You might also like