0% found this document useful (0 votes)
21 views159 pages

Java-BCA-II Sem

The document provides an overview of Object-Oriented Programming (OOP) through Java, detailing its evolution from early programming languages to the introduction of OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction. It emphasizes the need for OOP to manage complexity in software development and describes the responsibilities and interactions of objects within a program. Additionally, it covers Java's features, data types, and strategies for coping with complexity in programming.

Uploaded by

25bca107
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)
21 views159 pages

Java-BCA-II Sem

The document provides an overview of Object-Oriented Programming (OOP) through Java, detailing its evolution from early programming languages to the introduction of OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction. It emphasizes the need for OOP to manage complexity in software development and describes the responsibilities and interactions of objects within a program. Additionally, it covers Java's features, data types, and strategies for coping with complexity in programming.

Uploaded by

25bca107
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
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-1& I OBJECT ORIENTED THINKING © When computers were first invented, programming was done manually by toggling in a binary machine instruction by use of front panel, As programs began to grow, high level languages were introduced that gives the programmer more tools to handle complexity. + The first widespread high level language is FORTRAN, Which gave birth to structured programming in 1960's. The Main problem with the high-level language was they have no specific structure and programs becomes larger: the problem of complexity also increases, * So,C became the popular structured oriented language to solve all the above problems, + However, in SOP, when project reaches certain size its complexity exceeds, So, in 1980's a new way of programming was invented and it was OOP, OOP is a programming methodology that helps to ‘organize complex programs through the use of inheritance, encapsulation & polymorphism. NEED FOR OOP PARADIGM «Traditionally, the structured programming techniques were used earlier. + ‘There were many problems because of the use of structured programming technique. © The structured programming made use ofa top-down approach. + To overcome these problems the objectoriented programming concept was created. + The object-oriented programming makes use of bottom-up approach, © Italso manages the increasing complexity. + The description of an object-oriented program can be given as, a data that controls access to cade. * ‘The object-oriented programming technique builds a program using the objects along with a set of ‘well-defined interfaces to that object. © The object-oriented programming technique is a paradigm, as it describes the way in which elements within a computer program must be organized. + Italso describes how those elements should interact with each other, © In OOP, data and the functionality are combined into single entity called an object. © Classes as well as objects carry specific functionality in order to perform operations and to achieve the desired result, © The data and procedures are loosely coupled in procedural paradigm. + Whereas in OOP paradigm, the data and methods are tightly coupled to form objects, * These objects help to build structure models of the problem domain and enables to get effective solutions, * GOP uses various principles (or) concepts such as abstraction, inheritance, encapsulation and polymorphism, With the help of abstraction, the implementation is hidden and the functionality is exposed. + Use of inheritance can eliminate redundant code in a program, Encapsulation enables the data and methods to wrap into a single entity. Polymorphism enables the reuse of both code and design. SUMMARY OF OOP CONCEPTS * Everything is an object. ‘© Computation is performed by objects communicating with each other, requesting that other objects perform actions. Objects communicate by sending & receiving messages. A message is a request fe an action bundled with whatever arguments may be necessary to complete the task. + Each object has its own memory, which consists of other objects. © Every Object is an instance of class. A class simply represents a grouping of similar objects, such as integers oF lists. * The class is the repository for behavior associated with an object. That is all objects that are instances of same class can perform the same actions. + Classes are organized into a singly rooted tree structure, called inheritance hierarchy. OOP CONCEPTS OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every program is follows the concept of object. In other words, OOP is a way of writing programs based on the object concept, The object-oriented programming paradigm has the following core concepts. . Class + Object + Encapsulation . Inheritance + Polymorphism + Abstraction Class Class is a blue print which is containing only list of variables and methods and no memory is allocated for them, A class is a group of objects that has common properties. Object ‘© Any entity that has state and behavior is known as an object. + Forexample, a chair, pen, table, keyboard, bike, ete, It can be physical or logical. An Object can be defined as an instance of a class, + Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, ete. Encapsulation Encapsulation is the process of combining data and code into a single unit. * In OOP, every object is associated with its data and code. + In programming. data is defined as variables and code is defined as methods. * The java programming language uses the class concept ta implement encapsulation. Eneapsulation = Data * Code Class - Variables + Methods Inheritance Inheritance is the process of acquiring properties and behaviors from one object to another object or one class to another class, In inheritance, we derive a new class from the existing class, Here, the new class acquires the properties and behaviors from the existing class, In the inheritance concept, the class which provides properties is called as parent class and the class which recieves the properties are called as child class, Person name, designation learn(), walk(), eat() ee Programmer name, name, name, designation designation designation learn(), tearn(), learnt), wallki), walk(), walk(), eat(), eat(), eat(), cading() daneing() singing) Polymorphism Polymorphism is the process of defining same method with different implementation. That means creating multiple methods with different behaviors. ‘The java uses method overloading and method overriding to implement polymorphism. Method overloading - multiple methods with same name but different parameters. Method overriding multiple methods with same name and same parameters. Abstraction ‘Abstraction is hiding the internal details and showing only essential function: In the abstraction concept, we do not show the actual implementation to the end user, instead we provide only essential things. For example, if we want to drive a car, we do not need to know about the internal funetionality like how wheel system works? how brake system works? how music system works? etc. COPING WITH COMPLEXITY © Coping with complexity in Java, or any programming language, is an essential skill for software developers, * As your Java projects graw in size and comple: maintaining, debugging, and extending your code can become challenging. Here are some strategies to help you cope with complexity in Java: 1, Modularization; Breaking down the code into smaller, self-contained modules, classes, or packages to manage complexity. Each module should have a specific responsibility and interact with others through well-defined interfaces. 2. Design Patterns: Using established design patterns to solve common architectural and design problems. Design patterns provide proven solutions to recurring challenges in software development. 3. Encapsulation: Restricting access to class members using access modifiers (public, private, protected) to hide implementation details and provide a clear API for interacting with the class. 4, Abstraction: Creating abstract classes and interfaces to define contracts that classes must adhere to, making it easier to work with different implementations, 5. Documentation: Writing comprehensive documentation, including code comments and Javadoc, to explain how the code works, its purpose, and how to use it. 6, Testing: Implementing unit tests to ensure that individual components of the cade function correctly, which helps identify and prevent bugs. 7. Code Reviews: Collaborating with team members to review and provide feedback on code to catch issues and ensure code quality. 8. Version Control: Using version contral systems like Git to manage changes, track history, and collaborate with others effectively, 9, Refactoring: Regularly improving and simplifying the codebase by removing redundancy and improving its structure. ABSTRACTION MECHANISM * In Java, abstraction is a fundamental concept in ol t-oriented programming that allows you to hide complex implementation details while exposing simplified and welldefined interface. * Abstraction mechanisms in Java include the use of abstract classes and interfaces. AWAY OF VIEWING WORLD © Away of viewing the world is an idea to illustrate the object-oriented programming concept with an example of a real-world situation, © Let usconsider a situation, | am at my office and 1 wish to get food to my family members who are at my home from a hotel. Because of the distance from my office to home, there is no possibility of getting food from a hotel myself. So, how do we solve the issue? + To solve the problem, let me call zomato (an agent in food delivery community), tell them the variety and quantity of food and the hotel name from which { wish to deliver the faod to my family ‘members. AGENTS AND COMMUNITIES Let us consider a situation, I am at my office and 1 wish to get food to my family members who are at my home from a hotel. Because of the distance from my office ta home, there is no possibility of getting food from a hotel myself. So, how do we solve the issue? ‘To solve the problem, let me call zomato (an agent in food delivery community), tell them the variety and quantity of food and the hotel name from which | wish to deliver the food to my family members, An object-oriented program is structured as a community of interacting agents, called objects. Where each object provides a service (data and methods) that is used by other members of the community. In our example, the online food detivery system is a community in which the agents are zomato and set of hotels, Each hotel provides a variety of services that can be used by other members like zomato, myself, and my family in the community, RESPONSIBILITIES In object-oriented programming, behaviars of an object described in terms of responsibilities. In our example, my request for action indicates only the desired outcome (food delivered to my family), The agent (zomato) free to use any technique that solves my problem. By discussing a problem in terms of responsibilities increases the level of abstraction, TI enables more independence between the objects in solving complex problems, MESSAGES & METHODS To solve my problem, I started with a request to the agent zomato, which led to still more requests among the members of the community until my request has done. Here, the members of a community interact with one another by making requests until the problem has satisfied, Im object-oriented programming, every action is initiated by passing a message to an agent (object), which is responsible for the action, The receiver is the object to whom the message was sent. In response to the message, the receiver performs some methad to carry out the request, Every message may include any additional information as arguments, In our example, | send a request to zomato with a message that contains food items, the quantity of food, and the hotel details. The receiver uses a method to food get delivered to my home. HISTORY OF JAVA + Javaisan object oriented programming language. + Javawas created based on € and C++. * Javauses Csyntax and many of the object-oriented features are taken from C++, © Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc, © These languages had few disadvantages which were corrected in Java. + Java also innovated many new features to solve the fundamental problems which the previous ‘languages could not solve. + Java was developed by James Gosling, Patrick Naughton, Chris warth, Ed Frank and Mike Sheridon at Sun Microsystems in the year 1991, ‘© ‘This language was initially called as "OAK" but was renamed as “Java” in 1995, © The primary motivation behind developing java was the need for creating a platform independent Language (Architecture Neutral), that can be used to create a software which can be embedded various electronic devices such as remote controls, miero ovens etc. * The problem with C, C++ and most other languages is that, they are designed to compile on specific targeted CPU (ie, they are platform dependent), but java is platform Independent which ean run ‘on a variety of CPUs under different environments. © The secondary factor that motivated the development of java is to develop the applications that can run on Internet, Using java, we can develop the applications which can run on internet i.e., Applet. So, java isa platform Independent Language used far developing programs which are platform Independent and can run on internet. JAVA BUZZWORDS (JAVA FEATURES) + Javais the most popular object-oriented programming language. + Java has many advanced features; a list of key features is known as Java Buzz Words. ‘The Following list of Buzz Words * Simple * Secure + Portable © Object-oriented * Robust © Architecture-neutral (or) Platform Independent * Multi-threaded © Interpreted * High performance + Distributed © Dynamic Simple «Java programming language is very simple and easy to learn, understand, and code, * Most of the syntaxes in java follow basic programming language C and object-oriented programming concepts are similar to C+4. + Ina java programming language, many complicated features like pointers, operator overloading, structures, unions, etc. have been removed. + One of the most useful featuresis the garbage collector it makes java simpler. Secure © Java is said to be more secure program: 9g language because it does not have pointers concept. * java provides a feature "applet" which can be embedded into a web application. * The applet in java does not allow access to other parts of the computer, which keeps away from ‘harmful programs like viruses and unauthorized access, Portable + Portability is one of the core features of java. © Ifa program yields the same result on every machine, then that program is called portable. + Java programs are portable ‘© This is the result of java System independence nature. Object-oriented © Java [Link] object oriented programming language. * This means java programs use objects and classes. Robust © Robustmeans strong. © Java programs are strongand they don’t crash easily like a C or C++ programs ‘There are two reasons + Java has got excellent inbuilt exception handling features. An exception is an error that occurs at runtime, [fan exception occurs, the program terminates suddenly giving rise to problems like loss of data, Overcoming such problem is called exception handling. + Most of the C and G++ programs crash in the middle because of not allocating sufficient memory or forgetting the memory to be freed in a program. Such problems will nat accur in java because the user need not allocate or deallocate the memory in java. Everything will be taken care of by JVM only. Architecture-neutral (or) Platform Independent + Java has invented to archive "write once; run anywhere, anytime, forever", © The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform= ‘independent, * The JVM allows the java program created using one operating system can be executed on any other ‘operating system. Multi-threaded © Java supports multi-threading programming, ‘© Which allows us to write programs that do multiple operations simultaneously. Interpreted + Java programs are compiled to generate byte code, © This byte code can be downloaded and interpreted by the interpreter in JVM. * Ifwetake any other language, only an interpreter ora compiler is used to execute the program. + Butin java, we use bath compiler and interpreter for the execution. High performance © The problem with interpreter inside the [VMs that itis slow, * Because of Java programs used to run stow, ‘To overcome this problem along with the interpret + Java soft people have introduced JIT (Just in Time) compiler, to enhance the speed of execution. + So now in JVM, both interpreter and JIT compiler work together to run the program, Distributed * Information is distributed on various computers om a network. © Using Java, we can write programs, which capture information and distribute it to the client, * This is possible because Java can handle the protocols like'TCP/IP and UDP. Dynamic Java is said ta be dynamic because the java byte code may be dynamically updated on a running system and it has a dynamic memory allocation and deallocation (objects and garbage collector). DATA TYPES IN JAVA Java programming language has a rich set of data types, The data type isa category of data stored in variables. In java, data types are classified into two types and they are as follows. + Primitive Data Types + Non-primitive Data Types Data Types in java Primitive Data Types Non-primitive Data Types byte [-—Strins Integers short pg int List tang ‘Set float Stack Floating-Point migra —ssuas [—Vector [Dictionary ‘Ciaci—— sha: [—Altuser-defined classes [—ete., Boolean ——— boolean Primitive Data Types The primitive data types are built-in data types and they specify the type of value stored in a variable and the memory size, Integer Data Types Integer Data ‘Types represent integer numbers, i.e numbers without any fractional parts or decimal points, Minimum and Maximum Data Type Memory Size Default Value values byte I byte “12a to +128 0 short 2 bytes -32768 to +32767 0 int bytes -21474B3648 to +2147483647 0 +~9223372036854775 808 to toi 8 bytes oL mB ye #9223372036854775807 Float Data Types Float data types are represented numbers with decimal point. Minimum and Maximum Data Type Memory Size Default Value values 4638 to-1.4e-45 and 140-45 float A bytes oor to 3.4e38 ~1.8e308 to -4.9e-324 and 4.9e- double Bhytes ‘ood 324 to 1.8¢308 Note: Float data type can represent up to 7 digits accurately after decimal point. Double data type can represent up to 15 digits accurately after decimal point, Character Bata Type Character data type are represents a single character like a, P, & *,.etc. Minimum and Maximum Data Type Memory Size Default Value values char 2 bytes 0 to 65538 \uoaoo Boolean Data Types Boolean data types represent any of the two values, true oF false, JYM uses 1 bit to representa Boolean value internally. Minimum = and = Maximum Data Type Memory Size Default Value values boolean 1 byte Oort 0 (false) VARIABLES Variable isa name given toa memory location where we can store different values of the same data type during the program execution, The following are the rules to specify a variable name... Avariable name may contain letters, digits and underscore symbol Variable name should not start with digit. Keywords should not be used as variable names, ‘Variable name should not contain any special symbols except underscore (_). Variable name can be of any length but compiler considers only the first 31 characters of the variable name. Declaration of Variable Declaration of a variable tells to the compiler to allocate required amount of memory with specified variable name and allows only specified datatype values into that memory location, Syntax: datatype variablename; Example: int a; Syntax: data_type variable_name_1, variable name_2,. Example: int a, b; Initialization of a variable: Syntax: datatype variablename=value; Example: int a = 10; Syntax: data type variable_name_1=value, variable_name_2= value; Example: int a = 10, b = 20; SCOPE AND LIFETIME OF A VARIABLE © In programming, a variable can be declared and defined inside a class, method, or block, + Itdefines the scope of the variable ie, the visibility or accessibility of a variable, + Variable declared inside a block or method are not visible to outside. © Ifwe try todo so, we will get a compilation error, Note that the seope ofa variable can be nested, * Lifetime ofa variable indicates how long the variable stays alive in the memory. ‘TYPES OF VARIABLES IT'S SCOPE There are three types of variables in Java: 1. local variable 2, instance variable 3, static variable Variable Type ey Troughout the class except in static Until the object is available in the methods: memory, Troughout the class Until the end of the program ‘Until the control leaves the block SS Local Variables * Variables declared inside the methods or constructors or blocks are called as local variables, ‘+ The scope of local variables is within that particular method or constructor or black in which they have been declared, * Local variables are allocated memory when the method or constructor or block in which they are declared is invoked and memory is released after that particular method or constructor or block is executed. * Access modifiers cannot be assigned to local variables. © Itcan't be defined by a static keyword. * Local variables can be accessed directly with their name. Program ‘class Local Variables { public void show() { inta=10; [Link] printin(“Inside show method, a=" +a); } public void displayQ) { int b=20; ‘[Link] printin(“Inside display method, b =" + b); /{[Link](“Inside display method, a=" + a); // error } public static void main(String args(}) t LocalVariables obj = new LocalVariables(); [Link](); [Link](}; } } Instance Variables: * Variables declared outside the methods or constructors or blocks but inside the class are called as instance variables, + The scope of instance variables is inside the class and therefore all methods, constructors and blocks can access them. Instance variables are allocated memory during object creation and memory is released during object destruction, If'no object is created, then no memory is allocated. © For each object, a separate copy of instance variable is created. * Heap memory is allocated for storing instance variables. © Access modifiers can be assigned to instance variables. © Itis the responsibility of the JVM to assign default value to the instance variables as per the type of © Variable, ‘Instance variables can be called directly inside the instance area, ‘+ Instance variables cannot be called directly inside the statie area and necessarily requires an object reference for calling them. class InstanceVariable { intx = 100; public void show() { Systemout-printin(“Inside show method, x=" +x); x=x+ 100; } public void display) t [Link] println(“Inside display method, x= "+ x); iE public static void main(String args[]) : Class Variables obj = new ClassVariables(); [Link](); [Link]); } J Static variables Static variables are also known as class variable. * Static variables are declared with the keyword ‘static’ . * Astatic variable is a variable whose single copy in memory is shared by all the objects, any modification to it will also affect other objects. © Static keyword in java is used for memory management, i itsaves memory, * Static variables get memory only once in the class area at the time of class loading. © Static variables can be invoked without the need for creating an instance of a class. + Static variables contain values by default, For integers, the default value is 0, Far Booleans, itis false. And for object references, it is null. Syntax: static datatype variable name; Example; static int x=100; Syntax; [Link]; Example ‘class Employee { static intempid=500; static void emp1() { empid++; [Link]("Employee id:"tempid); } } ‘class Sample ( public static void main(String args{]) { Employee.emp1 Employeeemp10; Employeeemp1(); Emplayee.emp1(); Employee.emp1(); Employee.emp10); ARRAYS © Anarray isa collection of similar data values with a single name, © An array can also be defined as, a special type of variable that holds multiple values of the same data type ata time. In java, arrays are objects and they are created dynamically using new operator. * Everyarray in java is organized using Index values, «© The index value of an array starts with ‘0’ and ends with "zise-1', © We use the index value to access individual elements of an array. In java, there are two types of arrays and they are as follows, # One Dimensional Array = Mull mensional Array One Dimensional Array In the java programming language, an array must be created using new operator and with a specific size, The size must be an integer value but not a byte, short, or long, We use the following syntax to create an array, Syntax data_type array_name{ ] = new data_type[size]; for) data_type | array_name = new data_type[size]; Example class Onedarray { public static void main(String args[]) { inta[]=nesw int[S}; af0}=10; at al2]=70; al3]=40; al4]=50; for{int i=0;i<5ji+) [Link](afi}); } + In java,an array can also be initialized at the time of its declaration. © When an array is initialized at the time ofits declaration, it need not specify the size of the array and use of the new operator. + Here, the size is automatically decided based on the number of values that are initialized, Example intlist{] = (10,20, 30, 40, 50}; Multidimensional Array «In java, we can create an array with multiple dimensions, We can create 2-dimensional, 3+ dimensional, or any dimensional array. * In Java, multidimensional arrays are arrays of arrays. * To create a multidimensional array variable, specify each additional index using another set of square brackets. Syntax data_typearray_namef ][] = new data_type[rows] [columns]; (or) data_type[ ][] array_name = new data_type[rows] [columns]; © When an arrays initialized at the time of declaration, it need not specify the size of the array and use of the new operator. + Here, the size is automatically decided based on the number of values that are initialized. Example class Twodarray { public static void main(String args{]) { int arr{](}=({1.2,3),(2:4.5),{4,4,5}; forfint i=0;i<3;i++) { for(int j=0;)<3;j++) { Systemout-print(arr{i][j}#" } [Link](); } } OPERATORS ‘An operator isa symbol that performs an operation. An operator acts on some variables called operands to get the desired result. Example; a+b Here a, b are operands and + is operator. ‘Types of Operators 1, Arithmetic operators 2. Relational operators 3. Logical operators 4, Assignment operators 5, Inerementor Decrement operators 6. Conditional operator 7. Bit wise operators 1, Arithmetic Operators: Arithmetic Operatars are used for mathematical calculations, Operator Description + Addition : Subtraction . Multiplication t Division % Modular Program: Java Program to implement Arithmetic Operators class ArithmeticOperators { public static void main(String[] args) { inta=12,b [Link]("a + b= "+ (a+b); [Link](“a - b =" + (a- b)); [Link]("a * b=" + (a* b)); + (a/b); [Link]("a % b="+ (a % b)); [Link]("a / 2. Relational Operators: Relational operators are used to compare twa values and return a true or false result based upon that comparison. Relational operators are of 6 types Operator Description > Greater than oe Greater than or equal to < Less than < Less than or equal to Equal to Not equal to Program: Java Program to implement Relational Operators class. RelationalOperator ‘ public static void main(String(] args) { inta=10; int b= 3; int c= 5; Systemoutprintin("a> bs" + (a>b)); ‘Systemoutprintin(“a =b: "+ (a >=b)); Systemoutprintn("a <=b:" + (a <= by}; [Link](" “+la Systemout printin("“a != c:" + (a!= e)); } } 3. Logical Operator: The Logical operators are used to combine two or more conditions Logical operators are of three types 1, Logical AND (&&), 2. Logical OR (||) 3. Logician NOT (!) 1, Logical AND (&&) ; Logical AND is denoted by double ampersand characters (&&).it is used to check the combinations of more than one conditions. if any one condition false the complete condition becomes false, Truth table of Logical AND Condition1 Condition2 Condition1 && Condition2 True True True False False False True False False False False 2. Logieal OR ( |): Logical OR is denoted by double pipe characters (|J). it is used to check the combinations of more than one conditions, if any one condition true the complete condition becomes true, ‘Truth table of Logical OR Condition’ Condition2 Condition1 && Condition? True True True True False True False True True False False False 3. Logician NOT (1); Logical NOT is denoted by exclamatory characters (0), itis used to check the it makesa true condition false and false condition true. opposite result of any given test condition. i ‘Truth table of Logical NOT Condition ndition2 True False False True Example of Logical Operators class LogicalOp { public static void main (String[] args) { int x=10; [Link](x==10 && x>=5)); [Link](x==10 |] x>=5)); [Link] (! (x==10 )); 4. Assignment Operator: Assignment operators are used to assign a value (or) an expression (or) a value of a variable to another variable. ‘Syntax: variable name=expression (or) value Example; x=10; y=20; ‘The following list of Assignment operators are. Operator Description Example Meaning += Addition Assignment | x+=y xty Addition Assignment Xexey ts Addition Assignment xexty fe Addition Assignment xex/y = Addition Assignment | x%=y xexhy Example of Assignment Operators ‘class AssignmentOperator { public static void main(String[] args) { inta=4; int var; var=aj [Link] printin("var using =: "+ var); var += a; Systemout printin("var using+=:" + var}; var *= a; [Link] printin(“var using *=:"+ var); } 5: Increment And Decrement Operators ; The increment and decrement operators are very useful. ++ and re called increment and decrement operators used to add or subtract, Both are unary operators, The syntax of the operators is given below. These operators in two forms: _ prefix (++x) and postfix(x++). ++ -- ++ -- Operator Meaning +x Pre Increment =X Pre Decrement xt Post Increment xe Post Decrement re increment, first increment and then do the operation, : Pre decrement, first decrements and then do the aperation, 3: xe : Post increment, first do the operation and then increment. 4 x-~; Post decrement, first do the operation and then decrement. Example class Increment { publie static void main(String[] args) { int var: [Link] (var++); [Link] (++var); [Link] printin (vat [Link] (var): 6: Conditional Operator: A conditional operator checks the condition and executes the statement depending on the condition. Conditional operator consists of two symbols. 1 :question mark (?), 2:colon(:). ‘Syntax: condition ? exp]: exp2; It first evaluate the condition, ifit is true (non-zero) then the “exp1" is evaluated, if the condition is false (zero) then the "exp2" is evaluated, Example : class ConditionalOperator { public static void main(String|] args) { int februaryDays = 29; String result; result = (februaryDays == 28)? "Nota leap year” : "Leap year"; [Link](result); } } 7. Bitwise Operators: * Bitwise operators are used for manipulating a data at the bit level, also called as bit level programming, Bit-level programming mainly consists of 0 and 1. * Theyre used in numerical Computations to make the calculation process faster. + The bitwise logical operators work on the data bit by bit. LSB bit which is the rightmost bit, working towards ‘© Starting from the least significant the MSB (Most Significant Bit) which is the leftmost bit. Alist of Bitwise operators as follows... ater 4 Bitwise OR Bitwise XOR Bitwise Complement Left Shift 1. Bitwise AND (8): + Bitwise AND operator is represented by a single ampersand sign (&). + Two integer expre: + ifany one condition false ( 0.) the complete condition becomes false (0). ns are written on each side of the (&) operator, Truth table of Bitwise AND Condition1 | Condition? Condition! & Condition2 0 o 0 0 1 0 1 0 0 1 1 1 Example: — intx=10; inty=20; x&y x= 0000 1010 y= 0000 1011 x&y=0000 1010=10 2. Bitwise OR: + Bitwise OR operator is represented by a single vertical bar sign ([). © Two integer expressions are written on each side of the (|) operator. + ifany one condition true (1) the complete condition becomes true ( 1). ‘Truth table of Bitwise OR Condition1 | Condition? Condition! | Condition2 0 0 0 E 1 1 0 1 1 Example: — intx=10; inty xly= x= 0000 1010 y=0000 1011 x}y=00001011=11 3. Bitwise Exclusive OR: © The XOR operator is denoted bya carrot (*) symbol. # Ittakes two values and returns true if they are different; otherwise returns false, + Inbinary, the true is represented by 1 and false is represented by 0. Truth table of Bitwise XOR. Condition — Condition2 Condition1 * Condition2 0 0 0 0 1 1 1 0 1 4 f 0 Example: — intx= 10; inty=20; x*y x= 0000 1010 y=0000 1011 x*y=0000 0001 = 4. Bitwise Complement (~}: + The bitwise complement operator is a unary operator, * Itis denoted by ~, which is pronounced as tilde, + Itchanges binary digits 1 to 0 and 0 to 1. + bitwise complement ofany integer N is equal to - (N + 1). + Consideran integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36, Example; int=10; find the ~x value, x= 0000 1010 ~x= 11110101 5. Bitwise Left Shift Operator (<<): «This Bitwise Left shift operator (>) : * This Bitwise Right shift operator (>>) isa binary operator. © Itshifts the bits of a number towards right a specified [Link] times, Example: intx= 10; xer2=? o|sjelsio} Cried woth seas Resuit m2 EXPRESSIONS © In any programming language, if we want to perform any calculation or to frame any condition ete, we use a set of symbols to perform the task. These set of symbols makes an expression, In the java programming language, an expression is defined as follows, * Anexpression is a collection of operators and operands that represents a specific value. + In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical operations, and conditional operations, etc, Expression Types Inthe java programming language, expressions are divided into THREE types. They are as follows. + Infix Expression «Postfix Expression «Prefix Expression ‘The above classification is based on the operator position in the expression. Infix Expression ‘The expression which the operator is used between operands is called infix expression. The infix expression has the fallowing general structure. Example ath Postfix Expression The expression in which the operator is used after operands is called postfix expression. ‘The postfix expression has the following general structure, Example abs Prefix Expression The expression in which the operator is used before operands is called a prefix expression. ‘The prefix expression has the following general structure. Example ab CONTROL STATEMENTS In java, the default execution flow ofa program isa sequential order. ‘+ But the sequential order of execution flow may not be suitable forall situations, © Sometimes, we may want to jump from line to another line, we may want to skip a part of the program, or sometimes we may want to execute a part of the program again and again. + To solve this problem, java provides control statements, ‘Types of Control Statements Control Statements Selection Statements Iterative Statements Jump Statements. if Statement Simple if [— while -eise }—do-while a if [—for if-else-if LL ‘switch Statement ‘switch 1. Selection Control Statements In java, the selection statements are also known as decision making statements or branching statements. The selection statements are used to Select a part of the program to be executed based on a condition. Java provides the following selection statements. + if'statement + ifelse statement + ifelif'statement + nested if statement + switch statement if statement in java * In java, we use the if statement to test a con based on that condition result. + The ifstatement checks, the given condition then decides the execution ofa block of statements. If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored jon and decide the execution of a block of statements Syntax if{condtion) ifblock of statements: } ‘statement after iF block; Example public class IfStatementTest publicstatic void main(Stringf] args) { int x=10; ifs 0) xt [Link]{"x value is:"4+x); } In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition Is evaluated to False. Then the if statement ignores the execution of its block of statements. if-else statement in java + In java, we use the ifelse statement to test a condition and pick the execution of a block of statements out of two blocks based on that condition result. © The if-else statement checks the given condition then decides which block of statements to be executed based on the condition result. * Ifthe condition is True, then the true block of statements is executed and if it is False, then the false block of statements is executed. Syntax if(condtion) { true-block of statements; } else fl false-block of statements; } statement after if-block; Example public class IfElseStatementTest { public static void main(Stringf] args) ( [Link] (“Odd Number is :"sa); } } Nested if statement in java Writing an if statementinside another if-statement is called nested if statement. syntax if{condition_1) { f{condition_2) inner if-block of statements; } } public class NestedifStatementTest { publicstatic void main(String[] args) { int num=1; if{nume10) C if(num { a) [Link]("The value is equal to 1); [Link](“The value is greater than 1"); else { } [Link]-print("Nested if - else statement "); [Link]("The value is greater than 10°); if-else ifstatement in java Writing an if-statement inside else of an if statement is called if-else-if statement. ‘Syntax if(condition_1) 4 condition_1 true-block; J else if(condition 2) { condition_2 true-block; condition_1 false-block too; Example public class IfElselfStatementTest publicstatic void main(Stringf] args) { Systemout print("Value of Xis 10"); ta if(x==20) ‘ Systemoutprint("Value of X is 20°}; hes if(x==30) [Link] print("Value of X is 30"); else ‘[Link] print("This is else statement”); ee the switch statement, ane can select only one option from more number of options very easily. * In the switch statement, we provide a value that is to be compared with a value associated with each option, Whenever the given value matches the value associated with an option, the execution starts from that option. * In the switch statement, every option is defined asa case. Syntax: switch (expression) : case valuel: // statement sequence break; case value2: // statement sequence break; case valueN: ) Example class SampleSwitch { public static votd main(String args{]) { char color ='g'; switeh(color ) { case [Link]-printin(*RED*) ; break; case 'p': [Link]("GREEN") ; brea case [Link]("BLUE") ; break ; case "W's [Link]("WHITE") ; break; default: [Link]("No color") ; [Link] Statements + The java programming language provides a set of iterative statements that are used to execute a statement or a block of statements repeatedly as long as the given condition is true, + The iterative statements are also known as LOOPing statements or repetitive statements, java provides the following iterative statements. 1, while statement 2, do-while statement 3. forstatement 4, for-each statement while statement in java ‘The while statement is used ta execute a single statement or block of statements repeatedly as long as, the given condition is TRUE. The while statement is also known as Entry control !00Ping statement. Syntax while(condition) // body of 10OP } Example public class WhileTest t ‘public static void main(Stringf] args) { int num = while(num <= 10) { [Link](num); umes; I [Link] printin("Statement after while!" } } do-while statement in java «The do-while statement is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. + The do-while statements also known as the Exit control lOOPing statement. Syntax do { / [body of (OOP } while (condition); Example public class DoWhileTest t public static votd main(Stringf] args) { intnum=1; do { [Link],printin(num); num; }while(num <= 10); [Link]{"Statementafter do-while!”); } } for statement in java The for statement is used to execute a single statement ora block of statements repeatedly as lang as the given condition is TRUE, Syntax for(initialization; condition; inc/dec) { // body: Ifonly one statementis being repeated, there is no need for the curly braces. In for-statement, the execution begins with the initialization statement, After the initialization statement, it executes Condition. If the condition is evaluated to true, then the block of statements executed otherwise it terminates the for-statement. After the block of statements execution, the modification statement gets executed, followed by condition again, Example public class ForTest ‘ public static void main(Stringf] args) ‘ for(inti=0;i< 10; i++) ‘ , [Link](“i =" +i); [Link]("Statement after foi 3. Jump Statements ‘The java programming language supports jump statements that used to transfer execution control from one line to another line, The java programming language provides the following jump statements. 1. break statement 2. continue statement break When a break statement is encountered inside a 100P, the IOOP is terminated and program control resumes at the next statement following the |OOP. class BreakStatement { public static void main(String argsf] ) { inti; i=t; while(true) iffi>10) break; [Link](i+" "); ist } } } Continue This command skips the whole body of the OOP and executes the |OOP with the next iteration. On finding continue command, control leaves the rest of the statements in the OOP and goes back to the top of the 1OOP to execute it with the next iteration (value). Example /* Print Number fram 1 to 10 Except 5 */ class NumberExcept { public static void main(String argsf] ) continue; [Link]-print(i +” ‘TYPE CONVERSION AND CASTING ‘Type Casting © When a data type is converted into another data type bya programmer using the casting operator while writing a program code, the mechanism is known as type casting, © In typing casting, the destination data type may be smatier than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion. Syntax destination_datatype = (target_datatype)variable; Osis a casting operator. target. datatype : is a data type in which we want to convert the source data type. Example float x; byte y: ye(byte)x; Program public class NarrowingTypeCastingExample { public static vaid main(String args{]) { double d = 166.66; [Link] printin("Before conversion: “+d); [Link] printIn(“After conversion into int type:"*+i); } y Output: Before conversion: 166.66 After conversion into int type: 166 Type Conversion © Ifa data type is automatically converted into another data type at compile time is known as type conversion, * The conversion is performed by the compiler if both data typesare compatible with each other. Remember that the destination data type should not be smaller than the source type. + Itis also known as widening conversion of the data type. Example a=20; Float b; bea; // Now the value of variable bis 20.000 Program public class WideningTypeCastingExample { publicstatic void main(Stringf] args) t int x= 7; ‘System. out printin(“After conversion, float value "+y); } } Output: After conversion, the float value is: 7.0 STRUCTURE OF JAVA PROGRAM Structure of a Java program contains the following elements: Peete se nn Package Statement eee eee eee ae eee aed eae nes £ } Structure of Java Program main methed definition Documentation Section ‘The documentation section is an important section but optional for a java program, It includes basic information about a Java program. The information includes the author's name, date of creation, version, program name, company name, and description of the program. It improves the readability of the program. Whatever we write in the documentation section, the Java compiler ignores the statements during the execution of the program. To write the statements in the documentation section, we use comments, Comments there are three types 1. Single-line Comment: [t starts with a pair of forwarding slash (//). Example: //First Java Program 2. Multi-line Comment: It starts with a /* and ends with */, We write between these two symbols. Example: /* It isan example of multiline comment */ 3, Documentation Comment: It starts with the delimiter (/**) and ends with */, SAMPLE JAVA PROGRAM /* This is First Java Program */ Class sample { public static void main(String args(}) { t [Link]("Hello Java Programming”); Parameters used in First Java Program Let's see what is the meaning of class, public, static, void, main, String], Systemout printin().. class keyword is used to declare class in java, public keyword isan access madifier which represents visibility, It means itis visible to all. static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static methad is that there is no need to create an object to invoke the static method. ‘The main method is executed by the JVM, so it doesn't require to create an object to Invoke the main method. So it saves memory. void is the return type of the method. It means it doesn’t return any value, main represents the starting point of the program execution String{] argsis used for command line argument. [Link]() is used to print statement. Here, System is a class, out is the object of PrintStream class, printin() is the method of PrintStream class. How to Compile and Run the Java Program ‘To Compile: javacSamplejava [ program name] ToRun — : java Sample ‘Output: Hello Java Programming EXECUTION PROCESS OF JAVA PROGRAM a-d—e ‘Sample java tet ra oe oo WHAT IS JVM Java Virtual Machine is the heart of entire java program execution pracess. It is responsible for taking the .class file and converting each byte code instruction into the machine language instruction that can be executed by the microprocessor, CLASSES AND OBJECTS IN JAVA CLASSES: + In Java, classes and objects are basic concepts of Object Oriented Programm used to represent real-world concepts and entities, + classes usually consist of two things: instance variables and methods, ig (OOPS) that are «The class represents a group of objects having similar properties and behavior. + For example, the animal type Dogis a class while a particular dog named Tommy is an object of the Dog class. + Itis a user-defined blueprint or prototype from which objects are created. For example, Student is, a class while a particular student named Ravi is an object. + The java classisa template of an abject. + Every class in java forms a new data type. « Oncea class got created, we can generate as many objects as we want. Class Characteristics Identity - It is the name given to the class. State - Represents data values that are associated with an object. Behavior - Represents actions can be performed byan object. Properties of Java Classes 1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created. 2, Classdoes not occupy memory. 3. Classis graup of variables of different data types and a group of methods. 4. AClass in Java can contain: = Data member + Method + Constructor = Nested Class + Interface Creating a Class In java, we use the keyword class to create a class. A class in java contains properties as variables and behat Syntax class className ( irs as methods, data members declaration; methads definition; } + The ClassName must begin with an alphabet, and the Upper-case letter is preferred. + The ClassName must follow all naming rules, Example Here is a cass called Box that defines three instance variables: width, height, and depth, class Box t double width; double height; double depth; void volume() OBJECT + Injava,an object is an instance of a class. + Objects are the instances of a class that are created to use the attributes and methods ofa class. + All the objects that are created using a single class have the same properties and methods. But the value of properties is different for every object. Syntax ClassName objectName = new ClassName( ); + The objectName must begin with an alphabet, and a Lower-case letter is preferred, + The objectName must follow all naming rules. Example Box mybox = new Box(); The new operator dynamically allocates memory for an object. Example class Box { double width; double height; double depth; } class BoxDemo ( public static void main(String args[]) { Box mybox = new Box): double val; [Link] = 10; mybox height = 20; [Link] = 15: vol = [Link] * myboxheight* [Link]; [Link],printin("Volume is" + val); METHODS + Amethod isa block of statements under a name that gets executes only when it is called. + Every method is used to perform a specific task, The major advantage of methods Is code re- usability (define the code once, and use it many times), + Ina java programming language, a method defined as a behavior of an object. That means, every method in java must belong to a class. + Every method in java must be declared inside a class. Every method declaration has the following characteristics, + returnType - Specifies the data type of a return value. + Mame - Specifies a unique name to identify it, + parameters ~The data values it may accept or recieve, + ()+Defienes the block belongs to the method. Creating a method A method is created inside the class Syntax class ClassName { return Type methodName( parameters ) { // body of method } Callinga method + In java, a method call precedes with the object name of the class to which it belongs and a dot ‘operator, + Itmay call directly ifthe method defined with the static modifier. + Every method call must be made, as to the method name with parentheses (), and it must terminate with a semicolon, Syntax ‘objectNamemethodNamefactualArguments: ); Example //Adding a Method to the Box Class

You might also like