[Go to site: main page, start]

0% found this document useful (0 votes)
12 views8 pages

Java OOP Concepts and Code Snippets

These are notes for beginners who want to learn java
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Java OOP Concepts and Code Snippets

These are notes for beginners who want to learn java
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Applications (Java) Notes

Made By: ZanboxOne

Section A: Theory & Code Snippets

Chapter 1: Object Oriented Programming

- Source Code, Bytecode and Object Code


- Compiler and Interpreter
- Principles of Java
- Difference between OOP and POP.
- Tokens

Source Code ByteCode/UniversalCode [Task Performed by Compiler]


(.java) (.class)

Byte Code Machine/Object Code


(.bin/.exe)

JVM = Java Virtual Machine (Java Interpreter)


JDK = Java Development Kit
JRE = Java Runtime Environment
API = Application Programming Interface
JAVA = (Compiler of JAVA)

Difference Between Compiler and Interpreter

Java’s Compiler is JAVAC and Java’s Interpreter is JVM.

Compiler Interpreter
Compiler will Check Entire Block of Code at Interpreter checks code line by line and stops
Once and Generate list of errors. in between if error is found
Converts source code to universal bytecode Converts bytecode to object code
Compiler is Faster Interpreter is slower
Principles of Java and other OOP Languages

1. Data Abstraction: It is the property by which essential features of a class are


represented without informing the user about background details or backend of the
code, i.e. only front end is shown to the user.

Real Life Example: A Driver of a car is interested with the functionality of the car and its
controls (ex. Clutch, gears, accelerator, brakes, and steering wheel) but not with the
internal working of the car, i.e. how the working of the combustion chamber and
hydraulics.

2. Inheritance: It is the procedure of generating a new class with the help of a class already
created by using its properties and functionality, i.e. transfer of some properties of the
parent class to a sub class.

Real Life Example: A Child inherits the properties (physical and non-materialistic) of Its
parents due to inheritance.

3. Polymorphism: In OOP, polymorphism is the feature of being able to allot a dissimilar


meaning so that a variable, a method, or an object can have more than one form. This it
is the capacity of altering characteristics and behavior of a variable, according to the
need of an object.

Real Life Example: A Car can be in the form of a private car, a race car, a taxi etc.

4. Encapsulation: It is the wrapping up of data members and methods in a single bundle of


data or unit. It means that data can be accessed in the associated function only and safe
from misuse (data hiding)

Real Life Example: A medicine capsule containing various different ingredients to


perform a specific function in the human body.

Concept of Reusability
When another class is created sharing the properties of a previously generated class;
this reduces the amount of code needed and is known as reusability.
Difference between OOP and POP

1. Object Oriented Programming


a. Divided into parts called objects
b. Has a provision for hiding Data
c. Follows bottoms up approach
d. Based on Real World
e. Code Reusability is Present
f. Ex: Java, C++, Python, C#

2. Procedure Oriented Programming


a. Divided into parts called functions
b. Does note have a way of hiding data
c. Follows top to down approach
d. Based on Unreal World
e. Code Reusability is absent
f. Ex: C, Pascal, Basics, FORTRAN

Tokens: Tokens are everything written in Java Code

1. White Spaces (Blacks and Indentations)


