[Go to site: main page, start]

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

Java Programming Basics and Concepts

The document provides comprehensive notes on Java programming, covering its key features, such as being platform-independent, object-oriented, and secure. It explains essential concepts including JDK, JRE, keywords, identifiers, variables, methods, classes, objects, and the principles of object-oriented programming. Additionally, it discusses inheritance, constructors, and the use of 'this' and 'super' keywords, providing examples and interactive tasks for better understanding.

Uploaded by

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

Java Programming Basics and Concepts

The document provides comprehensive notes on Java programming, covering its key features, such as being platform-independent, object-oriented, and secure. It explains essential concepts including JDK, JRE, keywords, identifiers, variables, methods, classes, objects, and the principles of object-oriented programming. Additionally, it discusses inheritance, constructors, and the use of 'this' and 'super' keywords, providing examples and interactive tasks for better understanding.

Uploaded by

yalamanchili741
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming Notes

1 Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle). It was released in 1995 and is known for
being:

• Platform Independent: “Write once, run anywhere” — thanks to the Java


Virtual Machine (JVM), compiled Java code can run on any platform.

• Object-Oriented: Everything is based on classes and objects.

• Secure & Robust: Has built-in features for memory management, excep-
tion handling, and security.

• Multithreaded: Supports multithreaded programming (multiple threads


of execution).

• Portable: Java programs can move easily from one system to another.

2 JDK, JRE, JVM


2.1 So Here’s the Real Difference

Scenario JDK Needed? JRE Enough? Why?


Writing + Compiling Java code YES ×NO You need java
Just Running already-compiled .class files ×NO YES JVM in JRE can

2.2 Example Use Case


• Developer Machine: You write code → You need JDK (to compile).

• Client/User Machine: You give them .class or .jar → They only need
JRE (to run it).

Interactive Quiz: What do you need to compile Java code?


a) JRE b) JDK c) JVM
Answer: b) JDK (because it includes javac).

JDK is Dependent - To compile .java to .class


JVM is platform independent in behaviour because same .class file runs on
any OS.
JVM is also dependent software is 1different for each OS
3 Keywords
Keywords are a set of predefined or reserved words for which the meaning is
predefined by developers of the Java programming language.

• In Java, there are 51 keywords, all written in lower case.

• Examples: class, public, static, void.

Interactive Task: List 5 Java keywords you’ve encountered. Check if they’re


all lowercase!
Example Answer: int, for, if, return, new.

4 Identifiers
Identifiers are the names that we give to the class and methods in order to iden-
tify them.
1 class MyClass { // MyClass is an identifier
2 void myMethod() { // myMethod is an identifier
3 }
4 }

Rules for Identifiers:

• Must start with a letter, _, or $.

• Can include letters, digits, _, or $.

• Cannot be a keyword.

• Case-sensitive (e.g., myVar ̸= MyVar).

Interactive Question: Is 2myVar a valid identifier? Why or why not?


Answer: No, because it starts with a digit.

5 Variables
A variable is a container which holds the value while the Java program is exe-
cuted. A variable is the name of memory and is assigned with a datatype.

5.1 Architecture of Datatypes


1. Numeric:

• byte (8-bit, -128 to 127)


• short (16-bit, -32,768 to 32,767)
• int (32-bit, −231 to 231 − 1)
• long (64-bit, −263 to 263 − 1)
• float (32-bit, floating-point)

2
• double (64-bit, floating-point)

2. Non-Numeric:

• char (16-bit, Unicode character)


• boolean (true/false)

3. Non-Primitive:

• Classes, Arrays, Interfaces, Strings, etc.

1 int age = 25; // Numeric


2 char grade = ’A’; // Non-Numeric
3 String name = "John"; // Non-Primitive

Interactive Task: Declare a variable for storing a person’s salary (use an ap-
propriate datatype).
Example Answer: double salary = 50000.50;

6 Methods
Methods are a set of instructions written by the user to perform a specific task.

6.1 Example with Explanation

1 public static void main(String[] args) {


2 [Link]("Hello, World!");
3 }

• public: Access modifier (method is accessible from everywhere).

