0% found this document useful (0 votes)
9 views

JAVA Sheet

Uploaded by

jam.sm.7414
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JAVA Sheet

Uploaded by

jam.sm.7414
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Variables that are defined inside blocks are only accessible

by the code which is inside. To define a block of code we can


use curly braces { [Block of Code to be executed] }

JAVA SHEET READ FROM KEYBOARD

MAIN FUNCTION SYNTAX import java.util.Scanner ; /* Import a library */

public class Name { Scanner sc_name = new Scanner (System.in) ;

public static void main (String [] args) { String name = sc_name.next ( ) ;


/* This is a multi-line Comment */ sc_name.close ( ) ;
// This is a single-line Comment
DEBUG
System.out.println("Hello World" + var) ;
static final boolean debug = true/false ;
}
if (debug) { [Block of Code to be executed] }
}

VARIABLES STRINGS

Strings are objects that contain a collection of characters


DECLARATION
surrounded by double quotes:
[Public/Private] [Static] [Final] [Type] name = value ;
[Modifiers] String name = "Text\n" ;
Example: double number = 10.51e4 ;
Length ( ) name.length ( )
The word final means that the value of a variable is fixed, this IndexOf ( ) name.indexOf ("[Text]")
is useful for constant definition. The word static means that toUpperCase ( ) name.toUpperCase ( )
the value of a variable is shared by all the objects of the same toLowerCase ( ) name.toLowerCase ( )
class. We can choose between different primitive types or
classes. Note that a variable can be declared and not We can concatenate two Strings using the symbol + or using
initialized in the same instruction. The word private means the method concat. We can use special characters and
that the value of a variable is only accessible by the class sequences:
methods, and not accessible for other classes.
\' '
Boolean 1 bit true or false
\" "
Char 16 bits 'a' 'b' (ISO Unicode)
\\ \
Byte (integer) 8 bits -128 to +127
\n New line
Short (integer) 16 bits -32768 to +32767
\r Carriage return
-2147483648 to
Int (integer) 32 bits \t Tabulation
+2147483647
\b Blackspace
-9223372036854775808l to
Long (integer) 64 bits \f Form Feed
+ 9223372036854775807l
Float (real) 32 bits 1.4e-45f to 3.4e+38f
Double (real) 64 bits 4.9e-324 to 1.8e308
OPERATORS
String Object "text"
ARITHMETIC OPERATORS
CASTING
Addition + var1 = var2 + var3 ;
Type casting allows changing the type of a variable. Java Subtraction - var1 = var2 – var3 ;
makes widening casting automatically. However, narrowing Multiplication * var1 = var2 * var3 ;
casting must be done manually. Division / var1 = var2 / var3 ;
Modulus % var1 = var2 % var3 ;
variable = ([Type]) variable ; Increment ++ ++ var ;
Example: int integer = (int) number ; Decrement -- -- var ;

BLOCKS LOGICAL OPERATORS

© 2021 Alberto Ceballos. All rights reserved.


This kind of operator returns a Boolean value that can be }
true or false (0 or 1).
WHILE LOOP
Equal to == var1 == var2
Not Equal to != var1 != var2 do {
Greater than > var1 > var2
Less than < var1 < var2 [Block of Code to be executed] ;
Greater or Equal to >= var1 >= var2
Less or Equal to <= var1 <= var2 }
AND && expression1 && expression2
while (condition) ;
OR || expression1 || expression2
NOT ! ! expression1 while (condition) {

ASSIGNMENT OPERATORS [Block of Code to be executed] ;

The value of the left variable is assigned to the right variable. }

Note that the instruction continue will stop the current


= var1 = var2 ; var1 = var2 ;
iteration and will start the following one.
+= var1 += var2 ; var1 = var1 + var2 ;
-= var1 -= var2 ; var1 = var1 - var2 ;
FOR LOOP
*= var1 *= var2 ; var1 = var1 * var2 ;
/= var1 /= var2 ; var1 = var1 / var2 ;
for (statement1; statement2; statement 3) {
%= var1 %= var2 ; var1 = var1 % var2 ;
[Block of Code to be executed] ;
FLOW CONTROL
}
IF/ELSE Where statement1 is executed only one time before the
loop, statement2 is a condition and statement3 is executed
if (condition) { after each iteration. Example: for (int i = 0; i < value; i++) { }.
We can also go through the elements of an array:
[Block of Code to be executed] ;
for ([array-type] element : array-name) { }
}

else if (condition) { /* & last condition is false */ ARRAYS

[Block of Code to be executed] ; [Type] [ ] [ [ ] * n dim] name = { value1, value2, value3 } ;

} Example: int [ ] numbers = { 1, 2, 3 } ; /* 1-D array */

