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().
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Types of Method
There are two types of methods in Java:
Predefined Method
User-defined Method
Predefined Method :
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
System.out.println().
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
Method Overloading
Method overloading is a feature in Java that allows multiple methods with the same name but different parameter lists to exist within the same class. It enhances the flexibility and readability of the code.
Example :
public class PrintUtil {
public void print(String message) {
System.out.println(message);
}
public void print(String message, int times) {
for (int i = 0; i < times; i++) {
System.out.println(message);
}
}
}
Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It is a key aspect of polymorphism in Java, allowing subclasses to customize or extend the behavior of inherited methods.
In Java, String is the type of objects that can store the sequence of characters enclosed by double quotes and every character is stored in 16 bits i.e using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowing for various operations such as concatenation, comparison, and manipulation.
To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).
Example:
String demoString = “Java In String”;
2. Using new keyword (Heap Memory)
String s = new String(“Welcome”);
In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in the heap (non-pool)
In the given example only one object will be created. Firstly JVM will not find any string object with the value “Welcome” in the string constant pool, so it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance.
Example:
String demoString = new String (“Java In String”);
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.
String: It is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created.
CharSequence Interface
CharSequence Interface is used for representing the sequence of Characters in Java. Classes that are implemented using the CharSequence interface are mentioned below and these provides much of functionality like substring, lastoccurence, first occurence, concatenate , toupper, tolower etc.
String
StringBuffer
StringBuilder
1. String
String is an immutable class which means a constant and cannot be changed once created and if wish to change , we need to create an new object and even the functionality it provides like toupper, tolower, etc all these return a new object , its not modify the original object. It is automatically thread safe.
Syntax
// Method 1 String str= “geeks”;
// Method 2 String str= new String(“geeks”)
2. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can use it when we have multi threaded environment and shared object of string buffer i.e, used by mutiple thread. As it is thread safe so there is extra overhead, so it is mainly used for multithreaded program.
Syntax:
StringBuffer demoString = new StringBuffer(“GeeksforGeeks”);
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a mutable sequence of characters and it is not thread safe. It is used only within the thread , so there is no extra overhead , so it is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder(); demoString.append(“GFG”);
Immutable String in Java
A String is an unavoidable type of variable while writing any application program. String references are used to store various attributes like username, password, etc. In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can’t be changed but a new String object is created.
Example:
As you can see in the above figure that two objects are created but s reference variable still refers to “Sachin” not to “Sachin Tendulkar”.
But if we explicitly assign it to the reference variable, it will refer to “Sachin Tendulkar” object.
Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one object “Sachin”. If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different.
To avoid this kind of misinterpretation, String is immutable.
2. Thread Safe:
As the String object is immutable we don’t have to take care of the synchronization that is required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently.
Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same features to the new String objects as well as to the old ones.
SQL stands for Structured Query Language. It is a standardized programming language used to manage and manipulate relational databases.
1. Why we use SQL?
It allows end-users to communicate with databases and perform tasks like creating, updating, and deleting databases. Almost every mid to large-sized organization uses SQL, including Facebook, Microsoft, LinkedIn, and Accenture.
2. What is SQL?
Structured query language (SQL) is a programming language for storing and processing information in a relational database. A relational database stores information in tabular form, with rows and columns representing different data attributes and the various relationships between the data values. You can use SQL statements to store, update, remove, search, and retrieve information from the database. You can also use SQL to maintain and optimize database performance.
3. What does SQL do?
SQL is not like a typical programming language (like JavaScript, for example) that relies on constructs like iteration and recursion. We don’t need to tell SQL how to process data in the database—we simply give SQL server commands to perform a task (like selecting records) and the Query Engine under the hood generates an execution plan that it uses for efficient operation.
Selecting data and working with rows, columns, and tables is only the tip of the SQL iceberg! Most brands of SQL support functionality for aggregating data, indexing, creating user-defined functions and stored procedures, looping, using logical operators and variables, and managing user security.
Creating a database
Creating tables
Inserting records
Selecting records
Filtering records
Updating records
Modifying tables
2. What is PSQL ?
PostgreSQL, or Postgres, is an object-relational database management system that utilizes the SQL language. PSQL is a powerful interactive terminal for working with the PostgreSQL database. It enables users to execute queries efficiently and manage databases effectively.
Top PSQL Commands in PostgreSQL
Here are the top 22 PSQL commands that are frequently used when querying a PostgreSQL database:
Serial No.
Command
Description
1
psql -d database -U user -W
Connects to a database under a specific user
2
psql -h host -d database -U user -W
Connect to a database that resides on another host
3
psql -U user -h host "dbname=db sslmode=require"
Use SSL mode for the connection
4
\c dbname
Switch connection to a new database
5
\l
List available databases
6
\dt
List available tables
7
\d table_name
Describe a table such as a column, type, modifiers of columns, etc.
8
\dn
List all schemes of the currently connected database
9
\df
List available functions in the current database
10
\dv
List available views in the current database
11
\du
List all users and their assign roles
12
SELECT version();
Retrieve the current version of PostgreSQL server
13
\g
Execute the last command again
14
\s
Display command history
15
\s filename
Save the command history to a file
16
\i filename
Execute psql commands from a file
17
\?
Know all available psql commands
18
\h
Get help
19
\e
Edit command in your own editor
20
\a
Switch from aligned to non-aligned column output
21
\H
Switch the output to HTML format
22
\q
Exit psql shell
Additional Information:
The -d option in psql commands is used to state the database name.
The -U option specifies the database user.
The -h option indicates the host on which the database server resides.
The \h ALTER TABLE can be used to get detailed information on the ALTER TABLE statement.
Why should we use PostgreSQL?(TBD)
PostgreSQL comes with many features aimed to help developers build applications, administrators to protect data integrity and build fault-tolerant environments, and help you manage your data no matter how big or small the dataset. In addition to being free and open source, PostgreSQL is highly extensible. For example, you can define your own data types, build out custom functions, even write code from different programming languages without recompiling your database!
PostgreSQL tries to conform with the SQL standard where such conformance does not contradict traditional features or could lead to poor architectural decisions. Many of the features required by the SQL standard are supported, though sometimes with slightly differing syntax or function. Further moves towards conformance can be expected over time. As of the version 16 release in September 2023, PostgreSQL conforms to at least 170 of the 177 mandatory features for SQL:2023 Core conformance. As of this writing, no relational database meets full conformance with this standard.
Below is an inexhaustive list of various features found in PostgreSQL, with more being added in every major release:
Data Types
Primitives: Integer, Numeric, String, Boolean
Structured: Date/Time, Array, Range / Multirange, UUID
Parallelization of read queries and building B-tree indexes
Table partitioning
All transaction isolation levels defined in the SQL standard, including Serializable
Just-in-time (JIT) compilation of expressions
Reliability, Disaster Recovery
Write-ahead Logging (WAL)
Replication: Asynchronous, Synchronous, Logical
Point-in-time-recovery (PITR), active standbys
Tablespaces
Security
Authentication: GSSAPI, SSPI, LDAP, SCRAM-SHA-256, Certificate, and more
Robust access-control system
Column and row-level security
Multi-factor authentication with certificates and an additional method
Extensibility
Stored functions and procedures
Procedural Languages: PL/pgSQL, Perl, Python, and Tcl. There are other languages available through extensions, e.g. Java, JavaScript (V8), R, Lua, and Rust
SQL/JSON constructors, query functions, path expressions, and JSON_TABLE
Foreign data wrappers: connect to other databases or streams with a standard SQL interface
Customizable storage interface for tables
Many extensions that provide additional functionality, including PostGIS
Internationalisation, Text Search
Support for international character sets, e.g. through ICU collations
Case-insensitive and accent-insensitive collations
Full-text search
There are many more features that you can discover in the PostgreSQL documentation. Additionally, PostgreSQL is highly extensible: many features, such as indexes, have defined APIs so that you can build out with PostgreSQL to solve your challenges.
What is the main purpose of PostgreSQL?
PostgreSQL is used as the primary data store or data warehouse for many web, mobile, geospatial, and analytics applications.
The static keyword in Java is used for memory management primarily. It can be applied to variables, methods, blocks, and nested classes. When a member is declared static , it belongs to the class rather than instances of the class.
This means that only one instance of the static member exists, regardless of how many objects of the class are created.
Usage of Static Variables
Static variables are shared among all instances of a class. They are also known as class variables.
Example:
class Example {
static int counter = 0;
}
Static Methods
Static methods can be called without creating an instance of the class. They can access static data members and can change their values.
Example:
class Example {
static void display() {
System.out.println("Static method called");
}
}
Static Blocks
Static blocks are used for static initializations of a class. This code inside the static block is executed only once when the class is loaded into memory.
Example :
class Example {
static {
System.out.println("Static block executed");
}
}
Static Nested Classes
Static nested classes do not have access to other members of the enclosing class.
Example:
class OuterClass {
static class NestedStaticClass {
void display() {
System.out.println("Static nested class method called");
}
}
}
Tips and Best Practices
Memory Efficiency: Use static variables and methods to save memory and improve performance when the same value or method is used across all instances.
Utility Methods: Declare utility methods as static, as they do not require any state from the class instances. (TBD).
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
Initialization: Use static blocks for complex static variable initialization.
Access Control: Be mindful of access control; static members can be accessed directly using the class name, which might expose them unintentionally.
Avoid Overuse: Overusing static members can lead to code that is difficult to test and maintain. Use them judiciously. (TBD).
Common Mistakes and Errors
Non-static Context: Attempting to access non-static members from a static context will result in a compilation error.
Overuse of Static: Overusing static variables/methods can lead to issues with thread safety and maintenance complexity. Use static members only when necessary.
In Java, the static keyword typically flags a method or field as existing not once per instance of a class, but once ever. A class exists once anyway so in effect, all classes are “static” in this way and all objects are instances of classes.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers :
Access Modifier
within class
within package
outside package by subclass only
outside package
Private
Y
N
N
N
Default
Y
Y
N
N
Protected
Y
Y
Y
N
Public
Y
Y
Y
Y
1) Private
The private access modifier is accessible only within the class.
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class from outside the class.
2) Default
If you don’t use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
public class Customer {
Customer()
{
System.out.println(“Customer”);
} public static void main(String[] args) {
Customer prod = new Customer();
}
}
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.
It provides more accessibility than the default modifer.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
2. What is Package ?
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Example :
package com.billed;
public class Billed { public static void main(String[] args) { System.out.println(“Billed a value”);
} }
How to compile java package
javac -d directory javafilename
How to access package from another package?
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the package further.
If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.
Advantage of method overloading :
Method overloading increases the readability of the program.
Different ways to overload the method :
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
1) Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
//Method overloading changing no of arguments
class Adder {
public static int add(int a,int b) { return a+b; } public static int add(int a,int b,int c) { return a+b+c; } public static void main(String[] srga) { System.out.println(Adder.add(1,12)); System.out.println(Adder.add(1,12,2)); } }
Out put :
13
15
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
class Adder { static int add(int a,int b) { return a+b; } static double add(double a,double b) { return a+b; } public static void main(String[] args) { System.out.println(Adder.add(2,13)); System.out.println(Adder.add(2.3,2.3)); } }
Out put :
15
4.6
2. What is Constructor ?
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.
Rules for Creating Java Constructor :
Constructor name must be the same as its class name.
A Constructor must have no explicit return type.
A Java constructor cannot be abstract, static, final, and synchronized.(TBD).
Types of Java Constructors :
There are two types of constructors in Java:
Default Constructor (no-arg constructor)
Parameterized Constructor
Default Constructor :
A constructor is called “Default Constructor” when it does not have any parameter.
Syntax:
<class_name>(){}
Example :
public class Customer {
Customer()
{
System.out.println(“Customer”);
} public static void main(String[] args) {
Customer prod = new Customer();
}
}
Out put :
“Customer”.
What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
Parameterized Constructor :
A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.
Example :
public class Constroctor1 { String name; int price;
public Constroctor1(String name, int price) { System.out.println(“Milk rate is”); this.name = name; this.price = price; } public static void main(String[] args) {
Constroctor1 cus = new Constroctor1(“milk”, 35); System.out.println(cus.name); System.out.println(cus.price);
} }
Out put :
Milk rate is milk 35
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example:
public class SuperMarket { String name; int price;
public static void main(String[] args) { SuperMarket prod1 = new SuperMarket(“milk”,30); SuperMarket prod2 = new SuperMarket(“curd”,20); SuperMarket prod3 = new SuperMarket(); System.out.println(prod1.name); System.out.println(prod1.price); System.out.println(prod2.name); System.out.println(prod2.price); prod1.buy();
}
public void buy() { System.out.println(price); System.out.println(name);
}
}
Out put :
milk 30 curd 10 30 milk
Difference Between Constructor and Method in Java
Java Constructor
Java Method
A constructor is used to initialize the state of an object.
A method is used to expose the behavior of an object.
A constructor must not have a return type.
A method must have a return type.
The constructor is invoked implicitly.
The method is invoked explicitly.
The Java compiler provides a default constructor if we do not have any constructor in a class.
The method is not provided by the compiler in any case.
The constructor name must be same as the class name.
The method name may or may not be same as the class name.
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.
There are the following ways to copy the values of one object into another:
By Using Constructor
By Assigning the Values of One Object into Another
By Using clone() Method of the Object Class
Java Super Class Constructor :
In Java, the concept of the “super constructor” refers to a subclass’s ability to explicitly invoke a constructor of its superclass. It is a fundamental aspect of Java’s inheritance feature, which allows one class to inherit fields and methods from another. Using the super keyword to call a superclass’s constructor is crucial for the proper initialization of an object’s inheritance hierarchy.
In object-oriented programming, a class is a basic building block. It can be defined as template that describes the data and behaviour associated with the class instantiation. Instantiating is a class is to create an object (variable) of that class that can be used to access the member variables and methods of the class.
Modifiers: A class can be public or has default access.
class keyword: The class keyword is used to create a class.
Class name: The name must begin with an initial letter (capitalized by convention).
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
2. What is Object ?
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
3. What is data types ?
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Non-Primitive Data Types in Java
In Java, non-primitive data types, also known as reference data types, are used to store complex objects rather than simple values. Unlike primitive data types that store the actual values, reference data types store references or memory addresses that point to the location of the object in memory. This distinction is important because it affects how these data types are stored, passed, and manipulated in Java programs.
4. What is variables ?
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String – stores text, such as “Hello”. String values are surrounded by double quotes
int – stores integers (whole numbers), without decimals, such as 123 or -123
float – stores floating point numbers, with decimals, such as 19.99 or -19.99
char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
boolean – stores values with two states: true or false
Syntax :
1
type variableName = value;
5. What is Methods ?
The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Two types of Method :
Static vs Non-static Method
This table summarizes the key differences between static and non-static methods in Java or similar object-oriented programming languages.
Aspect
Static Methods
Non-static Methods
Associated with
Class
Instance
Accessing Members and Methods
Can only directly access static members and methods of the class.
Can directly access both static and non-static members and methods of the class.
Initialization
Initialized when the class is loaded into memory.
Initialized when an instance of the class is created.
Scope
Available throughout the program execution
Available as long as the instance exists
Usage
Useful for utility methods, where the method does not depend on instance-specific data.
Useful for operations that require access to instance-specific data.
Calling Process
Can be called using the class name.
Must be called using an instance of the class.
Binding Process
Bound at compile-time.
Bound at runtime.
Overriding Process
Cannot be overridden.
Can be overridden in subclasses.
Memory Allocation
Memory is allocated only once for the entire program execution.
Memory allocated each time an instance is created.
6. Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of interpretation and compilation. It defines all the processes involved in creating a Java program. Java Architecture explains each and every step of how a program is compiled and executed.
Java Architecture can be explained by using the following steps:
There is a process of compilation and interpretation in Java.
Java compiler converts the Java code into byte code.
After that, the JVM converts the byte code into machine code.
In object-oriented programming, a class is a basic building block. It can be defined as template that describes the data and behaviour associated with the class instantiation. Instantiating is a class is to create an object (variable) of that class that can be used to access the member variables and methods of the class.
Modifiers: A class can be public or has default access.
class keyword: The class keyword is used to create a class.
Class name: The name must begin with an initial letter (capitalized by convention).
Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
2. What is Object ?
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
3. What is data types ?
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Non-Primitive Data Types in Java
In Java, non-primitive data types, also known as reference data types, are used to store complex objects rather than simple values. Unlike primitive data types that store the actual values, reference data types store references or memory addresses that point to the location of the object in memory. This distinction is important because it affects how these data types are stored, passed, and manipulated in Java programs.
4. What is variables ?
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
String – stores text, such as “Hello”. String values are surrounded by double quotes
int – stores integers (whole numbers), without decimals, such as 123 or -123
float – stores floating point numbers, with decimals, such as 19.99 or -19.99
char – stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes
boolean – stores values with two states: true or false
Syntax :
type variableName = value;
5. What is Methods ?
The method in Java or Methods of Java is a collection of statements that perform some specific tasks and return the result to the caller. A Java method can perform some specific tasks without returning anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method must be part of some class that is different from languages like C, C++, and Python.
A method is like a function i.e. used to expose the behavior of an object.
It is a set of codes that perform a particular task.
Two types of Method :
Static vs Non-static Method
This table summarizes the key differences between static and non-static methods in Java or similar object-oriented programming languages.
Aspect
Static Methods
Non-static Methods
Associated with
Class
Instance
Accessing Members and Methods
Can only directly access static members and methods of the class.
Can directly access both static and non-static members and methods of the class.
Initialization
Initialized when the class is loaded into memory.
Initialized when an instance of the class is created.
Scope
Available throughout the program execution
Available as long as the instance exists
Usage
Useful for utility methods, where the method does not depend on instance-specific data.
Useful for operations that require access to instance-specific data.
Calling Process
Can be called using the class name.
Must be called using an instance of the class.
Binding Process
Bound at compile-time.
Bound at runtime.
Overriding Process
Cannot be overridden.
Can be overridden in subclasses.
Memory Allocation
Memory is allocated only once for the entire program execution.
Memory allocated each time an instance is created.
6. Features of JAva
The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
Java Architecture is a collection of components, i.e., JVM, JRE, and JDK. It integrates the process of interpretation and compilation. It defines all the processes involved in creating a Java program. Java Architecture explains each and every step of how a program is compiled and executed.
Java Architecture can be explained by using the following steps:
There is a process of compilation and interpretation in Java.
Java compiler converts the Java code into byte code.
After that, the JVM converts the byte code into machine code.
Welcome to WordPress! This is a sample post. Edit or delete it to take the first step in your blogging journey. To add more content here, click the small plus icon at the top left corner. There, you will find an existing selection of WordPress blocks and patterns, something to suit your every need for content creation. And don’t forget to check out the List View: click the icon a few spots to the right of the plus icon and you’ll get a tidy, easy-to-view list of the blocks and patterns in your post.