Unit 1 of 4 · B.Sc IT Sem 5

Unit 1: Java fundamentals

Programming in Java notes · PTU syllabus (BSIT502/BSBC502)

6 min read10 topics10 exam questions
On this page
  1. Unit summary
  2. The object-oriented paradigm
  3. Java history and features
  4. Java vs C and C++
  5. The Java environment
  6. Structure of a simple Java program
  7. Tokens and statements
  8. Constants, variables and data types
  9. Operators and expressions
  10. Decision making and branching
  11. Looping statements
  12. Key terms
  13. Quick revision
  14. Important questions

Unit summary

Java is a platform-independent, object-oriented language used for enterprise software, Android apps and web back ends. This unit covers the object-oriented paradigm, Java's history and features, how it differs from C and C++, the Java environment, the structure of a simple program, tokens, constants, variables, data types, operators and expressions, and decision-making, branching and looping statements.

After this unit you can

  • Explain the OOP paradigm and Java's features
  • Compare Java with C and C++ and describe the Java environment
  • Write simple Java programs using tokens, variables, data types and operators
  • Use decision-making, branching and looping statements

PTU syllabus topics

  • Object-oriented paradigm basics
  • Java history and features
  • differences from C/C++
  • Java environment
  • simple Java program structure
  • tokens and statements
  • constants/variables/data types
  • operators and expressions
  • decision making/branching/looping statements
1

Topic 1

The object-oriented paradigm

Object-oriented programming organises software around objects that combine data and behaviour. Its four pillars are encapsulation, inheritance, polymorphism and abstraction.

Key termsBasic OOP concepts
Object
Entity with state (fields) and behaviour (methods)
Class
Blueprint from which objects are created
Encapsulation
Binding data and methods; hiding data with private access
Abstraction
Showing essential features, hiding details
Inheritance
A class acquiring properties of another
Polymorphism
One name, many forms — overloading and overriding
Message passing
Objects communicate by calling methods
  • Benefits: reusability, modularity, easier maintenance, data security, real-world modelling.

Example

OOP with a bank account: a class Account has data (balance) and methods (deposit, withdraw). Balance is private (encapsulation); SavingsAccount extends Account (inheritance); withdraw behaves differently for savings and current accounts (polymorphism).

Exam tip

Explain each pillar with one small example.

2

Topic 2

Java history and features

Java's key features are simple, object-oriented, platform-independent (write once, run anywhere), secure, robust, multithreaded, portable and high performance (with JIT compilation).

ProcessHistory of Java
  1. 1

    1991

    James Gosling's team at Sun Microsystems starts the Green project; language named Oak

  2. 2

    1995

    Renamed Java; released with "write once, run anywhere"

  3. 3

    2006–07

    Open-sourced as OpenJDK

  4. 4

    2010

    Oracle acquires Sun

  5. 5

    2014

    Java 8: lambdas and streams

  6. 6

    2018 onward

    Six-monthly releases; long-term support versions 11, 17, 21 and 25

Key termsFeatures of Java
Simple
No pointers or operator overloading
Object-oriented
Everything inside classes
Platform independent
Compiled to bytecode that runs on any JVM
Secure
No explicit pointers, bytecode verifier, sandbox
Robust
Strong typing, exception handling, garbage collection
Multithreaded
Built-in threads
Distributed and dynamic
Networking libraries; classes loaded at run time
High performance
Just-in-time (JIT) compilation

Example

Platform independence: a program compiled on Windows produces bytecode (.class). The same .class file runs on Linux or macOS because each has its own JVM that interprets the bytecode.

Exam tip

The JVM makes Java platform-independent; bytecode is the key.

3

Topic 3

Java vs C and C++

FeatureCC++Java
ParadigmProceduralProcedural and OOPPure OOP (except primitives)
PlatformCompiled to machine codeCompiled to machine codeBytecode on the JVM
PointersYesYesNo explicit pointers
Multiple inheritance—Through classesThrough interfaces only
Operator overloadingNoYesNo
Memory managementmalloc and freenew and deleteAutomatic garbage collection
Global variables, goto, structuresYesYesNo
Header filesYesYesNo — uses packages and import