else { Arrays can be declared and not initialized in the same


instruction:
[Block of Code to be executed] ;
[Type] [ ] [ [ ] * n dim] name = new [Type] [size] ;
}
Example: int [ ] [ ] matrix = new int [3] [3] ; /* 2-D array */
We can reduce the lines of code using the ternary operator:
Note that name.length will return the size of the array and
variable = (condition) ? value-if-true : value-if-false ; name [ [Index] ] will allow accessing to each element and its
modification. Example: numbers [0] = 1 ;
SWITCH – CASE
Once an array is declared and instantiated, it must be filled
switch (variable) { with values using a for loop for instance.

case value: ENUMERATED TYPES


[Block of Code to be executed] ;
Special class that represents a group of constants (final string
break ; variables).

default: enum name {

[Block of Code to be executed] ; CTE1, CTE2, CTE3; }

© 2021 Alberto Ceballos. All rights reserved.


name.CTE_NAME allows accessing to each element of the Note that methods which return no data are identified by
enumerated type. The method values ( ) returns an array of the type void. The word Static means that the method can
all the constants. be accessed without creating an object. To execute the
methods we use:
ARRAY LISTS
- name_obj.method ([args]) ; (Public)
Special class that implements a resizable array. Use only - method ([args]) ; (Static)
when conventional arrays can’t be used.
Note that we can create different methods with the same
import java.util.ArrayList ;
name and different number of arguments.
import java.util.Collections ;
CONSTRUCTORS
ArrayList <[Type]> name = new ArrayList <[Type]> ( ) ;
Special method that is executed when an object is initialized.
Note that we can choose between different built-in types or
classes (String, Integer, Character, Double, Boolean, etc). It can be used to initialize the object attributes.

Add ( ) Add elements name.add (var) public Name_class ([Type] name_arg) {


Get ( ) Access to elements name.get (item)
Set ( ) Change elements name.set (item, var) [Block of Code to be executed] ;
Remove ( ) Delete elements name.remove (item)
Clear ( ) Delete all name.clear ( ) }
Size ( ) Get array length name.size ( )
Note that we can create different constructors with different
Note that collections.sort (ArrayList) allows sorting the list. number of arguments.

OBJECT-ORIENTED PROGRAMMING INHERITANCE

CLASSES [Public] class SubClass extends SuperClass {

[Attributes & Methods] ;


[Final] [Public] class Name_class {
}
[Attributes & Methods] ;
The new constructor method will extend the previous
}
superclass constructor.
Name_class name_obj = new Name_class ([args]) ;
public SubClass ([Type] name_arg) {
The word public means that other classes like Main can use
super ([args]) ;
the defined class.
[Block of Code to be executed] ;
ATTRIBUTES
}
Variables that are defined inside a class (using the classical
Note that object instanceof class will return a boolean value.
definition syntax shown previously). To access to the class
True if the object class is class, and False otherwise. The
attributes we use this.attribute inside the class definition or
SuperClass attributes must be public or protected, otherwise
name_obj.attribute outside the class.
the SubClass will not be able to access to its value. The word
final means that other classes can’t inherit from a specific
METHODS
class. Note that SubClasses can overwrite attributes and
[Private/Public] [Static] [Return] name ([Type] name_arg) { methods (this is called Polymorphism). Subclasses can only
inherit from one superclass.
[Block of Code to be executed] ;
ABSTRACT CLASSES
return variable ;
Classes that cannot be used to create objects, they must be
}
previously inherited from another class. We use the keyword
abstract to define this kind of classes.

© 2021 Alberto Ceballos. All rights reserved.


[Abstract] class Name_class { finally { [Block of Code] }

[Regular Attributes & Methods] ; Note that we can catch different kinds of exceptions (at the
same time). We can add a finally statement that will be
[Abstract] [Return] name ([Type] name_arg) ; executed regardless of whether the exception has occurred
or not. We can throw our own custom exceptions:
}
class Exception_name extends Exception { }
Inside abstract classes we can declare abstract methods
(without body) that will be implemented by the subclasses. class name throws Exception_name {
Note that the subclasses must implement these methods.
[Block of Code to be executed] ;
INTERFACES
throw ( new Exception_name (message) ) ;
Completely abstract classes that can only contain abstract
}
methods (no constructor method) and final attributes. Note
that interfaces cannot be used to create objects. Interface
methods are by default abstract and public, while attributes
are by default public static and final.

interface Name_interface {

[Type] attribute_name = value ;

[Return] method_name ([Type] name_arg) ;

To create classes that inherits these attributes and methods


we use the keyword implements instead of extends. Note
that the subclasses must implement all the abstract methods
(except abstract subclasses).

class Name_class implements Name_interface {

[Method Implementation] ;

[Return] name ([Type] name_arg) {[block of code]}

Java allows subclasses to implement multiple interfaces


(separate them with a comma). Note that inheritance
between interfaces is allowed.

EXCEPTIONS

Exceptions help to handle execution errors (not syntax ones)


making our code more robust and safer.

try { [Block of code suspected to raise an exception] }

catch ([Exception_name] message_name) {

[Block of Code to be executed] ;

return method_name ( ) ; /* recursion */

© 2021 Alberto Ceballos. All rights reserved.

You might also like