• static: Belongs to the class, not an object.

• void: Return type (method returns nothing).

• main: Method name (entry point of the program).

• String[] args: Parameter (array of Strings for command-line arguments).

Interactive Question: What does the void keyword signify in a method?


Answer: It means the method does not return any value.

7 Class
A class is a Java-defined block which will hold the state and behavior of the object
together. With respect to Java, state refers to variables, and behavior refers to
methods.

3
1 class Car {
2 String model; // State (variable)
3 void drive() { // Behavior (method)
4 [Link](model + " is driving.");
5 }
6 }

Interactive Task: Create a class Student with a variable name and a method
study().
Example Answer:
1 class Student {
2 String name;
3 void study() {
4 [Link](name + " is studying.");
5 }
6 }

8 Object
Objects are real-world entities having their own state and behavior, where state
refers to characteristics and behavior refers to functionality.
1 Car myCar = new Car(); // Object creation
2 [Link] = "Toyota"; // Setting state
3 [Link](); // Calling behavior

Interactive Question: What is the difference between a class and an object?


Answer: A class is a blueprint; an object is an instance of that blueprint.

9 Static in Java
The keyword static means "belonging to the class rather than any object."

9.1 Static Variable (Class Variable)


Definition: A variable declared with the static keyword is called a static vari-
able. It is shared among all instances (objects) of the class.
1 class Student {
2 static String college = "ABC College"; // static variable
3 String name; // non-static (instance variable)
4

5 Student(String name) {
6 [Link] = name;
7 }
8

9 void display() {
10 [Link](name + " - " + college);
11 }
12 }

4
Key Points:
• Stored in method area, not in heap.

• Only one copy exists regardless of how many objects are created.

• Can be accessed using class name: [Link].

9.2 Static Method


Definition: A method declared with static is shared by the class and can be
called without creating an object.
1 class MyClass {
2 static void show() {
3 [Link]("Static Method Called");
4 }
5

6 public static void main(String[] args) {


7 [Link](); // no need to create object
8 }
9 }

Key Rules:
• Can access static variables directly.

• ×Cannot access non-static (instance) variables or methods directly.

• Belongs to class, not object.

9.3 Static Block


Definition: A block that runs once when the class is loaded into memory. Used
to initialize static data.
1 class Test {
2 static int x;
3

4 static {
5 [Link]("Static Block Executed");
6 x = 10;
7 }
8

9 public static void main(String[] args) {


10 [Link]("Main Method");
11 [Link]("x = " + x);
12 }
13 }

Key Points:
• Executes before the main() method, only once.

• Mainly used to initialize static variables.

5
10 Non-Static (Instance)
10.1 Instance Variable (Non-Static Variable)
Definition: A variable that is not declared static is unique for each object (be-
longs to the object).
1 class Person {
2 String name; // instance variable
3

4 Person(String name) {
5 [Link] = name;
6 }
7

8 void show() {
9 [Link](name);
10 }
11 }

Key Points:

• Stored in the heap (inside the object).

• Each object gets its own copy.

• Can be accessed inside non-static methods directly.

10.2 Instance Method (Non-Static Method)


Definition: A method that operates on object (instance) data. It can access both
static and non-static members.
1 class Car {
2 String model; // instance variable
3

4 void display() {
5 [Link]("Model: " + model);
6 }
7 }

Key Points:

• Requires an object to be called.

• Can access:

– Non-static (instance) variables/methods


– Static variables/methods

10.3 Instance Block (Non-Static Block)


Definition: Block of code without any name or method, used to initialize in-
stance data. Runs every time before constructor is called.

6
1 class Example {
2 {
3 [Link]("Instance Block Called");
4 }
5

6 Example() {
7 [Link]("Constructor Called");
8 }
9

10 public static void main(String[] args) {


11 Example e1 = new Example();
12 Example e2 = new Example();
13 }
14 }

Key Points:

• Executes every time an object is created.

• Runs before constructor.

• Used to initialize common logic for all constructors.

11 Static vs Non-Static Summary Table

Feature Static Non-Static (Instance)