Example

Memory management compared: in C, a programmer must call free() after malloc(); forgetting causes memory leaks. In Java, objects are created with new and the garbage collector frees unused objects automatically.

Exam tip

Java has no pointers, no multiple inheritance of classes (it uses interfaces instead), and automatic garbage collection.

4

Topic 4

The Java environment

The JDK (development kit) contains tools such as javac and java; the JRE (runtime environment) contains the JVM and libraries needed to run programs.

ProcessCompile and run
  1. 1Write Hello.java
  2. 2javac Hello.java

    Compiler produces Hello.class (bytecode)

  3. 3java Hello

    JVM loads, verifies and runs bytecode

  4. 4JIT compiles hot code to machine code
Key termsJDK, JRE and JVM
JVM
Java Virtual Machine — executes bytecode; platform specific
JRE
JVM plus core libraries — needed to run programs
JDK
JRE plus development tools — javac, java, javadoc, jar, jdb

Exam tip

"Write once, run anywhere" in one line: javac turns source into bytecode, which is the same on every machine; each platform has its own JVM that runs that bytecode. The bytecode is portable; the JVM is not.

  • API: thousands of ready classes organised in packages — java.lang, java.util, java.io, java.awt, java.net.

Example

Compiling and running: javac Hello.java creates Hello.class (bytecode); java Hello starts the JVM, which loads and runs the bytecode and prints the output.

Exam tip

JDK = JRE + development tools; JRE = JVM + libraries.

5

Topic 5

Structure of a simple Java program

A Java program has an optional documentation section, package and import statements, and one or more classes. Execution starts at public static void main(String[] args).

java// Documentation section: program to greet a student
package college;                 // optional package statement
import java.util.Scanner;        // import statements

public class Hello {             // class definition; file must be Hello.java
    public static void main(String[] args) {   // entry point
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Welcome to SBS, " + name);
    }
}
  • main: public (accessible to the JVM), static (called without an object), void (returns nothing), String[] args (command-line arguments).

Example

Why main is static: the JVM calls main before any object exists, so main must be static (belong to the class). It is public so the JVM can access it, and void because it returns nothing.

Exam tip

Explain each word in public static void main(String[] args) — a frequent viva question.

6

Topic 6

Tokens and statements

Key termsJava tokens
Keywords
Reserved words — class, int, if, static (about 50)
Identifiers
Names of classes, variables, methods; start with a letter, _ or $
Literals
Constant values — 25, 3.14, 'A', "SBS", true
Operators
Symbols performing operations
Separators
( ) { } [ ] ; , .
  • Statements: expression statements, declarations, control statements, labelled statements, synchronisation statements, empty statements.

Example

Identifying tokens: in int total = marks + 10;, int is a keyword, total and marks are identifiers, 10 is a literal, = and + are operators, and ; is a separator.

Exam tip

The five token types: keywords, identifiers, literals, operators and separators.

7

Topic 7

Constants, variables and data types

Java has 8 primitive types — byte, short, int, long, float, double, char (2 bytes, Unicode) and boolean — and reference types (classes, arrays, interfaces). Constants are declared with final.

ClassificationJava data types
Data types
  • Primitive integer

    byte (1 byte), short (2), int (4), long (8)

  • Primitive floating

    float (4), double (8)

  • Primitive others

    char (2 bytes, Unicode), boolean (true or false)

  • Reference

    Classes, interfaces, arrays, String

Exam tip

Two literal traps: 3.5 is a double, so float f = 3.5; is a compile error — write 3.5f; and a whole number like 10 is an int, so a large value needs L — long n = 9000000000L;. A char is 2 bytes (Unicode), unlike 1 byte in C.

javafinal double PI = 3.14159;       // constant
int age = 19;                    // variable
long population = 1_400_000_000L;
float cgpa = 8.6f;
char grade = 'A';
boolean passed = true;
double avg = (double) 245 / 3;   // explicit casting
int x = 'A' + 1;                 // implicit widening: 66
var city = "Ludhiana";           // local type inference (Java 10+)
  • Variable kinds: local (inside methods), instance (per object), class or static (shared by all objects). Type conversion: widening is automatic (int → long → float → double); narrowing needs a cast.

