Java Basics

Java Environment

JDK (Java Development Kit):

JRE (Java Runtime Environment):

JVM (JVM (Java Virtual Machine):

Java Basic Syntax

Simplest HelloWorld Program.

class HelloWorld {
    public static void main(String args[]) { 
        System.out.println("Hello, World"); 
    } 
} 
1. Class definition:
class HelloWorld
2. main() method:
public static void main(String[] args)

Note: Like in C/C++, main method is the entry point of application and will subsequently invoke all the other methods required by program.

3. println() method:
System.out.println("Hello, World");
Notes:

Java Comments

Java Data Types

Primitive Data Types

img

Notes:

Non-Primitive / Reference Data Types

Strings:

Basic Syntax:

<String_Type> <string_variable> = “<sequence_of_string>”;

Example:

// Declare String without using new operator 
String s = "GeeksforGeeks"; 

// Declare String using new operator 
String s1 = new String("GeeksforGeeks"); 

Class:

Object:

Interface:

Array:

Java Variables

What is a Variable ?
How to declare variables ?

Examples:

float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of Variables

1. Local Variables:

Example:

public class StudentDetails { 
    public void StudentAge() { 
        // local variable age 
        int age = 0; 
        age = age + 5; 
        System.out.println("Student age is : " + age); 
    } 
  
    public static void main(String args[]) { 
        StudentDetails obj = new StudentDetails(); 
        obj.StudentAge(); 
    } 
} 

Output:

Student age is : 5

Here, the variable age is a local variable to the function StudentAge(). If we use the variable age outside StudentAge() function, the compiler will produce an error

2. Instance Variables:

Examples:

import java.io.*; 
class Marks { 
    // These variables are instance variables, they are in a class and are not inside any function 
    int engMarks; 
    int mathsMarks; 
} 
  
class MarksDemo { 
    public static void main(String args[]) { 
        // first object 
        Marks obj1 = new Marks(); 
        obj1.engMarks = 50; 
        obj1.mathsMarks = 80; 
  
        // second object 
        Marks obj2 = new Marks(); 
        obj2.engMarks = 80; 
        obj2.mathsMarks = 60; 
  
        // displaying marks for first object 
        System.out.println("Marks for first object:"); 
        System.out.println(obj1.engMarks); 
        System.out.println(obj1.mathsMarks); 
  
        // displaying marks for second object 
        System.out.println("Marks for second object:"); 
        System.out.println(obj2.engMarks); 
        System.out.println(obj2.mathsMarks); 
    } 
} 

Output:

Marks for first object:
50
80
Marks for second object:
80
60
3. Static Variables

Example:

import java.io.*; 
class Emp { 
  // static variable salary 
  public static double salary; 
  public static String name = "Harsh"; 
} 

public class EmpDemo { 
  public static void main(String args[]) { 
    // accessing static variable without object 
    Emp.salary = 1000; 
    System.out.println(Emp.name + "'s average salary:"+ Emp.salary); 
  } 
} 

Output:

Harsh's average salary:1000.0

Java Keywords

What are Java Keywords ?
List of reserved words or keywords
  1. abstract -Specifies that a class or method will be implemented later, in a subclass
  2. assert -Assert describes a predicate (a true–false statement) placed in a Java program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort.
  3. boolean – A data type that can hold True and False values only
  4. break – A control statement for breaking out of loops
  5. byte – A data type that can hold 8-bit data values
  6. case – Used in switch statements to mark blocks of text
  7. catch – Catches exceptions generated by try statements
  8. char – A data type that can hold unsigned 16-bit Unicode characters
  9. class -Declares a new class
  10. continue -Sends control back outside a loop
  11. default -Specifies the default block of code in a switch statement
  12. do -Starts a do-while loop
  13. double – A data type that can hold 64-bit floating-point numbers
  14. else – Indicates alternative branches in an if statement
  15. enum – A Java keyword used to declare an enumerated type. Enumerations extend the base class.
  16. extends -Indicates that a class is derived from another class or interface
  17. final -Indicates that a variable holds a constant value or that a method will not be overridden
  18. finally -Indicates a block of code in a try-catch structure that will always be executed
  19. float -A data type that holds a 32-bit floating-point number
  20. for -Used to start a for loop
  21. if -Tests a true/false expression and branches accordingly
  22. implements -Specifies that a class implements an interface
  23. import -References other classes
  24. instanceof -Indicates whether an object is an instance of a specific class or implements an interface
  25. int – A data type that can hold a 32-bit signed integer
  26. interface – Declares an interface
  27. long – A data type that holds a 64-bit integer
  28. native -Specifies that a method is implemented with native (platform-specific) code
  29. new – Creates new objects
  30. null -Indicates that a reference does not refer to anything
  31. package – Declares a Java package
  32. private -An access specifier indicating that a method or variable may be accessed only in the class it’s declared in
  33. protected – An access specifier indicating that a method or variable may only be accessed in the class it’s declared in (or a subclass of the class it’s declared in or other classes in the same package)
  34. public – An access specifier used for classes, interfaces, methods, and variables indicating that an item is accessible throughout the application (or where the class that defines it is accessible)
  35. return -Sends control and possibly a return value back from a called method
  36. short – A data type that can hold a 16-bit integer
  37. static -Indicates that a variable or method is a class method (rather than being limited to one particular object)
  38. strictfp – A Java keyword used to restrict the precision and rounding of floating point calculations to ensure portability.
  39. super – Refers to a class’s base class (used in a method or class constructor)
  40. switch -A statement that executes code based on a test value
  41. synchronized -Specifies critical sections or methods in multithreaded code
  42. this -Refers to the current object in a method or constructor
  43. throw – Creates an exception
  44. throws -Indicates what exceptions may be thrown by a method
  45. transient -Specifies that a variable is not part of an object’s persistent state
  46. try -Starts a block of code that will be tested for exceptions
  47. void -Specifies that a method does not have a return value
  48. volatile -Indicates that a variable may change asynchronously
  49. while -Starts a while loop
Reserved for future

Some keywords are reserved, even they are not currently in use.

Literals

They look like keywords, but in actual they are literals and still can’t be used as identifiers in a program

Java Operators

What are Java Operators ?
1. Arithmetic Operators:

They are used to perform simple arithmetic operations on primitive data types.

2. Unary Operators:

Unary operators need only one operand. They are used to increment, decrement or negate a value.

3. Assignment Operator : ‘=’
variable = value;
4. Relational Operators :
variable relation_operator value 
5. Logical Operators :
6. Ternary operator :
condition ? if true : if false
7. Bitwise Operators :
8. Shift Operators :
 number shift_op number_of_places_to_shift;
9. Instance of operator
object instance of class/subclass/interface

Example:

// Java program to illustrate instance of operator 
class Operators { 
    public static void main(String[] args) { 
        Person obj1 = new Person(); 
        Person obj2 = new Boy(); 
  
        // As obj is of type person, it is not an instance of Boy or interface 
        System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person)); 
        System.out.println("obj1 instanceof Boy: " + (obj1 instanceof Boy)); 
        System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); 
  
        // Since obj2 is of type boy, whose parent class is person and it implements 
        // the interface Myinterface, it is instance of all of these classes 
        System.out.println("obj2 instanceof Person: " + (obj2 instanceof Person)); 
        System.out.println("obj2 instanceof Boy: " + (obj2 instanceof Boy)); 
        System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); 
    } 
} 
  