Belongs to Class Object
Memory Method area Heap
Accessed by [Link] or object Object reference only
Variables Shared among all objects Separate copy for each object
Methods Cannot access instance members Can access static & instance members
Initialization Static block (once, class loading) Instance block (every object creation)
Constructor ×Not needed Used to initialize objects
Bonus Tip:

• Can static method call non-static method?


×No — because static method does not know which object’s instance it should
call.
But, a non-static method can call static ones — since static belongs to the
class.

Interactive Task: Write a class with a static variable to track the number of
objects created and a static method to display it.
Example Answer:
1 class Tracker {
2 static int objectCount = 0;
3 Tracker() {
4 objectCount++;

7
5 }
6 static void showCount() {
7 [Link]("Objects created: " + objectCount);
8 }
9 }

12 Constructor
Constructors are special methods which have the same name as the class name.

• Used to initialize non-static variables.

• Do not have a return type.

• Executed automatically when an object is created.

1 class Book {
2 String title;
3 Book() { // Constructor
4 title = "Unknown";
5 }
6 }

13 Constructor Overloading
Having multiple constructors in the same class which differ in their arguments,
parameters, and signature. The signature should differ in one of three ways:

• Length (number of parameters)

• Type (data types of parameters)

• Order (sequence of parameter types)

Note: Constructors do not have a return type. If a return type is specified, it


is treated as a non-static method.
1 class Student {
2 String name;
3 int age;
4 Student() { // No-arg constructor
5 name = "Unknown";
6 age = 0;
7 }
8 Student(String n, int a) { // Parameterized constructor
9 name = n;
10 age = a;
11 }
12 }

8
Interactive Task: Create a class Rectangle with overloaded constructors for
default and parameterized dimensions.
Example Answer:
1 class Rectangle {
2 double length, width;
3 Rectangle() {
4 length = 1.0;
5 width = 1.0;
6 }
7 Rectangle(double l, double w) {
8 length = l;
9 width = w;
10 }
11 }

14 OOPs (Object-Oriented Programming)


OOP is a programming paradigm based on the concept of objects, which contain
data (attributes) and methods (behavior). Key principles:

1. Encapsulation

2. Inheritance

3. Polymorphism

4. Abstraction

Interactive Question: Name the four pillars of OOP.


Answer: Encapsulation, Inheritance, Polymorphism, Abstraction.

15 Inheritance
Inheritance is the process of deriving properties of one class to another class. It
is an IS-A relationship (e.g., a car IS-A vehicle).

15.1 HAS-A Relationship


• Represents composition (e.g., a car HAS-A an engine).

• Achieved by creating an instance of one class as a field in another.

15.2 Types of Inheritance


1. Single: One child class inherits from one parent.

2. Multilevel: Class B inherits from A, C inherits from B.

3. Hierarchical: Multiple classes inherit from one parent.

9
15.3 Why Multiple Inheritance Is Not Allowed (for Classes)
• Problem: Ambiguity (diamond problem). If two parent classes have the
same method, which one does the child inherit?

• Solution: Java allows multiple inheritance via interfaces, not classes. In-
terfaces avoid this issue since they have only method signatures, not imple-
mentations.

15.4 Why Cyclic Inheritance Is Not Allowed


Cyclic inheritance (e.g., A inherits from B, B inherits from A) creates an infinite
loop, making class definition impossible. Java’s type system prevents this to en-
sure compile-time safety.
1 class Vehicle {
2 void move() {
3 [Link]("Vehicle is moving.");
4 }
5 }
6 class Car extends Vehicle {
7 void speed() {
8 [Link]("Car speed: 100 km/h");
9 }
10 }

Interactive Task: Create a hierarchical inheritance example with a Shape


class and two child classes Circle and Square.
Example Answer:
1 class Shape {
2 void draw() {
3 [Link]("Drawing shape.");
4 }
5 }
6 class Circle extends Shape {
7 void draw() {
8 [Link]("Drawing circle.");
9 }
10 }
11 class Square extends Shape {
12 void draw() {
13 [Link]("Drawing square.");
14 }
15 }

16 This Keyword
The this keyword is used to refer to the current object.
• Using this is optional when local and non-static variables have different
names.

