Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views24 pages

JAVA Notes 1

The document provides a comprehensive overview of basic Java programming concepts, including a simple 'HelloWorld' program, lexical analysis, Java class libraries, data types, variables, operators, control statements, and arrays. It explains the structure and components of Java code, common lexical errors, and the importance of Java class libraries for reusable code. Additionally, it details variable types, data types, type conversion, and various operators used in Java programming.

Uploaded by

palaks17008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views24 pages

JAVA Notes 1

The document provides a comprehensive overview of basic Java programming concepts, including a simple 'HelloWorld' program, lexical analysis, Java class libraries, data types, variables, operators, control statements, and arrays. It explains the structure and components of Java code, common lexical errors, and the importance of Java class libraries for reusable code. Additionally, it details variable types, data types, type conversion, and various operators used in Java programming.

Uploaded by

palaks17008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

BASIC PROGRAM OF JAVA

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Explanation of Components:

 public class HelloWorld:

o public: This is an access modifier, indicating that the class HelloWorld is accessible from any
other class.

o class: This keyword declares a class, which is the fundamental building block in Java's object-
oriented paradigm.

o HelloWorld: This is the name of the class. In Java, the class name should typically match the
filename (e.g., HelloWorld.java).

 public static void main(String[] args):

o This is the main method, the entry point for execution of any Java application.

o public: Allows the Java Virtual Machine (JVM) to access this method.

o static: Means the method belongs to the class itself, not to an instance of the class. It can be
called without creating an object of the class.

o void: Indicates that the method does not return any value.

o main: The standard name for the entry point method.

o String[] args: This declares a parameter named args, which is an array of String objects. It
allows command-line arguments to be passed to the program.

 System.out.println("Hello, World!");:

o This line prints the string "Hello, World!" to the console.

o System: A predefined class in Java's standard library.

o out: A static member of the System class, representing the standard output stream.

o println(): A method of the PrintStream class (which System.out is an instance of) that prints
the given argument and then moves the cursor to the next line.

Execution Flow:

 Compilation: The Java source code (.java file) is compiled into bytecode (.class file) by the Java
compiler (javac).

 Execution: The Java Virtual Machine (JVM) loads the .class file and executes the main method,
leading to the output "Hello, World!" on the console.
LEXICAL ISSUES IN JAVA

Lexical Issues in Java – Complete Overview

Lexical issues refer to how Java source code is broken down into meaningful tokens during the compilation
process. This step, known as lexical analysis, is the first phase of a Java compiler.

🔹 1. What is Lexical Analysis?

 It's the process of converting a sequence of characters into tokens.

 Tokens are the smallest meaningful elements: keywords, identifiers, literals, operators, etc.

🔹 2. Java Lexical Elements

Element Description & Examples

Ignored by the compiler unless inside string literals. Includes spaces, tabs, newlines. Example: int
Whitespace
x = 10;

Used for documentation, ignored by the compiler.Types:▪ // single-line▪ /* multi-line */▪ /**
Comments
Javadoc */

Names for variables, methods, classes, etc.Rules: Must begin with a letter, _, or $. Cannot be a
Identifiers
keyword.

Constant values: ▪ Integer: 10, 0xFF▪ Floating-point: 3.14, 1.0e2▪ Char: 'A'▪ String: "Hello"▪
Literals
Boolean: true, false

Separators Symbols to structure code: (), {}, [], ;, ,, .

Operators Symbols that perform operations: +, -, *, /, =, ==, &&, etc.

Reserved words with predefined meanings. Examples: int, class, return, new, if, else, static (Total:
Keywords
~50)

🔹 3. Example Program with Lexical Elements:

// Program to display message

