Download as pdf
Download as pdf
You are on page 1of 57
OBJECT ORIENTED Ce PROGRAMMING WITH JAVA L EXPRESS —J HANDWRITTEN ENGINEERING L—ExPRESS—] Unit | Object Oriented Programming with Java Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File Structure, and Compilation. Fundamental, Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access Specifies, Static Members, Final Members, Comments, Data types, Variables, Operators, Control low, Arrays & String Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class, Overriding, Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract Class Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for Library Packages, Import and Static Import Naming Convention For Packages Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception, Control Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw, throws in Exception Handling, In-built and User Defined Exceptions, Checked and Un-Checked Exceptions. " Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java. Multithreading: Thread, Thread Life Cycle, Cre: Threads, Inter-thread Communication. ing Threads, Thread Priorities, Synchronizing Java New Features: Functional Interfaces, Lambda Expression, Method References, Stream API, Oh cdi Bini lice iis “Wi “Wii ee Wisc, Vid Wile “Se. Engineering Express © Part_| - INTRODUCTION What_is_java_? | Language language for Internet_programming. "The nome of this program was initially named Green Talk, att rv which it was changed to Oak But is platform independent. This. means that Java programming language is not made for any particular hardware operating system, hence Engineering Express © (feature of Java makes Java the most popular language even today |whase ganna” Jovo-are generated in Bitcoin format with the_| |help of a compiler and then the Java interpreter executes them available means if you write a program in window OS so you can run it easily in Linux OS detecting the errors, Java is a virus free language which keeps programs safe Engineering Express © Simple language = Java is a easy language because_in this we use Se operator, overloading and header files like C++ wi] ad In Mii Sinema AN ws i" |we_can easily ace: eae in_lnternet. U # What_is JVM JVM stand for Java Virtual Machine. | JVM is an abstract machine Cvirtual machine) |It_is like a translator for Java code, It provides run time environment _| |for java byte code to execute them. Imagine it as a special computer inside your computer, which is designed to run Java program Engineering Express © # How does it work ? Safety first - the JVM checks for error before running code, |preventing crash. _ , 1M, |work your magic. # operations |The JVM performs following operation | Loads code | Verifies codes Executes code Provide Runtime environment. Engineering Express © 9 JRE | |___# What_is IRE LIRE is stand for Java Runtime Environment. LIRE is set of software tools which. application: ) ia TE alse LIRE works with the help of JVM, Jt contains set of libraries_and_other files that JVM uses at run time._||_ | —# How. does it_work ?. | So, its work like JVM Bl LIRE = JVM + set of libraries + some other Hes SET OF LIBRARIES Eg-rtjar etc. OTHER FILES # What_is it good for ? |Memory Management - lt handles memory, garbage collection, and | L keeps things neat. S ion - The JRE in y well-organized execution. | Platform independent - You write code once, and the JVM runs it_on_| different platforms like window, mac or Linu: Safety first - the JVM checks for error before running code, preventing crash, Engineering Express © Java_environment Javac_CJava Compiler) [YavaP_ Clava. Disassembler). 1. |Jdb Clava Debuggel Engineering Express © Java Source File Structure | structure. \class and name of program must match # structure of java program line in the source file. It tells to Java program that where to find the classes and interfaces _Lmport Statements: Ct ene A def Lt is Used to import classes, interfaces, or packages from_other sources | Land allows you to use their functionality in your code. Class Definition: A |A class is a blueprint for creating object: Lt Contains variables and_function: | When we write a class definition in java, we are creating a detailed plan for how objects Will look and function. | Example: public class MyClass © vai huncti 2 Engineering Express © # procedure to write simple JAVA PROGRAM Jnstall_ IDK - Before |.JDK on your computer. etup your work space — | a) Open a text editor like Notepad on Window: b) Write your Java code in the editor. |__c) Here’s an example of a_simple “Hello, World!” program public class HelloWorld — df LM System.out.printInC Hello, World!"); A 2 | Save Your File — ee 4 a a) Save the file with a | javal extension, for example, |HelloWorld java |__a) After compilation, a \class| file will be created. |__b)Run the program using the Java command: == | java HelloWorl See the Output Dif i Lin the Command Prompt. Engineering Express © A first java_program class. Simple COMPILE- £ javac_ Simple java Public static void main(String [ J args) | | Run- £ java Simple System.out printlnCHELLO WORLD”); || OUTPUT- 2 HELLO WORLD 2 ____|| Public_keyword = it makes classes, attributes (variables), methods, Static Ki he . mr. _____|land method to say “this belongs to the class itself, not to specific | Lobject. ” 4. WS ee me, 2 2. SS Fo ran. String [ ].args — It is used for command line argument. It contains MM Yr n_runnil rogram. 5 intin€.)— Iti ; Engineering Express © COMPILATION AND EXECUTION OF JAVA PROGRAM. |In Java programming, compilation is the process of turning the code read it. | How it works ? SEL PERSE j Java ai 7 checks for mistakes. Jf everything is okay, the compiler translates your code into bytecode, |which is a special_kind of code that_Java understands, | This bytecode gets saved ina new file with a .class extension. | Then class loader_will load this_bytecode into JVM memory befor FUNDAMENTALS OF JAVA PROGRAM. te @ f Ja = a s ” to create Java programs. Think of them like the ABCs of Java. They Linclude things like: \Variables - Little boxes where you store information. Data Types - Tells you what kind of stuff you_can_put_in_the boxes, like numbers or letter: | Operators - Symbols that let you do math or compare thing: | Control Statements - Rules that tell the computer what to do next, like choosing which path to take. | Methods - Sets of instructions that you can use over and over, like a recipe, Engineering Express © together. Dhjects = Thi | ___task: \know these fundamentals tomake-Java_programs do what you want! Part 2 = programming structures in java Class Lie’s like ie for. Ae in-java. Lace EL. 1, | |_Clas. Body: Inside the class, you define field: variables) and. Lmethods Cfunctions). The body is enclosed in curly braces £ 3. Fields: A feld ie Ii ae ‘i iable Ci iable) you_can_use it to store values like numbers, text, or any other type of | data Cint for numbers, string for text etc.) M Mm , Pj ion. TI Lover again. It’s a block of codes. That does a specific task. And you | 7 Soni ink of i as_a helper that takes a particular job so you don’t have to write the |same_code multiple time: Engineering Express © Lexample: |____class MyClass £ Field int number; Method void displayNumberC) £ System.out.printlaC Number: " + number); 2 public class Main £— public static void main(String] args) ¢ 11 Creating an object of MyCla: __MyClass obj = new MyClassQ;— ne y fi Pee, , . obj.number = 10; obj displayNumber(); 3 ANN , fi : \displayNumberC) , - ; en wnt of the program. _ oe: | or ji and displayNumberO method Types Of Cla | There are two types of classes [Predefined Classes: These are the classes that come with Java itself. They? P Jova’s librari program. Examples- include String, Math, and Array List. Engineering Express © PR). SAN do. something like new Bike(). \class Bike £ int_speed: This. f Bil |BikeC) £ |speed = 0; LL Setting the init jal speed 0; the bike. 2 3 | public class TestBike £ public static void mainCStringl] args) £ // Creating a new Bike object. Bike myBike = new BikeO; Engineering Express © intinC’Bil 0 Bike.speed): 3 2 ____|| the constructor is called, and-the-bike’s speed is set. Types Of Constructors: There_are_two types of Constructors Default. Constructor his. the conto. ds’ esd. omy LL |work, like specific features you want. It’s like ordering a_car with your ||_ 0 f 4 . Rules for creating java_constructor: | Same Name: The constructors name must be exactly the same as the || class name. |No Retum Type: Constructors don’t have a return type, not even void. to_control who can use the constructor, Static: C. » ic. The f th . |not the class itself. | Overloading Allowed: You can have more than one constructor in a || class as lon each has a different set_of parameters (this is called overloading) a) | __b) | __c) || Access Levels: You can_use access modifiers like public, private, etc. a) | 2) | Engineering Express © # METHODS pie a Ae |Add a Method Body: Write the code that will run. Sem the \method is called, |Here’s the basic syntax for_creating-a_method_in Java: LaccessModifier retumType methodName(parameterTyne | parameterName) £ .// method body \// cade to be executed execute, Engineering Express |Here’s an example of a simple method that adds two numbel | public int addCint numberl, int number2) £ Lint_sum = numberl + number2; Lreturn sum; \? \In_this example, add is the method name, int is the retum type, and _| Lnumber! and number2 are parameters # ACCESS MODIFIERS Access modifiers in Java_are_like rules that tell who can use certain | Lmedia_profile. Java Access Modifiers © Default \ Tele Engineering Express le |can_access it from anywhere A it = modifier Class Package Subclass World Public uv ¥ ¥ Yy Protected y ¥ iF N Default ¥ vy N N Private x N N N HSTATIC MEMBER In Java, static members are related with the class itself rather than |with specific instances Cobjects) of the class. — ao Static Methods: You can create a static method using the static keyword. | Static methods belong to the class and can be called without creating | Lan instance of the cla: | Example: class MyClass £ | static void myStaticMethodO) £ A : vata This. : dh"): 12 2 41 Calling the static method MyClass.myStaticMethodQ); | Static Fields (Variables): | Static fields are shared among all instances of a cla. They are initialized only once when the class is loaded. | Example: Engineering Express © |class Counter £ 7 2 7 Rea |Counter() £ |__count++; // Increment count for each instance 1? 2 | public class Main £ |__ Counter cl = new Counter; Counter c2 = new-Counter(); — ; intln Total i Ounce): 3 3 void display) f ‘ Ghee Silies 1): 3 i 3 |public class Main £ public static void main(String] args) £ |__Outer.Inner innerObj = new Outer.innerQ; Engineering Express © ___||_innerObj displayO; 5 H# FINAL MEMBER ____|| Here’s an example of a final variable in use: ____|| public class Bike £ / Declare a_final variable final_int_ MAX_SPEED = 100; void run()_£ Attempting to change the value will cause an error MAX_SPEED = 120; // This line would cause a_compiler ____|lervor if uncommented 3 public static void main(String args[)) £ Bike obj = new BikeQ; Engineering Express © obj.runQ); 2 5. jos “nal” # DATA TYPES rer # is CO Le | ( | characters, and Boolean values. They are like single items you can_put_| in the box—like a toy, a book, or a piece of catady -Primitive Data Types: These inc : , sf 5 fi ; Lsuch as a set of markers or a bunch of grape. Engineering Express © Data Type Size Range | Byte | byte -128 to 127 Short 2 bytes -32,768 to 32,767 Int @ bytes | -2,147,483,648 to 2,147,483,647 ~9,2.2 3,372,036,854,775,308 to | | Long 3 bytes | 49,223, 372,036,854,775,307 Approximately 3.40282 347x038 | | Float 4 bytes pp" Y | with 7 decimal digits of precision Approximately | Double 3 bytes +1,7976 93139362 315710" 308 with |_| 1S decimal digits of precision _|- Char 2 bytes 0 to 65,535 (Unicode characters) |_| Boolean | bit true or false | | NOTE: feimwla +o fh Range »~ is SS has tp yle@ => Sas } =27 40 2°) oT iS 23 Z1 tot Qbyfe => 16 bite CO On aS So, data types help organize your data and tell the computer how to ||_ handle different kinds of information Engineering Express © COMMENTS | Multi-line comments: Start with [° and end with */ They can span Lunultiple lines and are good for longer explanation. * This. i 7 |__You can use it to write notes that are too long for a_single line. Thi é f |__and for yourself when you come back to it later. */ | System.out.printinC Hello, World!"), used to automatically generate documentation in HTML format. Here’s how you write a documentation comment: Engineering Express © ___|| _._/t_ starts with /" and ends with“; values, exceptions, and references. a * Calculates the sum of two integers. ____||_* @param a_the first integer * @param_b the second integer ____||_* @retum the sum of a and b L return a + b: 2 In this example: The first_line describes what the method does: “Calculates thi | formats al) the infon ’ve provided. This makes it easier for _____||others to understand what your code does and how to use it. Engineering Express © VARIABLE hod, ke TE Ape or changes AN |__double price; // This variable can hold decimal_numbers. | You_can_assigna_value to_a_variable-whenyou declare_it_This is called_initialization. ice = 19.29: JLT 2 dagen 3h SD 19.99. | The_scope of a variable is the_part of the program where the variable _| Lcan be accessed. | SW Avzerm hie ¢ . ea or a myMethod. Z | 2 | The lifetime of a variable is the period during which the variabl. Lexists in memory and can be accessed. /1'localVariable’ exists only during the execution of ‘myMethod. ee ee ee | program = F 7% Engineering Express © Types of Variables: Hf alate tes Bans them , alle = 5-1? Beppe | declared in. | public class MyClass £ | inh hate Paice mer Klass! 2 tatic Variables: Declared with the static keyword. They are shared i cicce-? - . 4 i | final double Pl = 3.14159: // 'Pl' is a constant and cannot be | changed. OPERATORS ____|| in Java, operators are like tools that Operators ____|| perform specific tasks on your data, such | | ____|las adding numbers or comparing values. ____|| Operands are the items that the operators xX + y = _7. , ; h | problen. Operands Result Engineering Express © +_Unary Plus C+): Indicates-a positive value, but it’s usually fa ee aN > Example. tht x = int_a, b; azxtt; x=; // a = Sx = 6 II =IS b= ++x; b= 6x = 6 I/ x =7 boolean bool = true; tru Engineering Express © | Binary operators: If value of x = 100 and y = 20 like tools for doing tasks with | (Addition)+ | z=x+y | z=120 || Ltwo numbers or values. —___| (Subtraction) - | Arithmetic operator: For basic _| (Multiplication) pexey [2220001 Lath operations * - - U Z=Xx-y z=80 5 (Division) / z=x/y z=5 (Modulus)% | z=x%y z=0 W | Relational Operators : For comparing two values. \ [Operator-Operation | Examples | Result ‘Assume the value of a=100 and b=35. Evaluate the are ice == (is Equal) >>> a==b False > (Greater than) >e>arb True < (Less than) >>>a= (Greater than or Equalto) | >>>a>=b True <= (Less than or Equal to) >>>accb False != (Not equal to) >>>al=b True | Logical Operator: For combining condition. && | Logivaliands | Gees) | Palse || lt Logical on | (S<2)/\(623) True | Logi Gs | Assignment Operator: For assigning value: Ores erent renters = x=2 Simple assignment + xt=4 x=x+4 = y-=6 yey-6 “= pts p=P*s i= n/=10 n=n/10 %= n%=10 n=n%10 Engineering Express © syntax condition? if-true: if-false Resultant Value- a ane t | Example: | class TernaryExample £ f Aiea inta = 10, b = 20: an \means “hb” is greater than “a”. |Bitwise Operator: used for control the bit patterns of the data types they are applied to, Engineering Express © complement form). Engineering Express A ; Faia ae os P two fe Shift Ce<): Shi ; p as aa 5 | the right. bi ii. (o>): Shi 5 5 = = it Clef iD ee eee a | Example: LM __ Left Shift Operator (<<) A |// work on 3 bits) Inta=S; ‘ Formula-Left Shift By | _b=as< 1; 1. A | Mean: Multiply By 2 ' la=S = Mo00010) |b = as< | = 0000/0/0 FeLN' Lb = 10 Right shift Operator (>>) \//no_condition for bits ees Uinta = 7; | Formulo-Right Shift By b= a>>1/> f | Means divide By 2 ; = a>>]= I) b= 3 Engineering Express © Control _flow _____||statements that allow you to-dictate-how your program should run Java Control Statements Selection Statements Iteration Statements — Jump Statements al > while break Trelse "Do While continue NESTE Tt ror toon Tent Haotnasit Switch | variable. || The elements of an array are stored in contiguous memory location. intl] _ mnt LS]: | elements. ____|| Types of Java Arrays: L_||.Single-Dimensional Array: A_single-dimensional array is the most common type. It consists of a single row or a single line of element: Engineering Express © | Example: intl] age = £12, 4, 5, 2, 5}: Engineering Express © | Output: | Accessing Elements of Array: | First Element: 12 second Element: 4 Third Element: | Fourth Element: 2 Fifth Element: S \ quotes) or by creating new String object Common String Methods: A O:R | Sten the sen aftl s ' ; — original string. IsCStri String): Ci ings fe it | toUpperCaseC)_and toLowerCase(); Converts the string to uppercase Lor lowercase. concat( String str): Appends a string to the end of another. startsWith(String prefix) and endsWith(String suffix): Checks if a string starts or ends with a specified substring. Engineering Express | character with another. |on a regular expression. a ; ee greeting equalslnoreCaseChello, world!")): Systern.out-printlnC Uppercase: " + greeting tolipperCaseC)) System out printinC'Starts with ‘Hello "+ Output: Length: 13 | Character at index 7: | Substring from index 0 to S: Hello \1s egual to ‘hello, world!': true Uppercase: HELLO, WORLD! Starts with ‘Hello’: true Engineering Express © Class & object already don #INHERITANCE Inheritance in Java is like getting traits from your parents. Just like ——- =——— Lanother class. | This is super useful because it-saves time and effort. Instead of ln Lage TC can. ye ina | Why we need to_use inheritance noblemen: ae , Ws | Method Overriding: If you want to change how a method works in the | i ou Riek ka Meine amends ee, Maieabamie hae | Leverything Bicycle has, and you can_add more to_it. |Here’s a tiny example: Sau £ ll eslsinckietdamnal & speed -= decrement; Engineering Express © |void speedUpCint increment) £ speed += increment; | Class: Classis a set of objects which shares common characteristic Lobjects are created. | Super Class/Parent Class: The class whose features are inherited i Lknown as asuperclass(or a base class or a parent class) Sub CNgreunaridee f nad a ALA eae eT ; ) I ; fi 5 a spars fl and method: R p a scan ne ce es ee | includes some of the code that_we want, we can derive our new class _| fy he existing cl i i reusih lds an fp we Types OF Inheritance Si Inherit . It’s like a child inheriting traits from just one rent, In Ja\ | hild) inherits from on CI vent, Engineering Express © class Pavent £ Engineering Express © lass Child impleyn nt2 Engineering Express © | public void parent!Method() £ implementation of parentl's method I ae ; Of |__// implementation of parent2's method 1? 3 \Remember, Java doesn’t support Multiple Inheritance Ca class “Diamond | inheriting from more than one class) directly due to the“ | Problem,” where the compiler_can’t decide which parent class’s |method to use. But Java_uses interfaces to_get around this issue. i, verloadin: Overridin \when you press the buttons in different ways. For example, a_single | Fa apecrebainclanegng oS PRS PENT. pe Engineering Express © Engineering Express © HENCAPSULATION A 5 = Lin |which is called a class in Java: | Encapsulation in Java is like having aspecial diary with a lock. You keep your secrets (data) inside it | you have | Private Variables: You_mark the variables of a class as private, This i \like the pages of your diary where you write your secrets. Publi 1/7, i . \the diary and read or change the content: c A F Sax onto IM) ep to. \deciding who you trust to show your diary | Protect Data: It keeps the data safe from outside interference Just Here’s a simple example in Java: iary £ Pi . ; er, private String secret: i ) public String getSecretO £ |__return secret; 3 // Public method to write a secret (setter) public void setSecret(String newSecret) £ secret = newSecret; Engineering Express © \ln this example, Diary is a class with a private variable secret. The \methads setSecret and getSecret are like the key to your diary that lets you write and yead your secrets. The SecretKeeper class show! Advantages: Z Pintection: : a h oe | interference. Flexibility: You can change the code without affecting other parts of |your program. | Reusability: Encapsulated code can be reused across different parts of |your application. re Control Over Data: You can make class read-only or write-only bi using getter and setter method Engineering Express © beet thai” f retumn_a +b +c; In this example, the add method is overloaded with different pararneter lists. Engineering Express © method to be called is determined at_runtime.It’s achieved through a |_ class Animal £ |Here, Dog overrides the speak method of Animal_When you call the _| | speak method on an Animal object that’s actually a_Dog, the Dag’: s, eee AN . ¥ f ____||performed_ in_different ways. as 4 ode R ue, . : f for diff |types and classes, which saves time and effort. Flexibility: It_allows you to write code that_can_handle different data_ types and classes, making your program more flexible. changes in one part of the codebase don’t ripple out to others. Engineering Express © |how it does. it. Jn Java programming, abstraction_is_achieved using Abstract classe. Land Interface Rules for using abstract class: We can not create object for abstract cla It may or may not contain abstract method: Engineering Express © Lt can have abstract and_non-abstract_ methods. Labstract. |When to use abstract classes: |// Abstracted class. lclass Dog extends Animal £ ii . . T public void makeSoundQ |_ _£ System.out.printinCgetNameQ) +" bari 3 Engineering Express © i an Animal myDog = new DogCBuday'); Animal myCat = new CatCFluffy'); vayDog.makeSoundQ; vayCat.makeSoundQ; + SS YA Abstract_Method \is called abstract method. A_method which contains abstract modifier at the time of declaration ||_ Rules for using abstract method: It can only be used in abstract class Engineering Express © class Main £ public static void main(String] args) t Programming h=new HTMLO; Engineering Express © |// declare constant field's \// declare methods that abstract. // by default. // This is a class that implements the interface Lelass EnglishGreeting implements Greetable £ Engineering Express © Implementing the method from the interface |___public void greetC)_£ Engineering Express © Part 4 - Packages ey en This helps avoid mix-ups where | |two files have the same name because they're in_different “folders” \Crackages) Te LY | Types _of Packages: There are two main types: — WL). OA “a, like ere ; pel \>-jass hy OL (java.io Cor input/output_tasks,) laos grerpmmee wi to RenlNcran br Ath br tet, ome BM, a 8 8§=5= i‘ rc; Engineering Express © | Write Your Classes: First, you write your Java classes and save them _| in. I names, Fc if maeaen . 3 . ; 7 , Foon ‘lasses: i java files into .class files. This is like folding your clothes neatly before they go into the suitcase, Engineering Express © |to pack all your class files into a JAR file. You need to start at the organized in different compartments of your suitcase IMP. FOR PACKAGES \ln_ Java, import and static import are like shortcuts that help you use_| classes and static members without having to write their full names levery time. IMPORT STATEMENTS FOR PACKAGES |When we write Java programs, we often use classes and method: from other packages libraries). The import statement allows us to Engineering Express © |Here’s how it works: Fj “lasses from.a. P. Gi ): | Example: L iavautil.”- [1 : j i Importing a Specific Class from a Package: | that class. ft AN | Example: an ee OE class from java.util a cing uimpatted -Clascer: 5 a . f directly in our code. For example, atter importing java.util Scanner, we can create |a Scanner object without specifying the full package name.___| STATIC IMPORT. A | Static import is a_special kind of import that allows us to use static _| lmembers (like constants or methods) directly without specifying th class name. It improves code readability but should be used carefully. Example - Using Static Import for Math Methods S he I \value_of some numbers. Normally, > , Ka jc e public static void main(Stringl] args) £ System.out.printin(Math sqrt(4)); Engineering Express © Systern.out printin( Math abs(6.3)): 2 Engineering Express: Simplifying Engineering Educotion, ‘Are you drowning in complex.ehgineering concepts? Struggling to decipher cryptic notes? Fear not! Welcome to Engineering Express, where we decode the mysteries of engineering subjects for you. x What We Offer: Clear Explanations: Our notes breok down intricate tapi¢s* tito bite-sized, easy-to-understand language. No jargon, no headaches! Real-Life Connections: Ever wondered how those abstract formulas opply in the réal world? We've got you covered with relatable examples. Maximize Your Marks: Our mission? Boost your exam scores, With our-straightforward notes, you'll be well- prepared to conquer any engineering chollenge. Follow us on social media. YouTube = https://wufi youtube:com/@ EngineeringExpress:?sub_confirmation=I WhatsApp ~ https://chat.whatsapp.com/HI|6tpUlZ2SmQ3o6vleD 2DIu Instagram - https://www.,instagram.com/engineeringexpress2 3)2/ Telegram - https://t.me/engineeringexpressofficial Join the Engineering Express community today and unlock the power of simplified learning! @ @

You might also like