JAVA Basic Concept:
Basic syntax in Java:
Here’s a clear overview of the basic syntax in Java, which defines how Java programs
are structured and written
1. Basic Structure of a Java Program
Every Java program must have:
A class definition.
A main method — the entry point where program execution begins.
Example:
public class HelloWorld { // Class definition
public static void main(String[] args) { // Main method
[Link]("Hello, World!"); // Output statement
2. Important Syntax Rules
Case Sensitivity
Java is case-sensitive.
Example: MyClass and myclass are di erent identifiers.
Class Declaration
A Java program must have at least one class.
public class MyClass {
// code goes here
Main Method
The starting point of every Java program.
public static void main(String[] args) {
// program execution starts here
Statements
Each statement ends with a semicolon (;).
int x = 5;
[Link](x);
Braces { }
Used to define blocks of code, such as classes, methods, or loops.
if (x > 0) {
[Link]("Positive");
Comments
Used to describe code for readability (ignored by compiler).
// Single-line comment
/* Multi-line comment */
Identifiers
Names for classes, methods, and variables.
Must start with a letter, underscore (_), or dollar sign ($).
Cannot start with a number.
int totalMarks;
String studentName;
Data Types and Variables
Used to store data values.
int age = 20;
double salary = 50000.5;
char grade = 'A';
boolean isPassed = true;
Printing Output
Use [Link]() or [Link]() to display text.
[Link]("Hello Java!");
[Link]("This stays on the same line.");
3. Example Program
Here’s a simple complete example showing all the basics:
public class Example {
public static void main(String[] args) {
// Declare variables
int num = 10;
String name = "Santosh";
// Print output
[Link]("Number: " + num);
[Link]("Name: " + name);
Comment:
In Java, comments are notes or explanations written in the code that are ignored by
the compiler — they do not a ect the program's execution. Comments make your code
easier to read and understand for yourself and others.
There are three types of comments in Java:
1. Single-line comment
Begins with //
Anything after // on that line is treated as a comment.
Example:
// This is a single-line comment
int number = 10; // initializing variable
2. Multi-line comment
Begins with /* and ends with */
Everything between these symbols is ignored by the compiler.
Example:
/*
This is a multi-line comment.
It can span across multiple lines.
*/
int sum = a + b;
3. Documentation comment (JavaDoc comment)
Begins with /** and ends with */
Used to generate API documentation automatically using the JavaDoc tool.
Usually placed above classes, methods, or fields.
Example:
/**
* This class represents a simple calculator.
* It can add, subtract, multiply and divide two numbers.
*/
public class Calculator {
/**
* Adds two integers and returns the result.
* @param a First number
* @param b Second number
* @return Sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
Variable:
In Java, a variable is a container that holds data values.
It’s like a name attached to a memory location where data is stored for use in a program.
1. Definition
A variable is a named memory location used to store data that can change during
program execution.
Example:
int age = 25;
String name = "Santosh";
2. Variable Declaration
You declare a variable by specifying:
1. Data type
2. Variable name
3. (Optional) Value (initialization)
Syntax:
dataType variableName = value;
Example:
int number = 10; // integer variable
double salary = 55000; // decimal variable
char grade = 'A'; // character variable
boolean isPassed = true; // boolean variable
3. Types of Variables in Java
(a) Local Variable
Declared inside a method, constructor, or block.
Accessible only within that scope.
Must be initialized before use.
Example:
public void show() {
int x = 5; // local variable
[Link](x);
(b) Instance Variable
Declared inside a class but outside any method.
Each object of the class has its own copy.
Also known as non-static variables.
Example:
public class Student {
String name; // instance variable
int age;
public void display() {
[Link](name + " is " + age + " years old.");
(c) Static Variable (Class Variable)
Declared with the keyword static.
Shared by all objects of the class.
Belongs to the class, not to individual instances.
Example:
public class Student {
static String college = "LBEF"; // static variable
String name;
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Ram";
[Link]([Link] + " studies at " + college);
4. Naming Rules for Variables
Must start with a letter, underscore (_), or dollar sign ($).
Cannot start with a number.
Cannot be a Java keyword (like class, int, static, etc.).
Should be meaningful and written in camelCase.
Examples:
Correct Variable: studentName, totalMarks, isPassed
Incorrect Variable: 123name, class, total marks
5. Variable Example Program
public class VariableExample {
static int count = 0; // static variable
int number; // instance variable
public void setNumber(int num) {
int temp = num; // local variable
number = temp;
count++;
}
public static void main(String[] args) {
VariableExample v1 = new VariableExample();
[Link](10);
[Link]("Number: " + [Link]);
[Link]("Total Objects: " + count);
Di erence Between Local, Instance, and Static Variables
Feature / Static Variable (Class
Local Variable Instance Variable
Type Variable)
Declared inside a Declared inside a
Declared inside a class
Definition method, constructor, class but outside any
with the keyword static
or block method
Stored in heap
Memory Stored in stack Stored in method area
memory (inside
Location memory (class memory)
object)
Exists only while the Exists as long as the Exists as long as the class
Lifetime
method is executing object exists is loaded
Accessible only
Accessible through Accessible through the
Scope within the
the object class name or object
method/block
No default value
Default Gets default value Gets default value (e.g., 0,
(must be initialized
Value (e.g., 0, false, null) false, null)
before use)
Feature / Static Variable (Class
Local Variable Instance Variable
Type Variable)
Access Can have access
Cannot have access
Modifier modifiers (public, Can have access modifiers
modifiers
Use private, etc.)
Class (shared by all
Belongs To Method or block Object (instance)
objects)
Using object
How to Directly inside the Using class name
reference
Access method ([Link])
([Link])
int x = 10; inside a static String college =
Example int age; inside a class
method "LBEF";
Example Demonstrating All Types
public class Student {
static String college = "LBEF"; // static variable
int rollNo; // instance variable
void display() {
String name = "Ram"; // local variable
[Link](name + " (" + rollNo + ") - " + college);
public static void main(String[] args) {
Student s1 = new Student();
[Link] = 101;
[Link]();
}
Output:
Ram (101) – LBEF
Data Types in Java:
A data type defines the type of data a variable can store and how much memory it
requires.
Java is a strongly typed language, meaning every variable must have a data type.
Two Main Categories of Data Types
Category Description
1. Primitive Data Types Built-in types provided by Java
2. Non-Primitive (Reference) Created by the programmer or Java libraries (e.g.,
Data Types String, Array, Class)
1. Primitive Data Types
There are 8 primitive data types in Java
Type Size Example Description
byte 1 byte byte a = 10; Stores small integers (−128 to 127)
short 2 bytes short s = 1000; Stores larger integers (−32,768 to 32,767)
int 4 bytes int num = 50000; Default integer type
long 8 bytes long l = 100000L; Used for large integer values
float 4 bytes float f = 12.5f; Stores decimal numbers with single precision
double 8 bytes double d = 123.456; Stores decimal numbers with double precision
char 2 bytes char c = 'A'; Stores single characters (Unicode)
boolean 1 bit boolean flag = true; Stores true/false values
Example: Primitive Data Types
public class DataTypeExample {
public static void main(String[] args) {
int age = 22;
double salary = 45000.75;
char grade = 'A';
boolean isPassed = true;
[Link]("Your Age is: " + age);
[Link]("Salary: " + salary);
[Link]("Grade: " + grade);
[Link]("Passed: " + isPassed);
2. Non-Primitive (Reference) Data Types
Type Example Description
String String name = "Santosh"; Sequence of characters
Array int[] marks = {90, 80, 70}; Collection of same-type elements
Class class Student {} Blueprint for objects
Interface interface Shape {} Abstract type for multiple classes
Object Object obj = new Object(); Root of all classes in Java
Type Casting in Java:
Type casting means converting one data type into another.
It helps when you want to assign a value of one type to a variable of another type.
Types of Type Casting
Java supports two types of type casting:
Type Description
1. Widening (Implicit) Casting Automatically converts a smaller type to a larger type
2. Narrowing (Explicit) Casting Manually converts a larger type to a smaller type
1. Widening Casting (Implicit Type Casting)
Done automatically by Java.
Converts data from a smaller size type → larger size type.
No data loss occurs.
Conversion order:
byte → short → int → long → float → double
Example:
public class WideningExample {
public static void main(String[] args) {
int num = 10;
double result = num; // int automatically converted to double
[Link](result); // Output: 10.0
2. Narrowing Casting (Explicit Type Casting)
Done manually by the programmer.
Converts data from a larger size type → smaller size type.
May cause data loss or precision loss.
Syntax:
dataType variable = (dataType) value;
Example:
public class NarrowingExample {
public static void main(String[] args) {
double value = 9.78;
int result = (int) value; // manually cast double to int
[Link](result); // Output: 9
Example:
public class TypeCastingDemo {
public static void main(String[] args) {
// Widening
int a = 20;
double b = a; // automatic
[Link]("Widening: " + b);
// Narrowing
double x = 9.99;
int y = (int) x; // manual
[Link]("Narrowing: " + y);
}
Output:
Widening: 20.0
Narrowing: 9
User Input in Java:
In Java, user input means taking data from the user during program execution (e.g.,
typing values in the console).
The most common way is by using the Scanner class from the [Link] package.
Step 1: Import the Scanner Class
Before using Scanner, you must import it:
import [Link];
Step 2: Create a Scanner Object
Create an object to read input from the keyboard:
Scanner input = new Scanner([Link]);
Step 3: Use Scanner Methods to Read Di erent Data Types
Method Data Type Example Input
nextInt() Int 25
nextDouble() Double 12.5
nextFloat() Float 3.14
next() String (single word) Santosh
nextLine() String (whole line) Hello Java World
nextBoolean() Boolean true / false
Example Program
import [Link]; // Import Scanner class
public class UserInputExample {
public static void main(String[] args) {
Scanner input = new Scanner([Link]); // Create Scanner object
[Link]("Enter your name: ");
String name = [Link](); // Read string input
[Link]("Enter your age: ");
int age = [Link](); // Read integer input
[Link]("Hello, " + name + "! You are " + age + " years old.");
Output Example:
Enter your name: Santosh
Enter your age: 28
Hello, Santosh! You are 28 years old.
Operators in Java
Operators are symbols used to perform operations on variables and values.
Java operators can be classified into several types.
1. Arithmetic Operators
Used for mathematical calculations.
Operator Description Example
+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
/ Division 10 / 2 = 5
% Modulus (remainder) 10 % 3 = 1
++ Increment i++ or ++i
-- Decrement i-- or –i
2. Relational Operators
Used to compare two values; result is boolean (true/false).
Operator Meaning Example
== Equal to 5 == 5 → true
!= Not equal to 5 != 3 → true
> Greater than 5 > 3 → true
< Less than 3 < 5 → true
>= Greater than or equal 5 >= 5 → true
<= Less than or equal 3 <= 5 → true
3. Logical Operators
Used with boolean values for decision making.
Operator Meaning Example
&& Logical AND (true && false) → false
|| Logical OR (true || false) → true
! Logical NOT !true → false
4. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign x = 10
+= Add and assign x += 5 → x = x + 5
-= Subtract and assign x -= 5 → x = x – 5
*= Multiply and assign x *= 5 → x = x * 5
/= Divide and assign x /= 5 → x = x / 5
%= Modulus and assign x %= 5 → x = x % 5
5. Unary Operators
Operate on a single operand.
Operator Meaning Example
+ Positive sign +5
- Negative sign -5
++ Increment by 1 i++ or ++i
-- Decrement by 1 i-- or –i
Operator Meaning Example
! Logical NOT !true → false
6. Ternary Operator
Shortcut for if-else statement
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
int a = 10, b = 5;
int max = (a > b) ? a : b;
[Link](max); // Output: 10
Example Program Using Operators
public class OperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 5;
// Arithmetic
[Link]("a + b = " + (a + b));
[Link]("a % b = " + (a % b));
// Relational
[Link]("a > b: " + (a > b));
// Logical
boolean result = (a > b) && (b > 0);
[Link]("Logical AND: " + result);
// Ternary
int max = (a > b) ? a : b;
[Link]("Max: " + max);
Output:
a + b = 15
a%b=0
a > b: true
Logical AND: true
Max: 10