10
• It is mandatory when local and non-static variables have the same name.

1 class Student {
2 String name; // Non-static variable
3 Student(String name) { // Constructor with same-name parameter
4 [Link] = name; // Refers to instance variable
5 }
6 void display() {
7 String name = "Local"; // Local variable
8 [Link]("Instance name: " + [Link]);
9 [Link]("Local name: " + name);
10 }
11 }

17 Super Keyword
The super keyword is used to refer to the immediate super class.
• Mandatory when subclass and superclass members have the same name.

17.1 Combined Example (this and super)

1 class Person {
2 String name = "Parent";
3 Person() {
4 [Link]("Person constructor.");
5 }
6 }
7 class Student extends Person {
8 String name = "Child";
9 Student() {
10 super(); // Calls superclass constructor
11 [Link]("Student constructor.");
12 }
13 void display() {
14 [Link]("This name: " + [Link]); // Child
15 [Link]("Super name: " + [Link]); // Parent
16 }
17 }

Interactive Task: What does [Link] refer to in the above example?


Answer: The name field of the Student object.

18 Constructor Calling
Calling one constructor from another constructor in the same class.
• The call must be the first statement in the constructor.

• Done using this(<parameters>).

11
18.1 Why Use It?
Reduces code duplication by reusing constructor logic.
1 class Employee {
2 int id;
3 String name;
4 Employee(int id) {
5 this(id, "Unknown"); // Calls another constructor
6 }
7 Employee(int id, String name) {
8 [Link] = id;
9 [Link] = name;
10 }
11 }

Interactive Task: Write a class Box with two constructors, one calling the
other.
Example Answer:
1 class Box {
2 double length, width;
3 Box() {
4 this(10.0, 10.0); // Calls parameterized constructor
5 }
6 Box(double l, double w) {
7 length = l;
8 width = w;
9 }
10 }

19 Constructor Chaining
Calling a superclass constructor from a subclass constructor is called construc-
tor chaining.
• Implicit Chaining: Occurs when the superclass has a no-argument con-
structor (called automatically).

• Explicit Chaining: Occurs when the superclass has a parameterized con-


structor, requiring super(...).

1 class Animal {
2 String species;
3 Animal(String s) {
4 species = s;
5 }
6 }
7 class Dog extends Animal {
8 String breed;
9 Dog(String s, String b) {
10 super(s); // Explicit chaining

12
11 breed = b;
12 }
13 }

Interactive Question: What happens if super() is not called in a subclass


constructor?
Answer: Java implicitly calls the superclass’s no-arg constructor. If it doesn’t ex-
ist, a compilation error occurs.

20 Encapsulation
Encapsulation is the process of hiding the internal details of a class and only
exposing necessary parts using getters and setters.
1 public class Account {
2 private double balance;
3 public double getBalance() {
4 return balance;
5 }
6 public void setBalance(double b) {
7 if (b > 0) {
8 balance = b;
9 }
10 }
11 }

Interactive Task: Why use encapsulation?


Answer: To protect data integrity and control access.

21 Java Bean Class


Writing a public class with private data members, public constructors, getters,
and setters is known as a Bean Class.
1 public class User {
2 private String name;
3 private int age;
4 public User() { // Default constructor
5 }
6 public User(String n, int a) {
7 name = n;
8 age = a;
9 }
10 public String getName() { return name; }
11 public void setName(String n) { name = n; }
12 public int getAge() { return age; }
13 public void setAge(int a) { age = a; }
14 }

Interactive Task: Write a Java Bean class for a Product with id and price.
Example Answer:

13
1 public class Product {
2 private int id;
3 private double price;
4 public Product() {}
5 public Product(int i, double p) {
6 id = i;
7 price = p;
8 }
9 public int getId() { return id; }
10 public void setId(int i) { id = i; }
11 public double getPrice() { return price; }
12 public void setPrice(double p) { price = p; }
13 }

22 Abstraction
Abstraction is the process of hiding internal implementation details and showing
only the essential features to the user.

22.1 Abstract Class (Partial Abstraction)


A restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).

22.2 Abstract Method


Can only be used in an abstract class and does not have a body. The body is
provided by the subclass (inherited from).
1 abstract class Shape {
2 abstract void draw();
3 }
4 class Circle extends Shape {
5 void draw() {
6 [Link]("Drawing circle.");
7 }
8 }

22.3 Can We Use Constructors in Abstract Classes? Why?


• Yes, constructors can be used in abstract classes.

• They can initialize common fields shared by all subclasses.

• Why?: To enforce consistent initialization logic for all derived classes.

1 abstract class Vehicle {


2 String model;
3 Vehicle(String m) {

14
4 model = m;
5 }
6 }
7 class Car extends Vehicle {
8 Car(String m) {
9 super(m);
10 }
11 }

Interactive Question: Why can’t we instantiate an abstract class?


Answer: Because it may contain incomplete (abstract) methods.

23 Polymorphism
In Java, polymorphism refers to the ability of an object to take on many forms
— the same method name can behave differently based on the object.

23.1 Compile-Time Polymorphism (Method Overloading)


Same method name, but different number/types of parameters in the same class.

23.2 Run-Time Polymorphism (Method Overriding)


Same method name and parameters, but defined in parent and child classes.

23.3 Why Static vs. Dynamic Called?


• Static (Compile-Time): Resolved at compile time based on method signa-
tures (overloading).

• Dynamic (Run-Time): Resolved at run time based on the object’s type (over-
riding).

1 class Animal {
2 void sound() {
3 [Link]("Generic sound.");
4 }
5 }
6 class Dog extends Animal {
7 void sound() { // Overriding
8 [Link]("Bark.");
9 }
10 void sound(int volume) { // Overloading
11 [Link]("Bark at volume: " + volume);
12 }
13 }

Interactive Task: What’s an example of method overloading?


Example Answer:

15
1 class Calculator {
2 int add(int a, int b) { return a + b; }
3 int add(int a, int b, int c) { return a + b + c; }
4 }

24 Interface
An interface is a 100% abstract type that contains only abstract methods (or de-
fault/static methods since Java 8).

24.1 Types of Interface


1. Normal: Contains only abstract methods.

2. Functional Interface: Has exactly one abstract method (e.g., Runnable).

3. Marker Interface: Has no methods (e.g., Serializable, Cloneable).

24.2 Difference Between Abstract Class & Interface

Feature Interface Abstract Class


Methods Abstract, Default, Static (since Java 8) Abstract & Non-Abstract
Inheritance Multiple (implements) Single (extends)
Fields Only public, static, & final Can have any access modifier
Constructor No Yes

24.3 Why Default/Static Methods in Interfaces?


• Default Methods: Allow interfaces to evolve without breaking existing im-
plementations.

• Static Methods: Provide utility methods related to the interface.

24.4 Why Constructors in Abstract Classes but Not in Interfaces?


• Abstract Classes: Can have fields needing initialization, and subclasses
need to call the constructor to set them up.

• Interfaces: Cannot be instantiated and have no instance fields, so construc-


tors are unnecessary.

1 interface Drivable {
2 void drive();
3 default void stop() { // Default
4 [Link]("Stopping.");
5 }
6 static void honk() { // Static
7 [Link]("Honk!");

16
8 }
9 }
10 class Car implements Drivable {
11 public void drive() {
12 [Link]("Car driving.");
13 }
14 }

Interactive Task: Create an interface Flyable with an abstract method fly()


and a default method land().
Example Answer:
1 interface Flyable {
2 void fly();
3 default void land() {
4 [Link]("Landing.");
5 }
6 }

25 Final Interactive Quiz


1. What is the purpose of the static keyword?
a) Refer to instance b) Refer to class c) Refer to superclass
Answer: b) Refer to class

2. Why is multiple inheritance not allowed in Java classes?


Answer: To avoid the diamond problem (ambiguity in method resolution).

3. What’s the output of this code?

1 class Test {
2 static int x;
3 static { x = 10; }
4 public static void main(String[] args) {
5 [Link](x);
6 }
7 }

Answer: 10

17

You might also like