2. Variables
3. Operators
4. Datatypes
5. Special Symbols (//, \\, _, $)
6. Objects
7. Methods and Functions
8. Values/Literals/Constants
9. Punctuators -; ()
10. Identifiers (User Made Names: num, etc.)
11. Keywords (Words built-in the language)
Chapter 2: Objects and Classes

1. Classes (Classes Contain Data Members, and Member Methods)


//Data Members
double radius; // used for storing data

//Member Methods
Void input ()
void calculate ()
void display ()

Classes like Scanner are derived from Packages and Libraries (ex. Util package)

2. Objects (Instances of a Class)


An Object implements certain parts of a class as and how required. They are instances of
a class that contain characteristics of the same class.

New operator helps to allot memory of RAM to an object depending on how many times
it is being used and Constructor is a function or method that contains the same name as
that of the class of the object to initialize the object.

Objects contain varying characteristics, behaviors, and names.


Syntax to Create Object: [class name] [object name]=new [constructor]
Ex: Scanner sc=new Scanner([Link])

3. User Defined Datatypes: A class is a user define datatype. Such a datatype is derived
from existing datatypes. So, an object of a class containing various datatypes is a mixture
of all those datatypes. Hence, class is a user defined datatype.

Chapter 3: Values and Datatypes

Character Sets: A set of letters, digits, and special characters which is supported by a
programming language.

Java Character Sets: Alphabets, Digits Operators, Delimiters (punctuators or special characters)
ASCII Codes

ASCII – American Standard Code for Information Interchange


ASCII allows us to store any character values into numerical value in binary form. This can be
stored in the memory of a computer, processed, accessed, and displayed by the computer

Simple Ranges of ASCII Code


A to Z (Capital) 65 to 90
a to z (small) 97 to 112
0 to 9 (numbers) 48 to 57

Escape Sequences

1. Horizontal Tab (\t)


[Link](“Good Morning: \tStudents”);

2. New Line (\n)


[Link](“Good Morning:\nStudents”);

3. Double Quote (\”)


[Link](“He said, \”I eat two apples\””);

4. Single Quotes
[Link](“\’INDIA\’ is the \’seventh\’ largest country in the world”);

5. Back space(\b)

S Back Slash gives Single Slash in Output.

Data Types

1. Primitive Datatypes: These datatypes are pre-defined or built-in datatypes and their
names are reserved by a specific keyword. They have a fixed size in memory allocation
(ex: int, byte, char, long etc.)

2. Non-Primitive Datatypes: These are user defined datatypes. They don’t have a fixed
memory allocation and can increase or decrease depending on the size of variables
they contain. (ex: class, arrays, objects, String etc.)
Static Initialization: It’s basically when a value or literal is given to a variable of a certain
datatype. (ex: int a = 3;)

Dynamic Initialization: It’s basically when a variable is initialized during the execution of a
program (ex. Int e = c+ d). These can also be formulas.

Type of Datatype Size Default Value Example


byte 1 byte 0 Byte b = 10;
short 2 bytes 0 Short s = 1234
int 4 bytes 0 Int i = 123456
long 8 bytes 0L Long d = 123456L
Float 4 bytes 0.0f Float a = 10.67f
Double 8 bytes 0.0 or 0.0d Double b = 123.455
Char 2 bytes \u0000 Char c=’a’
boolean 1 bit false Boolean a =true

Type Conversion or Type Casting

Definition: Type Casting is the Conversion of Variable of one datatype into another datatype.

Implicit Type Casting: This is the conversion of a smaller datatype into a larger datatype. This
conversion is easier and happens automatically. (ex: putting a smaller box inside a bigger box)
ex: int code1= char ch; (this puts the character of variable ‘ch’ datatype ‘char’ into an integer
variable thus displaying it’s ASCII value)

Explicit Type Casting: Conversion of larger datatype into a smaller datatype. This is forced
conversion and it doesn’t happen automatically (ex: putting a large box inside a small one is
difficult)

Ex: int a = code1+32;


small = (char)a; (this puts the variable ‘a’ of ‘int’ datatype into the variable ‘small’ of char
datatype. (char) converts the integer to character. Explicit type casting is like compression.
Chapter 4: Operators

Forms of Operators:

a. Unary Operator (Single Operand Required)


Syntax: a++ (increases value of a by 1)
b. Binary Operator (Two Operands Required)
Syntax: a+b (adds a and b)
c. Ternary Operator (Works with Conditions)
Syntax: bonus=salary<6000?5000:4000 (variable = condition?true_value:false_value)

Note: For Types of Operators Textbook is the best source, so I’m not going to waste much time
but here’s a quick summary of examples associated with each operator

Arithmetic Operators (++, --, +, *, %, /)


Relational Operators (==, !=, >=, <=)
Logical (&&, ||, !)
Assignment(ternary, =)

Special Operators

1. Dot(.) operator: It is used to invoke or summon members of a class or package.


ex: [Link](“”);
Here is System is a class and out is the member of class.
ex: import [Link];
Here util is the package and Scanner is the class of util being summoned by dot operator

2. New Operator
“new” operator is used to assign dynamic memory (RAM) to store data members and
methods as a part of an object. Hence, it helps in the creation of an object and allocates
the object memory depending on it’s size and how many times it is used. It is also used
for creation of arrays. (Arrays not in portion for 9th)
ex: Scanner x=new Scanner([Link]);
Here x is the object of scanner class and ‘new’ operator allocates it dynamic memory
depending on how much it is used (ex. Int a =[Link]();)
Hierarchy of Operators
All calculations in Java follow the BEDMAS (Brackets, Exponents, Division, Multiplication,
Addition, and Subtraction) precedence and since operators are a part of this calculation,
they too have their own order of precedence. Here is the common list:

Postfix Unary ++, --


Prefix Unary and Logical Not ++, --, +, -, !
Multiplication, division and mod *, /, %
Addition and Subtraction +,-
Equality and non-equality ==, !=
Logical AND &&
Logical OR ||
Ternary ?:
Assignment =, +=,*=,/=,%=,&=,^=,|=,<<=,>>=,>>>=

Packages or Libraries are collections of classes and other packages that have various
presets for tasks like user input, Math functions and many others.

Note: Math Functions are Best Explained in Textbook so I wont waste time on that.

End of Theory Section (40mks)

Common questions

Powered by AI

The 'new' operator in Java is used to allocate dynamic memory from the heap to objects and arrays, effectively managing memory as per the requirements of the program . It creates instances of classes, allocating the necessary space for data members and methods of the class, hence facilitating object-oriented programming by enabling the instantiation of class objects .

Java, as an object-oriented programming (OOP) language, structures its code by dividing it into objects, which encapsulate data and behaviors, allowing for data hiding and reusability. It follows a bottom-up approach, is based on modeling real-world entities, and supports code reusability through inheritance . On the other hand, procedural programming languages like C divide code into procedures or functions without a mechanism for data hiding, follow a top-down approach, lack reusability features, and are based on the sequential execution of functions .

Static initialization involves assigning values to variables at the time of definition, which is efficient for memory as it sets known values initially, for example, `int a = 3;` . Dynamic initialization occurs during program execution, allowing values to be computed and assigned at runtime such as `int e = c + d;`, offering flexibility and adaptability since values can depend on conditions encountered while running the program .

Primitive data types in Java have a predefined structure and fixed memory size, providing efficiency and predictability in resource usage (e.g., `int`, `byte`, `char`). Non-primitive data types, such as classes or arrays, are flexible, allowing dynamic memory allocation based on their requirements, providing versatility for complex data manipulation and storage scenarios .

Data abstraction in software design allows for isolating the implementation details from the user, presenting only essential features. This is significant as it simplifies interface usage and fosters a robust and user-friendly design . A real-world example is the interface of a car, where users engage with controls like the steering wheel and pedals, without needing to understand the internal workings such as the combustion engine or transmission system .

The Java Virtual Machine (JVM) acts as an interpreter, converting the universal bytecode into machine-specific object code line by line, thereby enabling Java's platform independence . While the Java compiler (JAVAC) compiles source code into bytecode more quickly, the JVM interprets bytecode more slowly because it checks and executes code line by line, stopping upon errors . This makes JVM execution less efficient in terms of speed compared to the one-time compilation process of the Java compiler.

Polymorphism in object-oriented programming allows entities like variables and methods to take multiple forms. For example, a vehicle like a car can function as a personal vehicle, a race car, or a taxi, depending on its use . Encapsulation involves bundling data with the methods that operate on the data, similar to how a medicine capsule contains different ingredients to achieve a specific effect, ensuring each component is accessed correctly while remaining protected from misuse .

Inheritance enhances code reusability by allowing a new class to inherit the properties and methods of an existing class, reducing redundancy and allowing for extension of functionalities. For instance, in a program, a `Vehicle` class could have general attributes like speed. A `Car` class could inherit from `Vehicle` and have additional features like `numberOfDoors`, leveraging and extending the existing code base effectively .

Implicit type casting in Java is the automatic conversion of a smaller data type to a larger one, facilitating smooth operations without developer intervention, such as converting a `char` to an `int` . Explicit type casting requires a developer to manually convert a larger data type to a smaller one, often to meet specific variable requirements, such as converting an `int` to a `char` using a cast operator `(char)`, important for precise data handling and compression .

The hierarchy of operators in Java determines the order of operations within expressions, following BEDMAS (Brackets, Exponents, Division, Multiplication, Addition, Subtraction). For example, in the expression `5 + 3 * 2`, multiplication has higher precedence, so it computes as `5 + (3 * 2)` which equals 11 . Recognizing this hierarchy helps in evaluating expressions accurately and avoiding logical errors. Operators are categorized by priority starting with postfix unary, then prefix unary and logical NOT, followed by multiplication/division/modulus, addition/subtraction, equality, logical AND and OR, and finally assignment operators .

You might also like