Example

Type casting: double d = 9.7; int i = (int) d; gives i = 9 (explicit narrowing cast). int x = 5; double y = x; gives y = 5.0 (automatic widening).

Exam tip

char in Java is 2 bytes because it uses Unicode.

8

Topic 8

Operators and expressions

Key termsJava operators
Arithmetic
+ − × / % (multiplication is written with the asterisk symbol)
Relational
< <= > >= == !=
Logical
&&, the double-bar OR operator, !
Bitwise and shift
&, ^, ~, <<, >>, >>>
Assignment
= += −= and so on
Increment and decrement
++ and −−
Conditional
condition ? value1 : value2
instanceof
Checks an object's type

Example

Tracing operators: 17 / 5 gives 3 (integer division) and 17 % 5 gives 2, but 17.0 / 5 gives 3.4. With int a = 5; int b = a++ + ++a; — a++ uses 5 and makes a = 6, then ++a makes a = 7 and uses 7 — so b = 12 and a = 7. A cast truncates: (int) 9.8 is 9, not 10.

  • Precedence: unary > multiplicative > additive > shift > relational > equality > bitwise > logical > conditional > assignment. Integer division truncates (7 / 2 = 3); % gives the remainder.
9

Topic 9

Decision making and branching

Java provides if, if-else, else-if ladder, nested if, switch and the ternary operator (?:).

javaint marks = 72;
if (marks >= 75) System.out.println("Distinction");
else if (marks >= 60) System.out.println("First division");
else System.out.println("Pass");

int day = 3;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Other day");
}
String type = switch (day) {               // switch expression (Java 14+)
    case 6, 7 -> "Weekend";
    default -> "Weekday";
};

Example

Ternary operator: String result = (marks >= 40) ? "Pass" : "Fail"; — for marks = 35, result is "Fail". A switch on day can print the day name for values 1 to 7.

Exam tip

Remember break in each switch case to avoid fall-through.

10

Topic 10

Looping statements

javafor (int i = 1; i <= 10; i++) System.out.print(i * i + " ");   // squares

int n = 12345, sum = 0;
while (n > 0) { sum += n % 10; n /= 10; }                      // digit sum = 15

int k = 1;
do { System.out.println(k); k++; } while (k <= 3);             // runs at least once

int[] marks = {78, 85, 90};
for (int m : marks) System.out.println(m);                     // enhanced for

outer:
for (int i = 1; i <= 3; i++)
    for (int j = 1; j <= 3; j++) {
        if (i * j == 4) break outer;                            // labelled break
        if (j == 2) continue;
        System.out.println(i + "," + j);
    }

Key terms

Bytecode
Platform-independent code produced by javac
JVM
Virtual machine executing Java bytecode
JDK
Development kit with compiler and tools
Token
Smallest unit of a program
Type casting
Converting a value from one type to another

Quick revision

  • OOP concepts; Java history (Oak, Sun, Oracle); features.
  • Java vs C and C++.
  • javac → bytecode → JVM; JDK, JRE, JVM.
  • Program structure; main; tokens; eight primitive types; widening and narrowing.
  • Operators and precedence; if, switch, for, while, do-while, enhanced for, labelled break and continue.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.Why is Java platform independent?
  2. Q2.Distinguish JDK, JRE and JVM.
  3. Q3.Why is main declared static?
  4. Q4.Name the eight primitive data types of Java.
  5. Q5.Distinguish while and do-while.
  6. Q6.What is a labelled break?

Long-answer questions

  1. Q1.Explain the features of Java.
  2. Q2.Compare Java with C and C++.
  3. Q3.Explain the structure of a Java program and the Java environment.
  4. Q4.Explain the decision-making and looping statements of Java with examples.

Stuck on this unit?

Message SBS on WhatsApp for help with Programming in Java, or to ask about studying B.Sc IT at Synetic.

WhatsApp us