class Person { 
} 
  
class Boy extends Person implements MyInterface { 
} 
  
interface MyInterface { 
} 

Output:

obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true

Java Control Statements - Decision Making

What are Java Control Statements ?
1. if
if(condition) {
   // Statements to execute if
   // condition is true
}
2. if-else
if (condition){
    // Executes this block if condition is true
} else {
    // Executes this block if condition is false
}
3. nested-if
if (condition1) {
   // Executes when condition1 is true
   if (condition2) {
      // Executes when condition2 is true
   }
}
4. if-else-if ladder
if (condition1) {
    // statement;
} else if (condition2) {
   // statement;
} else if (condition3) {
   // statement;
}
.
.
.
else {
   // statement;
}
5. Switch-case
switch (expression){
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
  .
  .
  case valueN:
    statementN;
    break;
  default:
    statementDefault;
}
6. Jump Statements

Java Loops

What are Java Loops ?
1. while loop:
while (boolean condition) {
   // loop statements...
}
2. For Loop:
for (initialization condition; testing condition; increment/decrement){
    // statement(s)
}
Enhanced For Loop
for (T element : Collection obj or array) {
    // statement(s)
}

Example:

String array[] = { "Ron", "Harry", "Hermoine" }; 

for (String x : array) { 
    System.out.println(x); 
} 
Java For-Each loop
arrList.forEach((e) -> print(e));
3. do while loop
do {
    // statements..
} while (condition);