Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Primitive No Primitive: Data Types

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

JAVA

In Java, variables are only accessible inside the region they are created. This is called scope.
The final keyword is useful when you want a variable to always store the same value, like Pi
The final keyword is called a "modifier”
Primitive and no Primitive data types
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
1. Primitive types are predefined (already defined) in Java. Non-primitive types are created
by the programmer and is not defined by Java (except for String).
2. Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
3. A primitive type has always a value, while non-primitive types can be null.
4. A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all
the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
1. Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Java operators
Java divides the operators into the following groups:
 Arithmetic operators: + - % * / ++ --
 Assignment operators: = += -= *= /= %= &= |= ^= >>= <<=
 Comparison operators : == != > < >= <=
 Logical operators: && || !
 Bitwise operators
Working with strings in Java
The concat() method to concatenate two strings:
Java uses the + operator for both addition and concatenation.
Numbers are added. Strings are concatenated.
txt1 \"txt\" txt2." output: txt1 "txt" txt2. \"txt\"
"txt1\'txt txt2." output: txt1'txt txt2. \'txt
The sequence \\ inserts a single backslash in a string:
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed

Conditions in Java
There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands.
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

}
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for
loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
Syntax
for (type variableName : arrayName) {

// code block to be executed

Java methods
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method. Methods are used to perform certain
actions, and they are also known as functions. Why use methods? To reuse code: define the code
once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you
can also create your own methods to perform certain actions:
Example : Create a method inside Main:
public class Main {

static void myMethod() {

// code to be executed

}
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class.
void means that this method does not have a return value.
Parameters
When a parameter is passed to the method, it is called an argument
static void myMethod(String fname)
fname is a parameter while if we add unique names then its called an argument
Return Values
The void keyword indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char,
etc.) instead of void, and use the return keyword inside the method
Method Overloading
Multiple methods can have the same name as long as the number and/or type of parameters are
different.

Java - OOP
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
methods.
Object-oriented programming has several advantages over procedural programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You
should extract out the codes that are common for the application, and place them at a single place
and reuse them instead of repeating it.
A class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and methods from the class.
To create an object of Main(when Main in this case is the name of our class) , specify the class
name, followed by the object name, and use the keyword new:
Main myObj = new Main();
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for
better organization of classes (one class has all the attributes and methods, while the other class
holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name.
Static vs. Public
A static method, which means that it can be accessed without creating an object of the class,
unlike public, which can only be accessed by objects
Methods
The dot (.) is used to access the object's attributes and methods.
To call a method in Java, write the method name followed by a set of parentheses (), followed by
a semicolon (;).
A class must have a matching filename (Main and Main.java).

Java Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial values
for object attributes
The constructor name must match the class name, and it cannot have a return type (like void).
The constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you. However, then you are not able to set initial values for object attributes.

Java Modifiers
We divide modifiers into two groups:
 Access Modifiers - controls the access level
 Non-Access Modifiers - do not control access level, but provides other functionality
Access Modifiers
For classes, you can use either public or default:
1. public The class is accessible by any other class
2. default The class is only accessible by classes in the same package. This is used when
you don't specify a modifier.
For attributes, methods and constructors, we use the one of the following:
1. Public The code is accessible for all classes
2. Private The code is only accessible within the declared class
3. Default The code is only accessible in the same package. This is used when you
don't specify a modifier.
4. Protected The code is accessible in the same package and subclasses.
Non-Access Modifiers
For classes, you can use either final or abstract:
1. Final The class cannot be inherited by other classes
2. Abstract The class cannot be used to create objects (To access an abstract class, it must
be inherited from another class)
For attributes and methods, you can use the one of the following:
1. Final Attributes and methods cannot be overridden/modified
2. Static Attributes and methods belongs to the class, rather than an object
3. Abstract Can only be used in an abstract class, and can only be used on methods. The
method does not have a body, for example abstract void run();. The body is provided
by the subclass (inherited from).
4. Transient Attributes and methods are skipped when serializing the object containing
them
5. Synchronized Methods can only be accessed by one thread at a time
6. Volatile The value of an attribute is not cached thread-locally, and is always read
from the "main memory

Java Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
 declare class variables/attributes as private
 provide public get and set methods to access and update the value of a private variable
Get and Set
Private variables can only be accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable, with
the first letter in upper case:
Example
public class Person {

private String name; // private = restricted access

// Getter

public String getName() {

return name;

// Setter

public void setName(String newName) {

this.name = newName;

The get method returns the value of the variable name.


The set method takes a parameter (newName) and assigns it to the name variable. The this
keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this class:
Why Encapsulation?
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use the get method), or write-only (if
you only use the set method)
 Flexible: the programmer can change one part of the code without affecting other parts
 Increased security of data

Java Packages
Java Packages & API
A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are
divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much much
more.
The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that
belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code: Example
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found
in the Scanner class documentation.
To create a package, use the package keyword

Java Inheritance
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
we use the extends keyword to inherit from a class.

Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related to
each other by inheritance.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those
methods to perform different tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method called animalSound().
Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.)

Java Inner Classes


In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is
to group classes that belong together, which makes your code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create an object of the
inner class Example:
class OuterClass {

int x = 10;

class InnerClass {

int y = 5;

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();

OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x);

Private Inner Class


Unlike a "regular" class, an inner class can be private or protected. If you don't want outside
objects to access the inner class, declare the class as private
Static Inner Class
An inner class can also be static, which means that you can access it without creating an object
of the outer class

Java Abstraction
Data abstraction is the process of hiding certain details and showing only essential information to
the user. Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is a non-access modifier, used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects (to access it, it
must be inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods

Java Interface
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with empty
bodies. Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited) by
another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:
Interfaces:
 Like abstract classes, interfaces cannot be used to create objects
 Interface methods do not have a body - the body is provided by the "implement" class
 On implementation of an interface, you must override all of its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma (see example below).

Java User Input (Scanner)


The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found
in the Scanner class documentation.
Input Types
 nextBoolean() Reads a boolean value from the user
 nextByte() Reads a byte value from the user
 nextDouble() Reads a double value from the user
 nextFloat() Reads a float value from the user
 nextInt() Reads a int value from the user
 nextLine() Reads a String value from the user
 nextLong() Reads a long value from the user
 nextShort() Reads a short value from the user

Java ArrayList
The ArrayList class is a resizable array, which can be found in the java.util package.
The difference between a built-in array and an ArrayList in Java, is that the size of an array
cannot be modified (if you want to add or remove elements to/from an array, you have to create a
new one). While elements can be added and removed from an ArrayList whenever you want.
The syntax is also slightly different: Example
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // import the ArrayList class

ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object

Add Items
The ArrayList class has many useful methods. For example, to add elements to the ArrayList,
use the add() method:
Access an Item
To access an element in the ArrayList, use the get() method and refer to the index
number:Example
cars.get(0);

Change an Item
To modify an element, use the set() method and refer to the index number: Example
cars.set(0, "Opel");

Remove an Item
To remove an element, use the remove() method and refer to the index number: Example
cars.remove(0);
To remove all the elements in the ArrayList, use the clear() method
To find out how many elements an ArrayList have, use the size method: cars.size();

Java LinkedList
The LinkedList class is almost identical to the ArrayList
How the ArrayList works
The ArrayList class has a regular array inside it. When an element is added, it is placed into the
array. If the array is not big enough, a new, larger array is created to replace the old one and the
old one is removed.
How the LinkedList works
The LinkedList stores its items in "containers." The list has a link to the first container and each
container has a link to the next container in the list. To add an element to the list, the element is
placed into a new container and that container is linked to one of the other containers in the list.
Use an ArrayList for storing and accessing data, and LinkedList to manipulate data.
LinkedList Methods
For many cases, the ArrayList is more efficient as it is common to need access to random items
in the list, but the LinkedList provides several methods to do certain operations more efficiently:
 addFirst() Adds an item to the beginning of the list.
 addLast() Add an item to the end of the list
 removeFirst() Remove an item from the beginning of the list.
 removeLast() Remove an item from the end of the list
 getFirst() Get the item at the beginning of the list
 getLast() Get the item at the end of the list

Java Regular Expressions


A regular expression is a sequence of characters that forms a search pattern. When you search for
data in a text, you can use this search pattern to describe what you are searching for. A regular
expression can be a single character, or a more complicated pattern. Regular expressions can be
used to perform all types of text search and text replace operations.
Java does not have a built-in Regular Expression class, but we can import the java.util.regex
package to work with regular expressions. The package includes the following classes:
 Pattern Class - Defines a pattern (to be used in a search)
 Matcher Class - Used to search for the pattern
 PatternSyntaxException Class - Indicates syntax error in a regular expression pattern
Regular Expression Patterns
The first parameter of the Pattern.compile() method is the pattern. It describes what is being
searched for.
Brackets are used to find a range of characters:
 [abc] Find one character from the options between the brackets
 [^abc] Find one character NOT between the brackets
 [0-9] Find one character from the range 0 to 9
Metacharacters
Metacharacters are characters with a special meaning:
 | Find a match for any one of the patterns separated by | as in: cat|dog|fish
 . Find just one instance of any character
 ^ Finds a match as the beginning of a string as in: ^Hello
 $ Finds a match at the end of the string as in: World$
 \d Find a digit
 \s Find a whitespace character
 \b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b
 \uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers
Quantifiers define quantities:
 n+ Matches any string that contains at least one n
 n* Matches any string that contains zero or more occurrences of n
 n? Matches any string that contains zero or one occurrences of n
 n{x} Matches any string that contains a sequence of X n's
 n{x,y} Matches any string that contains a sequence of X to Y n's
 n{x,} Matches any string that contains a sequence of at least X n's

You might also like