Core Java Tutorial | Basics of Java Programming
What is Core Java? What it contains ?
Core Java is a part of Java Standard Edition (SE) where we can develop desktop based apps using the basic concepts of Java like: Classes and objects i.e. basic OOPS programming, Operators, data types, AWT and swing, threading, exception handling, overloading, overriding and collections. Core Java has the basic set of instruction through which we can create applications. It is the base for all the Java frameworks.
Using core Java, we can build mostly general purpose desktop based applications. Advance Java covers topics like web services, JSP, servlets, dB connectivity, EJB, etc. We are going to cover all of these topics in shorts just to give you proper meaning and understanding on it.
OOPs (Object-Oriented Programming):

Data Types in java
Data types in Java provide instructions to the compiler about what should happen with data. There are two categories of data types supported: primitive types and reference types of data.
Primitive data types offered by Java are among the simplest data types, while references data types identify objects.
Primitive Data Types Primitive data types in Java represent basic values. There are four kinds of primitive types – integer types, floating point types, characters types and boolean types.
Integer Types in Java Integer types are used to represent numbers in their entirety. There are four types of integers in Java; short, byte, int and long are all types of integers used to store integer data types that represent small, medium and large values respectively. While bytes store small numbers while bytes hold larger integers. Finally long can store extremely huge integers.
Floating-Point Types
Floating-points can be used to display numbers with fractional parts. There are two floating point types in Java; these are known as float and double. Float type floating-point figures represent single precision figures while double precision numbers use double precision figures as representation.
Character Types (char) are used to indicate single characters, indicated by single quotation marks. Boolean Type (boolean) allows us to show whether an amount is either false or true by using quotation marks and an “or”.
Type Casting It refers to the act of changing data types between classes. Java supports two forms of type casting: implicit and explicit. Implicit type casting takes place automatically via compiler while explicit type casting must be carried out manually by programmers. Read more about type casting here
Exception Handling
The handling of exceptions is an method in Java that allows programmers to manage unexpected situations or errors that may happen during the execution of a program. The term “exceptions” refers to unexpected circumstances that could occur during the execution the program, for example, being unable to store memory, or attempting the division of zero.
In Java the exceptions are described as objects. The handling of exceptions is performed by using catch blocks that try to handle exceptions. Try blocks are used to wrap the code that can throw an exception, while catch blocks are used to handle an exception that is that is thrown.
If an exception occurs and an error occurs, when an exception is thrown, the Java runtime system looks for an appropriate catch block to handle the situation. If there is a catch block and the exception is caught, it is thrown and the code contained in the block that is caught will be executed. If the catch block isn’t discovered, the error is propagated through in the call stack, until it’s removed or the program ceases to function.
Collections
Collections in Java are a set of classes and interfaces that offer a way of storing and manipulating groups of objects. Collections play an integral part in Java programming and constitute part of its API.
The Java Collections Framework consists of interfaces and classes that offer a standardized way of managing collections of objects. Some popular collection classes include ArrayList, LinkedList, HashSet TreeMap HashMap.
Collections can provide several advantages, such as:
Dynamic Storage: Collections provide an easy way to organize and manipulate groups of objects dynamically, providing greater flexibility in terms of size and type of data stored.
Type Safety: The Java Collections Framework was specifically created to offer type safety, which helps avoid runtime errors and makes code easier to understand and maintain.
Performance: The Collections Framework offers optimized data structures and algorithms designed to enhance performance and reduce memory requirements when storing data.
Standardization: The Java Collections Framework offers a standardized way of managing collections of objects, making it simpler for programmers to work with code written by others.
Common interfaces used within the Java Collections Framework include List, Set and Map. These provide an efficient means for working with various collections including lists, sets and maps.
The List and Set interfaces offer ordered collections of elements. In contrast, Map provides an efficient method for matching keys to values for fast data search and retrieval.
Java Memory Management
Java is a programming language that utilizes automatic memory management for memory allocation and deallocation. The Java Virtual Machine (JVM) manages this aspect by allocating and reallocating memory for objects created in programs automatically.
Java’s memory management relies on the concept of a heap, which is an area in memory used for dynamic memory allocation. The heap can be divided into two areas – young generation and old generation – with objects initially created in young generation moving over time into its older sister section as they age.
Young Generation members are divided further into an Eden space and two survivor spaces, where objects that have just been created are stored until garbage collection arrives, when they will then be transferred into one of the survivor spaces; these survivor spaces serve as storage areas for items not eligible for collection.
Java’s garbage collector is responsible for freeing up memory that is no longer being utilized by programs. It periodically scans heap objects to detect those no longer referenced by programs. When these objects have been marked as trash they will be removed during next cycle’s garbage collection cycle.
Java offers a mechanism for controlling memory allocation through its java.lang.Runtime class. This class offers methods for allocating and allocating new memory, retrieving free space information, and forcing garbage collection.
Java’s memory management system offers several advantages over traditional methods of memory allocation and deallocation, including eliminating explicit memory allocation/deallocation to reduce risk of memory leaks and errors related to memory management. Unfortunately, however, its automatic nature imposes increased overhead costs as its garbage collector must scan heap periodically in order to detect and remove garbage objects.
JVM Memory Module
Java is a programming language that utilizes automatic memory management for memory allocation and deallocation. The Java Virtual Machine (JVM) manages this aspect by allocating and reallocating memory for objects created in programs automatically.
Java’s memory management relies on the concept of a heap, which is an area in memory used for dynamic memory allocation. The heap can be divided into two areas – young generation and old generation – with objects initially created in young generation moving over time into its older sister section as they age.
Young Generation members are divided further into an Eden space and two survivor spaces, where objects that have just been created are stored until garbage collection arrives, when they will then be transferred into one of the survivor spaces; these survivor spaces serve as storage areas for items not eligible for collection.
Java’s garbage collector is responsible for freeing up memory that is no longer being utilized by programs. It periodically scans heap objects to detect those no longer referenced by programs. When these objects have been marked as trash they will be removed during next cycle’s garbage collection cycle.
Java offers a mechanism for controlling memory allocation through its java.lang.Runtime class. This class offers methods for allocating and allocating new memory, retrieving free space information, and forcing garbage collection.
Java’s memory management system offers several advantages over traditional methods of memory allocation and deallocation, including eliminating explicit memory allocation/deallocation to reduce risk of memory leaks and errors related to memory management. Unfortunately, however, its automatic nature imposes increased overhead costs as its garbage collector must scan heap periodically in order to detect and remove garbage objects.
Conditional Statements
Conditional statements are programming constructs that allow programs to execute certain actions based on conditions that can be expressed with various logical operators such as ==,!=, =, >= and &&. In Java there are three main kinds of conditional statements: If statements, switch statements and ternary operators.
If Statements
If statements are one of the simplest types of conditional statements available in Java. They allow code execution if certain conditions are true. Here is its basic syntax in Java:
if(condition){
//execute these block of statments if the above condition is true
}
You can also use an else statement to execute a different block of code if the condition is false:
if(condition){
//execute these block of statments if the above condition is true
}else{
//execute these block of statments if the above condition is false
}
In addition to if and else statements, you can also use else-if statements to test multiple conditions in a single block of code:
if(condition){
//execute these block of statments if the above condition is true
}else if(condition_2){
//execute these block of statments if the above condition2 is true
}else{
//execute this block if both the conditions are false.
}
Switch statements are another type of conditional statement used in Java, used to check a single variable against multiple possible cases. Here is its basic syntax in Java:
switch (variable_matching_criteriaOrCondition) {
case A:
//execute this code if variable equals A
break;
case B:
// execute this code if variable equals B
break;
// add as many cases as needed
default:
// execute this code if none of the cases are true
break;
}
Ternary Operators
Ternary operators in Java provide a shorthand way of writing if-else statements. They allow programmers to assign values based on conditions. Here is its basic syntax.
variable = (condition) ? value1 : value2;
Based on condition, a value will get assigned to the variable.
Looping statements
Looping statements are programming constructs that enable a program to repeatedly execute a block of code until a specified condition has been met, typically specified using logic operators such as =, >=,!= or ==. In Java there are three main forms of looping statements: while loops, do-while loops and for loops.
While Loops
While loops are the foundational form of Java looping statements. Used to execute code repeatedly while an specified condition holds true, here’s the basic syntax for creating one:
while (condition) {
//execute this block of code while condition is true, once conditiuon is false then it will terminate the loop
}
Do-while Loops
Similar to while loops, do-while loops differ by having at least one execution before testing its condition. Here is the basic syntax of a do-while loop in Java:
do {
// execute this code at least once
} while (condition);
In do while it will always execute the block of statements at least once.
For Loops
A for loop is an advanced form of Java looping statements used to execute a block of code repeatedly for an specified number of iterations or range of values. Here is its basic syntax in Java:
for (initialization; condition; increment/decrement) {
// execute this code for each iteration of the loop
}
Initializing and testing values of counter variables are accomplished using initialization statements and condition statements respectively, while increment/decrement statements update its values after every iteration of a loop.
Example for Java: Looping Statements
Let’s look at some examples of how looping statements are implemented in Java.
While Loop
int i = 0;
while (i < 10) {
System.out.println("The value of i is: " + i);
i++;
}
Do-While Loop
int j = 0;
do {
System.out.println("The value of j is: " + j);
j++;
} while (j < 10);
For Loops
for (int k = 0; k < 10; k++) {
System.out.println("The value of k is: " + k);
}
Looping statements are an integral component of programming languages like Java. Loops allow a program to execute blocks of code repeatedly until an event or condition is met, which can prove invaluable when working on various programming projects. By understanding and mastering different types of looping statements in Java, you can produce more efficient and effective code to match exactly to your requirements and specifications.
Methods, Class & Objects
Java is an object-oriented programming language, so its based upon classes and objects. We will see further into these concepts as well as methods in Java programming language.
Classes and Objects
A Java class serves as a blueprint or template for creating objects, while objects are instances of those classes, representing concrete realizations of those properties and behaviors of said class (e.g. “Car” defines properties like color, model and speed) so you could use that class to build red Ferraris or blue toyta !
Here’s an example of creating a class in Java:
public class Car {
//Car has below properties
String color;
String model;
int speed;
int breakSpeed;
//car class constructor
public Car(String color, String model, int speed, int breakSpeed) {
this.color = color;
this.model = model;
this.speed = speed;
this.breakSpeed = breakSpeed;
}
//car class method
public void accelerate(int amount) {
this.speed += amount;
}
//car class method
public void break(int amount) {
this.breakSpeed += amount;
}
}
Creating Objects
Once You Have Defined A Class, let’s create objects of that class can be created using the “new” keyword. Here’s an example of creating new objects of Car’s class using this method:
Car carObject = new Car("blue", "Ferrari", 0 , 2);
Car carObject2 = new Car("yellow", "Ferrari", 2, 2);
Methods
Methods in Java can be used to perform actions on objects belonging to a class, such as altering properties or performing more complex tasks. Here is an example of such a method from the “Car” class:
//car class method
public void accelerate(int amount) {
this.speed += amount;
}
//car class method
public void break(int amount) {
this.breakSpeed += amount;
}
carObject.accelerate(100);
carObject.break(80);
carObject2.accelerate(33);
carObject2.break(23);