public class Demo {

public static void main(String[] args) {

int number = 5; // integer literal

String message = "Hi!"; // string literal

System.out.println(message); // method call

Tokens here include: public, class, Demo, (, ), {, int, number, =, 5, ;, etc.


🔹 4. Common Lexical Errors

Error Type Example Description

Invalid Identifier int 2count; Cannot start with a digit

Unclosed String "Hello Missing closing quote

Unrecognized Token int @x = 5; @ not valid in identifiers

Mismatched Brackets if(x > 0 { Missing )


Java Class Libraries – Complete Overview

Java Class Libraries form the core building blocks of the Java platform. They provide predefined classes and
interfaces that developers can reuse to perform a wide range of tasks without writing code from scratch.

🔹 1. What Are Java Class Libraries?

 They are precompiled packages of Java classes provided by the Java Development Kit (JDK).

 These libraries contain thousands of standard classes that simplify programming tasks like I/O, data
structures, networking, GUIs, etc.

🔹 2. Key Features

 Reusable: Use existing classes for common tasks (e.g., file handling, math functions).

 Portable: Write once, run anywhere (WORA).

 Well-organized: Classes are grouped into packages.

🔹 3. Common Java Packages and Their Use

Package Name Description Examples

java.lang Core classes auto-imported. String, Math, Object, System

java.util Utility classes. ArrayList, HashMap, Date, Collections

java.io Input/output classes. File, BufferedReader, PrintWriter

java.net Networking. Socket, URL, HttpURLConnection

java.sql Database connectivity. Connection, Statement, ResultSet

javax.swing GUI components. JFrame, JButton, JLabel, JTextField

java.time Date and time API (Java 8+). LocalDate, LocalTime, Duration

🔹 4. Example: Using Class Libraries

import java.util.ArrayList;

public class Example {

public static void main(String[] args) {

ArrayList<String> names = new ArrayList<>();

names.add("Java");

names.add("Python");

System.out.println(names);
}

Here, ArrayList is from java.util, and System.out is from java.lang.


Java Data Types and Variables – Detailed Explanation

🔶 1. Variables in Java

A variable is a container used to store data values. In Java, every variable must be declared with a data type.

Syntax:

dataType variableName = value;

Example:

int age = 25;

String name = "John";

Types of variables:

 Local variable – declared inside a method or block.

 Instance variable – non-static variable inside a class.

 Static variable – variable declared with static keyword.

🔶 2. Data Types in Java

Java has two types of data types:

Category Examples

Primitive int, float, char, boolean

Non-Primitive String, Array, Class, Object

There are 8 primitive data types:

🔷 3. Integer Types

Used to store whole numbers.

Data Type Size Range Example

byte 1 byte -128 to 127 byte a = 10;

short 2 bytes -32,768 to 32,767 short b = 200;

int 4 bytes -2,147,483,648 to 2,147,483,647 int c = 1000;

long 8 bytes Very large range long d = 100000L;

🔷 4. Floating-Point Types

Used to store numbers with decimals.


Data Type Size Example

float 4 bytes float f = 2.5f;

double 8 bytes double d = 3.14159;

Note: Always suffix float with f or F.

🔷 5. Character Type

Represents a single character using Unicode.

Data Type Size Example

char 2 bytes char ch = 'A';

Supports special characters like '\n', '\t', etc.

🔷 6. Boolean Type

Used to store truth values.

Data Type Size Values

boolean 1 bit true, false

Example:

boolean isJavaFun = true;

🔶 7. Java Literals

A literal is a constant value assigned to a variable.

Types of Literals:

Literal Type Example Description

Integer 10, 0x1A, 075 Decimal, Hexadecimal, Octal

Floating Point 3.14, 2.0f Default is double unless suffixed with f

Boolean true, false No other values allowed

Character 'A', '1', '\n' Must be enclosed in single quotes

String "Hello" Must be enclosed in double quotes

🔶 8. Type Conversion and Casting

🔸 Type Conversion (Widening Conversion)

Automatic conversion from lower to higher data type.

Example:

int a = 10;
double b = a; // int to double (automatic)

🔸 Type Casting (Narrowing Conversion)

Manual conversion from higher to lower data type using casting syntax.

Syntax:

dataType variable = (dataType) value;

Example:

double x = 10.5;

int y = (int) x; // y = 10

🔶 9. Automatic Type Promotion in Expressions

 During expressions, smaller data types are automatically promoted to larger data types.

 This happens to prevent data loss or overflow.

Rules:

1. If one operand is double, the entire expression is promoted to double.

2. byte, short, and char are promoted to int during arithmetic operations.

Example:

byte a = 10;

byte b = 20;

int result = a + b; // a and b are promoted to int

Another example:

int x = 10;

float y = 5.5f;

float z = x + y; // int promoted to float

Concept Key Points

Variables Store values using declared types

Primitive Types 8 types: int, float, char, boolean, etc.

Literals Fixed values: "text", 100, 'A', true

Type Conversion Implicit (smaller → larger)

Type Casting Explicit (larger → smaller)

Auto Type Promotion Applied in mixed-type expressions


Let me know how you'd like to use this content!

🔹 1. Operators in Java

Arithmetic Operators:
Used to perform basic mathematical operations:

Operator Description Example (a=10, b=5) Result

+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division a/b 2

% Modulus (Remainder) a % b 0

int a = 10, b = 3;

System.out.println("Addition: " + (a + b)); // 13

System.out.println("Subtraction: " + (a - b)); // 7

System.out.println("Multiplication: " + (a * b)); // 30

System.out.println("Division: " + (a / b)); // 3

System.out.println("Modulus: " + (a % b)); // 1

Increment & Decrement Operators:

Operator Description Example Result

++ Increment ++a or a++ 11

-- Decrement --a or a-- 9

 ++a (pre-increment): Increments and then uses value.

 a++ (post-increment): Uses value, then increments.

int x = 5;

System.out.println("Post-increment: " + (x++)); // 5

System.out.println("Now x: " + x); // 6

int y = 5;

System.out.println("Pre-increment: " + (++y)); // 6

Bitwise Operators:

Used for binary-level operations.

Operator Meaning Example Result

& AND 5&3 1


Operator Meaning Example Result

` ` OR `5

^ XOR 5^3 6

~ Complement ~5 -6

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

int m = 5; // 0101

int n = 3; // 0011

System.out.println("AND: " + (m & n)); // 0001 = 1

System.out.println("OR: " + (m | n)); // 0111 = 7

System.out.println("XOR: " + (m ^ n)); // 0110 = 6

System.out.println("NOT: " + (~m)); // bitwise NOT

System.out.println("Left Shift: " + (m << 1)); // 1010 = 10

System.out.println("Right Shift: " + (m >> 1)); // 0010 = 2

Relational Operators:

Used to compare values.

Operator Meaning Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater or equal a >= b

<= Less or equal a <= b

int a = 10, b = 20;

System.out.println(a > b); // false

System.out.println(a <= b); // true

System.out.println(a == b); // false

Boolean Logical Operators:

Operate on boolean values:


Operator Meaning Example

&& Logical AND a > 10 && b < 5

` `

! Logical NOT !true → false

boolean x = true, y = false;

System.out.println(x && y); // false

System.out.println(x || y); // true

System.out.println(!x); // false

Operator Precedence:

Defines the order of execution.


Example (from highest to lowest):

1. ()

2. ++, --

3. *, /, %

4. +, -

5. <, >, <=, >=

6. ==, !=

7. &&, ||

8. =

int result = 10 + 5 * 2; // Multiplication happens first

System.out.println(result); // Output: 20

Use parentheses to control precedence:

int result = (10 + 5) * 2; // Output: 30

🔹 2. Control Statements

Java’s Selection Statements:

Used for decision making.

if Statement:

 if (a > b) {

 System.out.println("a is greater");

 }
if-else:

 if (a > b)

 System.out.println("a is greater");

 else

 System.out.println("b is greater");

else if Ladder:

 if (a > b) {...}

 else if (a == b) {...}

 else {...}

int num = 10;

if (num > 0) {

System.out.println("Positive number");

} else if (num < 0) {

System.out.println("Negative number");

} else {

System.out.println("Zero");

switch Statement:

 switch(choice) {

 case 1: System.out.println("Option 1"); break;

 case 2: System.out.println("Option 2"); break;

 default: System.out.println("Invalid");

 }

int day = 2;

switch (day) {

case 1: System.out.println("Sunday"); break;

case 2: System.out.println("Monday"); break;

default: System.out.println("Invalid");

}
Iteration Statements (Loops):

for Loop:

 for (int i = 0; i < 5; i++) {

 System.out.println(i);

 }

while Loop:

 int i = 0;

 while (i < 5) {

 System.out.println(i);

 i++;

 }

do-while Loop:

 int i = 0;

 do {

 System.out.println(i);

 i++;

 } while (i < 5);

Jump Statements:

 break – exits the loop or switch

 continue – skips current iteration and moves to next

 return – exits from method and optionally returns a value

for (int i = 1; i <= 10; i++) {

if (i == 5)

break; // exits loop

System.out.println(i);

for (int i = 1; i <= 5; i++) {

if (i == 3)

continue; // skips 3
System.out.println(i);

🔹 3. Arrays in Java

1D Array (One-dimensional):

int[] numbers = {10, 20, 30, 40};

System.out.println(numbers[2]); // Output: 30

Or:

int[] marks = new int[5];

marks[0] = 90;

int[] arr = {10, 20, 30, 40};

for (int i = 0; i < arr.length; i++) {

System.out.println("Element at index " + i + ": " + arr[i]);

2D Array (Two-dimensional):

int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};

System.out.println(matrix[1][2]); // Output: 6

Or:

int[][] arr = new int[2][3];

arr[0][0] = 10;

code: int[][] matrix = {

{1, 2, 3},

{4, 5, 6}

};

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

Demonstrate All above Concepts

public class JavaBasicsDemo {

public static void main(String[] args) {

// Arithmetic and relational operators

int a = 10, b = 5;

System.out.println("Addition: " + (a + b));

System.out.println("Greater: " + (a > b));

// Bitwise

System.out.println("Bitwise AND: " + (a & b));

// Logical

boolean x = true, y = false;

System.out.println("Logical AND: " + (x && y));

// Control Statements

if (a > b) {

System.out.println("a is greater");

for (int i = 1; i <= 3; i++) {

if (i == 2) continue;

System.out.println("Loop i: " + i);

// Arrays
int[] oneD = {1, 2, 3};

for (int val : oneD) {

System.out.println("1D Value: " + val);

int[][] twoD = {{1, 2}, {3, 4}};

for (int i = 0; i < twoD.length; i++) {

for (int j = 0; j < twoD[i].length; j++) {

System.out.print(twoD[i][j] + " ");

System.out.println();

Here is a complete beginner-friendly explanation of the topic:

📘 Introduction to Classes in Java


🔹 1. Class Fundamentals

In Java, everything revolves around classes and objects.


A class is a blueprint for creating objects. It defines:

 Fields (attributes/data members): Variables that hold the data.

 Methods (functions/behaviors): Code that defines the behavior of the object.

✅ Example:

class Student {

// Fields (data members)

int rollNo;

String name;

// Method (behavior)

void display() {

System.out.println("Roll No: " + rollNo);

System.out.println("Name: " + name);

🔹 2. Declaring Object and Reference Variable

A class by itself does not create memory. To use it, we must create an object.

✅ Syntax to Create Object:

ClassName objectName = new ClassName();

 objectName is the reference variable

 new ClassName() creates an instance (object) of the class

✅ Example:

Student s1 = new Student(); // s1 is a reference to a Student object

🔹 3. Introducing Methods

A method defines an action or behavior for the object. Methods can:

 Take parameters

 Return values

 Perform logic or calculations

✅ Method Syntax:

returnType methodName(parameterList) {
// method body

🔹 Full Example Program:

// Define the class

class Student {

// Fields

int rollNo;

String name;

// Method to set data

void setData(int r, String n) {

rollNo = r;

name = n;

// Method to display data

void display() {

System.out.println("Roll No: " + rollNo);

System.out.println("Name: " + name);

// Main class

public class Main {

public static void main(String[] args) {

// Create object

Student s1 = new Student(); // reference variable 's1'

// Call method to set data

s1.setData(101, "Aman");

// Call method to display data

s1.display();
}

🔍 Output:

Roll No: 101

Name: Aman

✅ Summary Table:

Concept Description

Class Blueprint or template to create objects

Object Instance of a class

Reference Variable Points to the memory location of the object

Method Function inside a class that performs operations

Let me know if you want to explore:

 Constructors

 Static methods

 Multiple objects

 Real-world analogy (like student, car, bank account)


I can add that next!

What is a Constructor?

A constructor in Java is a special method used to initialize objects.

 It has the same name as the class.

 It does not have a return type (not even void).

 It is automatically called when an object is created using the new keyword.


Key Characteristics of Constructors

1. Name must be the same as the class.

2. Cannot have a return type.

3. Automatically executed at object creation.

4. Can be overloaded (multiple constructors in a class).

Types of Constructors

1. Default Constructor (Compiler-Provided)

If you do not define any constructor, Java provides a default one that does nothing.

class Car {

String brand;

public class DefaultConstructorExample {

public static void main(String[] args) {

Car c1 = new Car(); // Calls default constructor

System.out.println(c1.brand); // null (not initialized)

2. No-Argument Constructor (User-Defined)

class Car {

String brand;

// No-arg constructor

Car() {

brand = "Unknown";

System.out.println("Car object created!");

public class NoArgConstructorExample {

public static void main(String[] args) {


Car c1 = new Car(); // Calls constructor

System.out.println(c1.brand);

Output:

Car object created!

Unknown

3. Parameterized Constructor

class Car {

String brand;

int year;

// Parameterized constructor

Car(String b, int y) {

brand = b;

year = y;

void display() {

System.out.println(brand + " - " + year);

public class ParameterizedConstructorExample {

public static void main(String[] args) {

Car c1 = new Car("Toyota", 2020);

Car c2 = new Car("Honda", 2022);

c1.display();

c2.display();

Output:
Toyota - 2020

Honda - 2022

Constructor Overloading

You can have multiple constructors with different parameter lists.

class Student {

String name;

int age;

// No-argument constructor

Student() {

name = "Unknown";

age = 0;

// Parameterized constructor

Student(String n, int a) {

name = n;

age = a;

void display() {

System.out.println(name + " - " + age);

public class ConstructorOverloadingExample {

public static void main(String[] args) {

Student s1 = new Student();

Student s2 = new Student("Jaspreet", 25);

s1.display();

s2.display();

}
}

Output:

Unknown - 0

Jaspreet - 25

You might also like